public void RunApplication(string[] args) { if (args.Length == 0) { Platform.Log(LogLevel.Error, "Name of data file to import must be supplied as first argument."); return; } try { using (StreamReader reader = File.OpenText(args[0])) { List <string> lines = null; while ((lines = ReadLines(reader, DEFAULT_BATCH_SIZE)).Count > 0) { using (PersistenceScope scope = new PersistenceScope(PersistenceContextType.Update)) { ((IUpdateContext)PersistenceScope.CurrentContext).ChangeSetRecorder.OperationName = this.GetType().FullName; Import(lines, (IUpdateContext)PersistenceScope.CurrentContext); scope.Complete(); } } } } catch (EntityValidationException e) { Log(LogLevel.Error, e.Message); } catch (Exception e) { Log(LogLevel.Error, e.ToString()); } }
protected sealed override void ImportCore(IEnumerable <IImportItem> items) { var enumerator = items.GetEnumerator(); for (var more = true; more;) { using (var scope = new PersistenceScope(PersistenceContextType.Update)) { var context = (IUpdateContext)PersistenceScope.CurrentContext; context.ChangeSetRecorder.OperationName = this.GetType().FullName; for (var j = 0; j < ItemsPerUpdateTransaction && more; j++) { more = enumerator.MoveNext(); if (more) { var item = enumerator.Current; var data = (TDataContract)Read(item.Read(), typeof(TDataContract)); Import(data, context); } } scope.Complete(); } } }
public void RunApplication(string[] args) { using (PersistenceScope scope = new PersistenceScope(PersistenceContextType.Update)) { ((IUpdateContext)PersistenceScope.CurrentContext).ChangeSetRecorder.OperationName = this.GetType().FullName; ImportFromPlugins((IUpdateContext)PersistenceScope.CurrentContext); scope.Complete(); } }
public object StartOperation(bool canCreateInstance) { using (StartOperationScope scope = new StartOperationScope(this)) { if (this.markedForCompletion) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InstanceNotFoundException(this.InstanceId)); } if (this.instance == null) { if (!TryActivateInstance(canCreateInstance)) { using (PersistenceScope persistenceScope = new PersistenceScope( this.saveStateInOperationTransaction, this.clonedTransaction)) { if (this.lockingProvider != null) { this.instance = this.lockingProvider.Load(this.operationTimeout, true); } else { this.instance = this.provider.Load(this.operationTimeout); } if (DiagnosticUtility.ShouldTraceInformation) { string traceText = SR2.GetString(SR2.ServiceDurableInstanceLoadedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False"); TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ServiceDurableInstanceLoaded, SR.GetString(SR.TraceCodeServiceDurableInstanceLoaded), new StringTraceRecord("DurableInstanceDetail", traceText), this, null); } } this.existsInPersistence = true; } } scope.Complete(); } Fx.Assert( this.instance != null, "Instance should definitely be non-null here or we should have thrown an exception."); return(this.instance); }
public void RunApplication(string[] args) { SetupCommandLine cmdLine = new SetupCommandLine(); try { cmdLine.Parse(args); using (PersistenceScope scope = new PersistenceScope(PersistenceContextType.Update)) { ((IUpdateContext)PersistenceScope.CurrentContext).ChangeSetRecorder.OperationName = GetType().FullName; // import authority tokens AuthorityTokenImporter tokenImporter = new AuthorityTokenImporter(); IList <AuthorityToken> allTokens = tokenImporter.ImportFromPlugins((IUpdateContext)PersistenceScope.CurrentContext); // create the sys admin group, which has all tokens assigned by default string[] tokenStrings = CollectionUtils.Map <AuthorityToken, string, List <string> >(allTokens, t => t.Name).ToArray(); AuthorityGroupDefinition adminGroupDef = new AuthorityGroupDefinition(cmdLine.SysAdminGroup, cmdLine.SysAdminGroup, false, tokenStrings); AuthorityGroupImporter groupImporter = new AuthorityGroupImporter(); IList <AuthorityGroup> groups = groupImporter.Import(new AuthorityGroupDefinition[] { adminGroupDef }, (IUpdateContext)PersistenceScope.CurrentContext); // find the admin group entity that was just created AuthorityGroup adminGroup = CollectionUtils.SelectFirst(groups, g => g.Name == cmdLine.SysAdminGroup); // create the "sa" user CreateSysAdminUser(adminGroup, cmdLine, PersistenceScope.CurrentContext, Console.Out); // optionally import other default authority groups defined in other plugins if (cmdLine.ImportDefaultAuthorityGroups) { groupImporter.ImportFromPlugins((IUpdateContext)PersistenceScope.CurrentContext); } scope.Complete(); } } catch (CommandLineException e) { Console.WriteLine(e.Message); cmdLine.PrintUsage(Console.Out); } }
public void RunApplication(string[] args) { var cmdLine = new SetupCommandLine(); try { cmdLine.Parse(args); using (var scope = new PersistenceScope(PersistenceContextType.Update)) { ((IUpdateContext)PersistenceScope.CurrentContext).ChangeSetRecorder.OperationName = GetType().FullName; // import authority tokens var tokenImporter = new AuthorityTokenImporter(); var allTokens = tokenImporter.ImportFromPlugins((IUpdateContext)PersistenceScope.CurrentContext); var tokenStrings = CollectionUtils.Map <AuthorityToken, string, List <string> >(allTokens, t => t.Name).ToArray(); // import built-in groups var builtInAuthorityGroups = new[] { GetSysAdminGroupDefinition(tokenStrings), BuiltInAuthorityGroups.SystemAccounts }; var groupImporter = new AuthorityGroupImporter(); var groups = groupImporter.Import(builtInAuthorityGroups, (IUpdateContext)PersistenceScope.CurrentContext); // create the "sa" user var adminGroup = CollectionUtils.SelectFirst(groups, g => g.Name == BuiltInAuthorityGroups.Administrators.Name); CreateSysAdminUser(adminGroup, cmdLine, PersistenceScope.CurrentContext, Console.Out); // optionally import other default authority groups defined in other plugins if (cmdLine.ImportDefaultAuthorityGroups) { groupImporter.ImportFromPlugins((IUpdateContext)PersistenceScope.CurrentContext); } scope.Complete(); } } catch (CommandLineException e) { Console.WriteLine(e.Message); cmdLine.PrintUsage(Console.Out); } }
private static void DryRunHelper(bool dryRun, Action <object> action) { if (dryRun) { // create a new persistence scope, so that we do not use the scope inherited by the service using (var scope = new PersistenceScope(PersistenceContextType.Update, PersistenceScopeOption.RequiresNew)) { action(null); // try to synch state to see if DB will accept changes scope.Context.SynchState(); //note: do not call scope.Complete() under any circumstances - we want this transaction to rollback } } else { // just do the action in the usual scope action(null); } }
protected override IEnumerable <IExportItem> ExportCore() { using (PersistenceScope scope = new PersistenceScope(PersistenceContextType.Read)) { IReadContext context = (IReadContext)PersistenceScope.CurrentContext; IMetadataBroker metaBroker = context.GetBroker <IMetadataBroker>(); IEnumBroker enumBroker = context.GetBroker <IEnumBroker>(); List <Type> enumClasses = CollectionUtils.Sort(metaBroker.ListEnumValueClasses(), delegate(Type x, Type y) { return(x.FullName.CompareTo(y.FullName)); }); foreach (Type enumClass in enumClasses) { EnumerationData data = new EnumerationData(); data.EnumerationClass = enumClass.FullName; data.Members = CollectionUtils.Map <EnumValue, EnumerationMemberData>(enumBroker.Load(enumClass, true), delegate(EnumValue v) { return(new EnumerationMemberData(v)); }); yield return(new ExportItem(data)); } scope.Complete(); } }
protected sealed override IEnumerable <IExportItem> ExportCore() { var more = true; for (var row = 0; more; row += ItemsPerReadTransaction) { using (var scope = new PersistenceScope(PersistenceContextType.Read)) { var context = (IReadContext)PersistenceScope.CurrentContext; var items = GetItemsForExport(context, row, ItemsPerReadTransaction); foreach (var entity in items) { var data = Export(entity, context); yield return(new ExportItem(data)); } // there may be more rows if the last query returned any items more = (items.Count > 0); scope.Complete(); } } }
protected override void ImportCore(IEnumerable <IImportItem> items) { using (PersistenceScope scope = new PersistenceScope(PersistenceContextType.Update)) { IUpdateContext context = (IUpdateContext)PersistenceScope.CurrentContext; context.ChangeSetRecorder.OperationName = this.GetType().FullName; IMetadataBroker metaBroker = context.GetBroker <IMetadataBroker>(); IEnumBroker enumBroker = context.GetBroker <IEnumBroker>(); IList <Type> enumClasses = metaBroker.ListEnumValueClasses(); foreach (IImportItem item in items) { EnumerationData data = (EnumerationData)Read(item.Read(), typeof(EnumerationData)); // find the enum class Type enumClass = CollectionUtils.SelectFirst(enumClasses, delegate(Type ec) { return(ec.FullName == data.EnumerationClass); }); if (enumClass == null) { Platform.Log(LogLevel.Error, string.Format("{0} is not a valid enumeration class name.", data.EnumerationClass)); continue; } IList <EnumValue> existingValues = enumBroker.Load(enumClass, true); foreach (EnumerationMemberData md in data.Members) { // check if a conflicting value exists // (this can happen if there is existing data in the db with the same value but different code) EnumValue conflict = CollectionUtils.SelectFirst(existingValues, delegate(EnumValue v) { return(v.Code != md.Code && v.Value == md.Value); }); if (conflict != null) { Platform.Log(LogLevel.Error, string.Format("{0} value {1} conflicts with existing value {2} and will not be imported.", data.EnumerationClass, md.Code, conflict.Code)); continue; } // check if the value already exists EnumValue value = CollectionUtils.SelectFirst(existingValues, delegate(EnumValue v) { return(v.Code == md.Code); }); if (value == null) { // value does not exist - add it value = enumBroker.AddValue(enumClass, md.Code, md.Value, md.Description, md.DisplayOrder, md.Deactivated); existingValues.Add(value); } else { // value exists - update it enumBroker.UpdateValue(enumClass, md.Code, md.Value, md.Description, md.DisplayOrder, md.Deactivated); } } context.SynchState(); } scope.Complete(); } }
public StartOperationAsyncResult(ServiceDurableInstance durableInstance, bool canCreateInstance, AsyncCallback callback, object state) : base(callback, state) { this.durableInstance = durableInstance; bool completeSelf = false; IAsyncResult result = null; this.operationContext = OperationContext.Current; scope = new StartOperationScope(this.durableInstance); bool success = false; try { if (this.durableInstance.instance == null) { if (this.durableInstance.TryActivateInstance(canCreateInstance)) { completeSelf = true; } else { using (PersistenceScope persistenceScope = new PersistenceScope( this.durableInstance.saveStateInOperationTransaction, this.durableInstance.clonedTransaction)) { if (this.durableInstance.lockingProvider != null) { result = this.durableInstance.lockingProvider.BeginLoad(this.durableInstance.operationTimeout, true, loadCallback, this); } else { result = this.durableInstance.provider.BeginLoad(this.durableInstance.operationTimeout, loadCallback, this); } } this.durableInstance.existsInPersistence = true; if (result.CompletedSynchronously) { completeSelf = true; } } } else { completeSelf = true; } success = true; } finally { if (!success) { scope.Dispose(); } } if (completeSelf) { try { if (result != null) { this.durableInstance.instance = this.durableInstance.provider.EndLoad(result); } Fx.Assert(this.durableInstance.instance != null, "The instance should always be set here."); Complete(true); scope.Complete(); } finally { scope.Dispose(); } } }
public FinishOperationAsyncResult(ServiceDurableInstance durableInstance, bool completeInstance, bool performPersistence, Exception operationException, AsyncCallback callback, object state) : base(callback, state) { this.durableInstance = durableInstance; IAsyncResult result = null; OperationType operation = OperationType.None; bool completeSelf = false; bool disposeInstace; operation = this.durableInstance.FinishOperationCommon(completeInstance, operationException, out disposeInstace); if (performPersistence) { switch (operation) { case OperationType.Unlock: if (this.durableInstance.lockingProvider != null) { using (PersistenceScope scope = new PersistenceScope( this.durableInstance.saveStateInOperationTransaction, this.durableInstance.clonedTransaction)) { result = this.durableInstance.lockingProvider.BeginUnlock(this.durableInstance.operationTimeout, unlockCallback, this); } } break; case OperationType.Delete: using (PersistenceScope scope = new PersistenceScope( this.durableInstance.saveStateInOperationTransaction, this.durableInstance.clonedTransaction)) { result = this.durableInstance.provider.BeginDelete(this.durableInstance.Instance, this.durableInstance.operationTimeout, deleteCallback, this); } break; case OperationType.Create: using (PersistenceScope scope = new PersistenceScope( this.durableInstance.saveStateInOperationTransaction, this.durableInstance.clonedTransaction)) { if (this.durableInstance.lockingProvider != null) { result = this.durableInstance.lockingProvider.BeginCreate(this.durableInstance.Instance, this.durableInstance.operationTimeout, disposeInstace, createCallback, this); } else { result = this.durableInstance.provider.BeginCreate(this.durableInstance.Instance, this.durableInstance.operationTimeout, createCallback, this); } } break; case OperationType.Update: using (PersistenceScope scope = new PersistenceScope( this.durableInstance.saveStateInOperationTransaction, this.durableInstance.clonedTransaction)) { if (this.durableInstance.lockingProvider != null) { result = this.durableInstance.lockingProvider.BeginUpdate(this.durableInstance.Instance, this.durableInstance.operationTimeout, disposeInstace, updateCallback, this); } else { result = this.durableInstance.provider.BeginUpdate(this.durableInstance.Instance, this.durableInstance.operationTimeout, updateCallback, this); } } break; case OperationType.None: break; default: Fx.Assert("Unknown OperationType was passed in."); break; } } if (disposeInstace) { this.durableInstance.DisposeInstance(); } if (operation == OperationType.None || (result != null && result.CompletedSynchronously)) { completeSelf = true; } if (!performPersistence) { Fx.Assert(result == null, "Should not have had a result if we didn't perform persistence."); Complete(true); return; } if (completeSelf) { CallEndOperation(operation, result); Complete(true); } }
public object StartOperation(bool canCreateInstance) { using (StartOperationScope scope = new StartOperationScope(this)) { if (this.markedForCompletion) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InstanceNotFoundException(this.InstanceId)); } if (this.instance == null) { if (!TryActivateInstance(canCreateInstance)) { using (PersistenceScope persistenceScope = new PersistenceScope( this.saveStateInOperationTransaction, this.clonedTransaction)) { if (this.lockingProvider != null) { this.instance = this.lockingProvider.Load(this.operationTimeout, true); } else { this.instance = this.provider.Load(this.operationTimeout); } if (DiagnosticUtility.ShouldTraceInformation) { string traceText = SR2.GetString(SR2.ServiceDurableInstanceLoadedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False"); TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ServiceDurableInstanceLoaded, SR.GetString(SR.TraceCodeServiceDurableInstanceLoaded), new StringTraceRecord("DurableInstanceDetail", traceText), this, null); } } this.existsInPersistence = true; } } scope.Complete(); } Fx.Assert( this.instance != null, "Instance should definitely be non-null here or we should have thrown an exception."); return this.instance; }
public void FinishOperation(bool completeInstance, bool performPersistence, Exception operationException) { try { bool disposeInstance; OperationType operation = FinishOperationCommon(completeInstance, operationException, out disposeInstance); Fx.Assert( (performPersistence || (operation != OperationType.Delete && operation != OperationType.Unlock)), "If we aren't performing persistence then we are a NotAllowed contract and therefore should never have loaded from persistence."); if (performPersistence) { switch (operation) { case OperationType.Unlock: // Do the null check out here to avoid creating the scope if (this.lockingProvider != null) { using (PersistenceScope scope = new PersistenceScope( this.saveStateInOperationTransaction, this.clonedTransaction)) { this.lockingProvider.Unlock(this.operationTimeout); } } break; case OperationType.Delete: using (PersistenceScope scope = new PersistenceScope( this.saveStateInOperationTransaction, this.clonedTransaction)) { this.provider.Delete(this.instance, this.operationTimeout); if (DiagnosticUtility.ShouldTraceInformation) { string traceText = SR.GetString(SR.TraceCodeServiceDurableInstanceDeleted, this.InstanceId); TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ServiceDurableInstanceDeleted, traceText, new StringTraceRecord("DurableInstanceDetail", traceText), this, null); } } break; case OperationType.Create: using (PersistenceScope scope = new PersistenceScope( this.saveStateInOperationTransaction, this.clonedTransaction)) { if (this.lockingProvider != null) { this.lockingProvider.Create(this.Instance, this.operationTimeout, disposeInstance); } else { this.provider.Create(this.Instance, this.operationTimeout); } if (DiagnosticUtility.ShouldTraceInformation) { string traceText = SR2.GetString(SR2.ServiceDurableInstanceSavedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False"); TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ServiceDurableInstanceSaved, SR.GetString(SR.TraceCodeServiceDurableInstanceSaved), new StringTraceRecord("DurableInstanceDetail", traceText), this, null); } } break; case OperationType.Update: using (PersistenceScope scope = new PersistenceScope( this.saveStateInOperationTransaction, this.clonedTransaction)) { if (this.lockingProvider != null) { this.lockingProvider.Update(this.Instance, this.operationTimeout, disposeInstance); } else { this.provider.Update(this.Instance, this.operationTimeout); } if (DiagnosticUtility.ShouldTraceInformation) { string traceText = SR2.GetString(SR2.ServiceDurableInstanceSavedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False"); TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ServiceDurableInstanceSaved, SR.GetString(SR.TraceCodeServiceDurableInstanceSaved), new StringTraceRecord("DurableInstanceDetail", traceText), this, null); } } break; case OperationType.None: break; default: Fx.Assert("We should never get an unknown OperationType."); break; } } if (disposeInstance) { DisposeInstance(); } } finally { CompleteClonedTransaction(); } }
protected override void ImportCore(IEnumerable<IImportItem> items) { using (PersistenceScope scope = new PersistenceScope(PersistenceContextType.Update)) { IUpdateContext context = (IUpdateContext) PersistenceScope.CurrentContext; context.ChangeSetRecorder.OperationName = this.GetType().FullName; IMetadataBroker metaBroker = context.GetBroker<IMetadataBroker>(); IEnumBroker enumBroker = context.GetBroker<IEnumBroker>(); IList<Type> enumClasses = metaBroker.ListEnumValueClasses(); foreach (IImportItem item in items) { EnumerationData data = (EnumerationData) Read(item.Read(), typeof(EnumerationData)); // find the enum class Type enumClass = CollectionUtils.SelectFirst(enumClasses, delegate(Type ec) { return ec.FullName == data.EnumerationClass; }); if(enumClass == null) { Platform.Log(LogLevel.Error, string.Format("{0} is not a valid enumeration class name.", data.EnumerationClass)); continue; } IList<EnumValue> existingValues = enumBroker.Load(enumClass, true); foreach (EnumerationMemberData md in data.Members) { // check if a conflicting value exists // (this can happen if there is existing data in the db with the same value but different code) EnumValue conflict = CollectionUtils.SelectFirst(existingValues, delegate(EnumValue v) { return v.Code != md.Code && v.Value == md.Value; }); if(conflict != null) { Platform.Log(LogLevel.Error, string.Format("{0} value {1} conflicts with existing value {2} and will not be imported.", data.EnumerationClass, md.Code, conflict.Code)); continue; } // check if the value already exists EnumValue value = CollectionUtils.SelectFirst(existingValues, delegate(EnumValue v) { return v.Code == md.Code; }); if (value == null) { // value does not exist - add it value = enumBroker.AddValue(enumClass, md.Code, md.Value, md.Description, md.DisplayOrder, md.Deactivated); existingValues.Add(value); } else { // value exists - update it enumBroker.UpdateValue(enumClass, md.Code, md.Value, md.Description, md.DisplayOrder, md.Deactivated); } } context.SynchState(); } scope.Complete(); } }
internal static SystemIdentityStore Load() { if (_store != null) { return(_store); } lock (_syncroot) { if (_store == null) { const string userName = "******"; var serializer = new XmlSerializer(typeof(SystemIdentityStore)); var documentName = typeof(SystemIdentityStore).FullName; var versionString = VersionUtils.ToPaddedVersionString(new Version(0, 0), false, false); var criteria = new ConfigurationDocumentSearchCriteria(); criteria.User.EqualTo(userName); criteria.DocumentName.EqualTo(documentName); criteria.DocumentVersionString.EqualTo(versionString); SystemIdentityStore store = null; using (var scope = new PersistenceScope(PersistenceContextType.Read)) { var broker = scope.Context.GetBroker <IConfigurationDocumentBroker>(); var document = broker.Find(criteria).FirstOrDefault(); if (document != null) { try { using (var reader = new StringReader(document.Body.DocumentText)) store = (SystemIdentityStore)serializer.Deserialize(reader); } catch (Exception) { store = null; } } scope.Complete(); } if (store == null || store.SecretKey == null || store.SecretKey.Length == 0) { if (store == null) { store = new SystemIdentityStore(); } store.SecretKey = new byte[128]; using (var crng = new RNGCryptoServiceProvider()) crng.GetBytes(store.SecretKey); using (var scope = new PersistenceScope(PersistenceContextType.Update)) using (var writer = new StringWriter()) { serializer.Serialize(writer, store); var broker = scope.Context.GetBroker <IConfigurationDocumentBroker>(); var document = broker.Find(criteria).FirstOrDefault(); if (document != null) { document.Body.DocumentText = writer.ToString(); } else { document = new ConfigurationDocument(documentName, versionString, userName, null); document.Body.DocumentText = writer.ToString(); scope.Context.Lock(document, DirtyState.New); } scope.Complete(); } } Interlocked.Exchange(ref _store, store); } return(_store); } }
protected override IEnumerable<IExportItem> ExportCore() { using (PersistenceScope scope = new PersistenceScope(PersistenceContextType.Read)) { IReadContext context = (IReadContext) PersistenceScope.CurrentContext; IMetadataBroker metaBroker = context.GetBroker<IMetadataBroker>(); IEnumBroker enumBroker = context.GetBroker<IEnumBroker>(); List<Type> enumClasses = CollectionUtils.Sort(metaBroker.ListEnumValueClasses(), delegate (Type x, Type y) { return x.FullName.CompareTo(y.FullName);}); foreach (Type enumClass in enumClasses) { EnumerationData data = new EnumerationData(); data.EnumerationClass = enumClass.FullName; data.Members = CollectionUtils.Map<EnumValue, EnumerationMemberData>(enumBroker.Load(enumClass, true), delegate(EnumValue v) { return new EnumerationMemberData(v); }); yield return new ExportItem(data); } scope.Complete(); } }