public void ShouldReadWriteEpochMillisecondsDatTime() { using (IJournal <File> journal = CreateJournal(DateTimeMode.EpochMilliseconds)) { TestUtils.GenerateRecords(journal, 1000, 2, GenerateFile); IQuery <File> r2 = journal.OpenReadTx(); int i = 0; foreach (File file in r2.All()) { Assert.That(file.Path, Is.EqualTo(i.ToString(CultureInfo.InvariantCulture))); DateTime expectedModifedDate = TestUtils.START.AddMilliseconds(i * _timeIncrement); Assert.That(DateUtils.DateTimeToUnixTimeStamp(file.Modified) , Is.EqualTo(DateUtils.DateTimeToUnixTimeStamp(expectedModifedDate))); DateTime?expectedCreatedDate = i % 2 == 0 ? TestUtils.START.AddMilliseconds(i * _timeIncrement * 2) : (DateTime?)null; Assert.That(file.Created, Is.EqualTo(expectedCreatedDate)); i++; } } }
/// <summary> /// Only recovers blocks that reside in logs. It returns object serialized by /// journal for further processing. /// </summary> /// <param name="provider">The block provider.</param> /// <param name="journal">The journal.</param> public static bool StartupRecovery(IJournal journal) { // We go through all journal logs. return(true); }
/// <summary> /// Construct my default state. /// </summary> /// <param name="journal">The <see cref="IJournal{T}"/> of the registration</param> /// <param name="sourcedType">The type of the registered source</param> private Info(IJournal journal, Type sourcedType) { Journal = journal; SourcedType = sourcedType; EntryAdapterProvider = new EntryAdapterProvider(); StateAdapterProvider = new StateAdapterProvider(); }
public SourcedProcessTest(ITestOutputHelper output) { var converter = new Converter(output); Console.SetOut(converter); _world = World.StartWithDefaults("five-step-process-test"); var queue = new AsyncMessageQueue(null); _exchange = new LocalExchange(queue); _dispatcher = new MockJournalDispatcher(); _journal = new InMemoryJournal <string>(_dispatcher, _world); _sourcedTypeRegistry = new SourcedTypeRegistry(_world); RegisterSourcedTypes <FiveStepSendingSourcedProcess>(); RegisterSourcedTypes <FiveStepEmittingSourcedProcess>(); _exchangeReceivers = new ExchangeReceivers(); _exchangeSender = new LocalExchangeSender(queue); var processTypeRegistry = new ProcessTypeRegistry(_world); processTypeRegistry.Register(new SourcedProcessInfo <FiveStepSendingSourcedProcess, PorcessObjectState>(nameof(FiveStepSendingSourcedProcess), _exchange, _sourcedTypeRegistry)); processTypeRegistry.Register(new SourcedProcessInfo <FiveStepEmittingSourcedProcess, PorcessObjectState>(nameof(FiveStepEmittingSourcedProcess), _exchange, _sourcedTypeRegistry)); RegisterExchangeCoveys(); }
public void ShouldDeleteOutDatedPartitionVersionWhenNotInUse() { int days = 40; var server = new AsyncJournalServer(TimeSpan.FromSeconds(1)); using (IJournal <PocoType> journal = WriteJournal(EPartitionType.Month, TimeSpan.FromDays(1), days, server)) { using (var rtx = journal.OpenReadTx()) { var newVersion = new PartitionDate(START_DATE, 1, EPartitionType.Month).Name; var newPartitionPath = Path.Combine(_directoryPath, newVersion); Directory.CreateDirectory(newPartitionPath); using (var rtx2 = journal.OpenReadTx()) { var len = rtx.All().Length.Value; } } // Act. server.DoEvents(); // Verify. var oldVersion = new PartitionDate(START_DATE, 0, EPartitionType.Month).Name; var oldPartitionPath = Path.Combine(_directoryPath, oldVersion); Assert.That(Directory.Exists(oldPartitionPath), Is.EqualTo(false)); } }
public override UpgradeEngine Given() { scriptProvider = Substitute.For <IScriptProvider>(); versionTracker = Substitute.For <IJournal>(); versionTracker.GetExecutedScripts().Returns(new List <ExecutedSqlScript> { new ExecutedSqlScript { Hash = "a", Name = "#1" }, new ExecutedSqlScript { Hash = "b", Name = "#2" }, new ExecutedSqlScript { Hash = "c", Name = "#3" } }); scriptExecutor = Substitute.For <IScriptExecutor>(); var config = new UpgradeConfiguration { ConnectionManager = new TestConnectionManager(Substitute.For <IDbConnection>()) }; config.ScriptProviders.Add(scriptProvider); config.ScriptExecutor = scriptExecutor; config.Journal = versionTracker; var upgrader = new UpgradeEngine(config); return(upgrader); }
public override UpgradeEngine Given() { scriptProvider = Substitute.For <IScriptProvider>(); scriptProvider.GetScripts(Arg.Any <IConnectionManager>()).Returns(new List <SqlScript> { new SqlScript("#1", "Content of #1"), new SqlScript("#3", "Content of #3"), }); versionTracker = Substitute.For <IJournal>(); versionTracker.GetExecutedScripts().Returns(new[] { "#1", "#2", "#3" }); scriptExecutor = Substitute.For <IScriptExecutor>(); var config = new UpgradeConfiguration { ConnectionManager = new TestConnectionManager(Substitute.For <IDbConnection>()) }; config.ScriptProviders.Add(scriptProvider); config.ScriptExecutor = scriptExecutor; config.Journal = versionTracker; var upgrader = new UpgradeEngine(config); return(upgrader); }
private static void AppendRecords(IJournal <Quote> qj, long startDate, long increment) { using (var wr = qj.OpenWriteTx()) { for (int i = 0; i < 300; i++) { var quote = new Quote { Ask = i, Ex = "Ex_" + i % 20, Sym = "Symbol_" + i % 20, Bid = i % 5, BidSize = -i, AskSize = i % 5, Timestamp = startDate + i * increment }; if (i % 5 == 0) { quote.__isset.askSize = false; } wr.Append(quote); } wr.Commit(); } }
public override UpgradeEngine Given() { scriptProvider = Substitute.For <IScriptProvider>(); scriptProvider.GetScripts(Arg.Any <IConnectionManager>()).Returns(new List <SqlScript> { new SqlScript("1234", "foo") }); versionTracker = Substitute.For <IJournal>(); dbConnection = Substitute.For <IDbConnection>(); dbCommand = Substitute.For <IDbCommand>(); dbConnection.CreateCommand().Returns(dbCommand); var connectionManager = new TestConnectionManager(dbConnection); scriptExecutor = new SqlScriptExecutor(() => connectionManager, () => Substitute.For <IUpgradeLog>(), null, () => true, null, () => versionTracker); var builder = new UpgradeEngineBuilder() .WithScript(new SqlScript("1234", "create table $var$ (Id int)")) .JournalTo(versionTracker) .WithVariable("var", "sub"); builder.Configure(c => c.ScriptExecutor = scriptExecutor); builder.Configure(c => c.ConnectionManager = connectionManager); var upgrader = builder.Build(); return(upgrader); }
public void Validate_number_length_failed() { IJournal entity = this.CreateEntity(); entity.Number = @"0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 123456"; var errors = this.validation.Validate(entity); errors.Should().Contain(x => !x.IsValid && x.Code == "El campo 'Número de asiento' tiene longitud incorrecta"); }
public static void Init(IJournal journal, SignalsFactory signals, InvertorsService powers) { mSpeed = signals.GetSignal(SensorName.Derivative(SystemName.Conveyor, SignalName.Speed)); if (mSpeed == null) { throw new Exception("bad signal"); } mSpeed.Update(mCurrentSpeed); //mSpeed.OnChange += sensor => Console.WriteLine("Conveyor speed: {0}"); AcceptCheckout.OnTimeout += sender => mSpeed.Update(mCurrentSpeed); mCord = new Cord(signals.GetSignal(SensorName.Cord(6))); mCord.OnChange += sensor => { if (sensor.Value > 0) { //Console.WriteLine("Conveyor: cord F6"); OnErrorCaller(sensor); } }; mKv9 = new Relay(journal, RelayName.Kv9, signals); mKv9.OnError += OnErrorCaller; mKv10 = new Relay(journal, RelayName.Kv10, signals); mKv10.OnError += OnErrorCaller; mState = signals.GetSignal(SensorName.Derivative(SystemName.Conveyor, SignalName.Status)); }
public long ShouldUseNewPartitionOnRecreate(bool clearPartition1, int days) { var server = new AsyncJournalServer(TimeSpan.FromSeconds(1)); using (IJournal <PocoType> journal = WriteJournal(EPartitionType.Month, TimeSpan.FromDays(1), days, server)) { using (var rtx = journal.OpenReadTx()) { var newVersion = new PartitionDate(START_DATE, 1, EPartitionType.Month).Name; var newPartitionPath = Path.Combine(_directoryPath, newVersion); Directory.CreateDirectory(newPartitionPath); using (var rtx2 = journal.OpenReadTx()) { var len = rtx2.All().Length.Value; } } // Act. server.DoEvents(); // Verify. using (var rtx = journal.OpenReadTx()) { return(rtx.All().Length.Value); } } }
/// <summary> /// Initializes a new instance of the <see cref="PhysicalDatabase"/> class. /// </summary> /// <param name="journal">The journal.</param> public unsafe PhysicalDatabase(IJournal journal, Caching.BlockCache cache, JournalRecovery recovery) { this.journal = journal; this.journal.Startup(cache, recovery); // Must make sure we construct the first node if not already there ("default node"). Block block = journal.ReadService.Read(BlockType.NoCache, 0); fixed(byte *p = block.Data) { DatabaseHeader *header = (DatabaseHeader *)p; rootAddress = header->RootObjectAddress; } // We must initialize it. if (rootAddress == 0) { journal.Execute(new Operations.CreateRootObject()); block = journal.ReadService.Read(BlockType.NoCache, 0); fixed(byte *pp = block.Data) { DatabaseHeader *header = (DatabaseHeader *)pp; rootAddress = header->RootObjectAddress; } Debug.Assert(rootAddress != 0); } }
public void Journal2() { IICalendar iCal = iCalendar.LoadFromFile(@"Calendars\Journal\JOURNAL2.ics")[0]; ProgramTest.TestCal(iCal); Assert.AreEqual(1, iCal.Journals.Count); IJournal j = iCal.Journals[0]; Assert.IsNotNull(j, "Journal entry was null"); Assert.AreEqual(JournalStatus.Final, j.Status, "Journal entry should have been in FINAL status, but it was in " + j.Status + " status."); Assert.AreEqual("PRIVATE", j.Class, "Journal class should have been PRIVATE, but was " + j.Class + "."); Assert.AreEqual("JohnSmith", j.Organizer.CommonName, "Organizer common name should have been JohnSmith, but was " + j.Organizer.CommonName); Assert.IsTrue( string.Equals( j.Organizer.SentBy.OriginalString, "mailto:[email protected]", StringComparison.InvariantCultureIgnoreCase), "Organizer should have had been SENT-BY 'mailto:[email protected]'; it was sent by '" + j.Organizer.SentBy + "'"); Assert.IsTrue( string.Equals( j.Organizer.DirectoryEntry.OriginalString, "ldap://host.com:6666/o=3DDC%20Associates,c=3DUS??(cn=3DJohn%20Smith)", StringComparison.InvariantCultureIgnoreCase), "Organizer's directory entry should have been 'ldap://host.com:6666/o=3DDC%20Associates,c=3DUS??(cn=3DJohn%20Smith)', but it was '" + j.Organizer.DirectoryEntry + "'"); Assert.AreEqual( "MAILTO:[email protected]", j.Organizer.Value.OriginalString); Assert.AreEqual( "jsmith", j.Organizer.Value.UserInfo); Assert.AreEqual( "host.com", j.Organizer.Value.Host); Assert.IsNull(j.Start); }
public static IImportedBankBalance GetImportedBankBalance(IDalSession session, IJournal bankJournal, DateTime bookBalanceDate) { Hashtable parameters = new Hashtable(); parameters.Add("BankJournalKey", bankJournal.Key); parameters.Add("BookBalanceDate", bookBalanceDate); string hql = @"from ImportedBankBalance I where I.BankJournal.Key = :BankJournalKey and I.BookBalanceDate = :BookBalanceDate"; IList result = session.GetListByHQL(hql, parameters); if (result != null && result.Count == 1) return (ImportedBankBalance)result[0]; else return null; //List<ICriterion> expressions = new List<ICriterion>(); //expressions.Add(Expression.Eq("BankJournal.Key", bankJournal.Key)); //expressions.Add(Expression.Eq("BookBalanceDate", bookBalanceDate)); //IList result = session.GetList(typeof(ImportedBankBalance), expressions); //if (result != null && result.Count == 1) // return (IImportedBankBalance)result[0]; //else // return null; }
public VirtualFund(IVirtualFundHoldingsAccount holdingsAccount, IVirtualFundTradingAccount tradingAccount, IJournal journal) : this() { this.HoldingsAccount = holdingsAccount; this.TradingAccount = tradingAccount; this.JournalForFund = journal; }
public Relay(IJournal journal, RelayName name, ISignalsFactory signals) { mJournal = journal; mOutput = signals.GetSignal(SensorName.Relay(name)); // TODO: uncomment mFeedback = signals.GetSignal(SensorName.Relay(name, SignalName.Feedback)); if (mFeedback != null) { mFeedback.OnChange += FeedbackOnChange; } if (mOnTimeout == null) { mOnTimeout = signals.GetSignal("relay.feedback.on.timeout"); } if (mFeedback != null) { mOnTimeout.OnUpdate += signal => { var rv = signal.ValueAsInt < 1500 ? 1500 : signal.ValueAsInt > 6000 ? 6000 : signal.ValueAsInt; mJournal.Debug(string.Format("Таймер реле (ОС) установлен в {0} мс для {1}", rv, mOutput.Specification.Id), MessageLevel.System); mTask.SetTimeout(rv); }; } // задержка на контроль обратной связи по контактору по умолчанию mTask = new DelayedTask(mOnTimeout == null ? 3000 : mOnTimeout.ValueAsInt < 1500 ? 1500 : mOnTimeout.ValueAsInt > 6000 ? 6000 : mOnTimeout.ValueAsInt); mTask.OnTimeout += Checkout; }
public static void Init(IJournal journal, ISignalsFactory signals) { mRelay = new Relay(journal, RelayName.Kv4, signals); mOnTimeout = signals.GetSignal("soundalarm.on.timeout"); mOnTimeout.OnUpdate += signal => { var rv = signal.ValueAsInt < 1500 ? 1500 : signal.ValueAsInt > 6000 ? 6000 : signal.ValueAsInt; journal.Debug(string.Format("Таймер вкл. сирены установлен в {0} мс", rv), MessageLevel.System); mTask.SetTimeout(rv); }; mOffTimeout = signals.GetSignal("soundalarm.off.timeout"); mOffTimeout.OnUpdate += signal => { var rv = signal.ValueAsInt < 2500 ? 2500 : signal.ValueAsInt > 10000 ? 10000 : signal.ValueAsInt; journal.Debug(string.Format("Таймер выкл. сирены установлен в {0} мс", rv), MessageLevel.System); mUnlockInterval = rv; }; // values by default mTask = new DelayedTask(mOnTimeout.ValueAsInt); // 1500 mUnlockInterval = mOffTimeout.ValueAsInt; // 5000 mTask.OnTimeout += ProcessTimerEvent; }
public JournalService(bool isConsoleEnable) { mServer = new MultiThreadServer(); mJournal = new SqLiteJournal { IsConsoleEnable = isConsoleEnable }; }
public virtual void AfterEach() { ScriptProvider = null; VersionTracker = null; ScriptExecutor = null; Log = null; DbUpgrader = null; }
public TcpMaster(IJournal journal, string url, int port) { mJournal = journal; mUrl = url; mPort = port; ReadTimeout = 1000; }
public void Validate_succeed() { IJournal entity = this.CreateEntity(); var errors = this.validation.Validate(entity).ToList(); errors.Count.Should().Be(0); }
public Query(IJournal <T> journal, IReadTransactionContext transactionContext) { _transactionContext = transactionContext; _journal = journal; _queryable = new Lazy <JournalQueryable <T> >( () => new JournalQueryable <T>(new JournalQueryProvider <T>(_journal, transactionContext))); _recordQuery = new RecordQuery(journal, transactionContext); }
public Coupler(IJournal journal, string url) { mJournal = journal; mConnection = new TcpMaster(journal, url, 502); mThread = new Thread(Update); }
private IJournal <PocoType> WriteJournal(EPartitionType type, TimeSpan increment, int days, AsyncJournalServer server = null) { Utils.ClearJournal <PocoType>(FOLDER_PATH); IJournal <PocoType> qj = OpenJournal(EFileAccess.ReadWrite, type, server); AppendRecords(qj, START_DATE, increment, days); return(qj); }
/// <summary> /// Initializes a new instance of the <see cref="HashedEmbeddedScriptsProvider" /> class. /// </summary> /// <param name="assembly">The assemblies to search.</param> /// <param name="filter">The filter.</param> /// <param name="encoding">The encoding.</param> /// <param name="journal">The Journal</param> public HashedEmbeddedScriptsProvider(Assembly assembly, Func <string, bool> filter, Encoding encoding, IJournal journal) { _assembly = assembly; _filter = filter; _encoding = encoding; _journal = (HashedSqlTableJournal)journal; }
public void Transport(Package package, IJournal journal, int distance) { Kilocalories -= package.GetWeight() * 100; journal.Write($"Walking with {package.Name}..."); var time = distance / 3; TransportFor(time); journal.Write("Finished walking!"); }
public void Transport(Package package, IJournal journal, int distance) { Gas -= package.GetWeight() * 23; journal.Write($"Driving with {package.Name}..."); var time = distance / 35; TransportFor(time); journal.Write("Finished driving!"); }
public void Transport(Package package, IJournal journal, int distance) { Gas -= base.CalculateDepletion(package, 23); journal.Write($"Driving with {package.Name}..."); var time = base.CalculateTime(distance, 35); base.TransportFor(time); journal.Write("Finished driving!"); }
private void SendJournal(IJournal journal) { _hubContext.All.onJournalCreated(new JournalCreatedMessage { CustomerId = journal.Customer.Id, DateCreated = journal.DateTimeCreated.ToLocalTime().ToString("MM/dd/yyyy HH:mm"), Description = journal.Description }); }
public void Transport(Package package, IJournal journal, int distance) { CalculateDepletion(package.GetWeight()); journal.Write($"{ToTitleCase(GetVerb())} with {package.Name}..."); var time = distance / GetRate(); TransportFor(time); journal.Write($"Finished {GetVerb().ToLower()}!"); }
private ColumnStorage CreateStorage(IJournal <TestJournal> journal) { _fileFactory = new Mock <ICompositeFileFactory>(); _fileFactory.Setup(f => f.OpenFile(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <EFileAccess>())).Callback( (string name, int bitHint, EFileAccess access) => _bitHint = bitHint); return(new ColumnStorage(journal.Metadata, "temp", EFileAccess.ReadWrite, 0, _fileFactory.Object)); }
/// <summary> /// Initializes a new instance of the <see cref="ScriptExecutingEngine"/> class. /// </summary> /// <param name="configuration">The configuration.</param> public ScriptExecutingEngine(DbInstallerConfiguration configuration) { _connectionString = configuration.ConnectionString; _journal = configuration.Journal; _databaseServerAdapter = configuration.DatabaseServerAdapter; _logger = configuration.Logger; _scriptProviders = configuration.ScriptProviders; _scriptPreProcessors = configuration.ScriptPreprocessors; _variables = configuration.Variables; }
private DatabaseUpgradeResult Upgrade(IDatabaseProvider provider, IScriptProvider scriptProvider, IUpgradeLog log, IJournal journal, string schema) { var upgradeEngine = provider.GetUpgradeEngineBuilder(connectionStringProvider.ConnectionString, schema) .WithScripts(scriptProvider) .JournalTo(journal) .LogTo(log) .Build(); return upgradeEngine.PerformUpgrade(); }
public static IList GetImportedBankMovements(IDalSession session, IJournal bankJournal, DateTime bankStatementDate) { List<ICriterion> expressions = new List<ICriterion>(); List<Order> orderings = new List<Order>(); expressions.Add(Expression.Eq("BankJournal.Key", bankJournal.Key)); expressions.Add(Expression.Eq("BankStatementDate", bankStatementDate)); orderings.Add(Order.Asc("CloseBalanceProcessDate")); orderings.Add(Order.Asc("CloseBalanceProcessTime")); // Last two null parameters are necessary, otherwise sorting doesn't work return session.GetList(typeof(ImportedBankMovement), expressions, orderings, null, null); }
public BankStatement(IBankStatement lastBankStatement, IJournal journal, string journalEntryNumber, decimal exchangeRate) : base(journal, journalEntryNumber) { if (lastBankStatement != null) { Journal = lastBankStatement.Journal; TransactionDate = getNextWorkingDay(lastBankStatement.TransactionDate); if (TransactionDate > DateTime.Today) throw new ApplicationException( string.Format("Journal '{0}' is up-to-date: a Bank Statement for the last working day already exists.", Journal.JournalNumber)); PrevBankStatement = lastBankStatement; } }
public Unit(UnitSettings settings, IPollManager manager, IJournal journal, UnitGeneralCompleteHandler completion) { string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + settings.FilePath; Assembly assembly = Assembly.LoadFile(filePath); foreach (Type t in assembly.GetTypes()) { if (t.GetInterfaces().Contains(typeof(IUnit))) { Instance = (IUnit)Activator.CreateInstance(t); break; } } this.FullName = settings.FullName; this.ShortName = settings.ShortName; this.SymbolicName = settings.SymbolicName; this.Address = settings.Address; Instance.Initialize(MainThread.Dispatcher, settings, manager, journal, completion); Instance.UnitParamUpdateEvent += delegate(object sender, Param param) { if (UnitParamUpdateEvent != null) { UnitParamUpdateEvent(this, param); } }; Instance.UnitAlarmUpdateEvent += delegate(object sender, IAlarm alarm) { if (UnitAlarmUpdateEvent != null) { UnitAlarmUpdateEvent(this, alarm); } }; Instance.UnitStateChangedEvent += delegate(object sender, ParamState state) { if (UnitStateChangedEvent != null) { UnitStateChangedEvent(this, state); } }; }
public virtual void BeforeEach() { ScriptProvider = Substitute.For<IScriptProvider> (); VersionTracker = Substitute.For<IJournal> (); ScriptExecutor = Substitute.For<IScriptExecutor> (); ScriptPreprocessor = Substitute.For<IScriptPreprocessor>(); Log = Substitute.For<IUpgradeLog> (); var config = new UpgradeConfiguration(); config.ScriptPreprocessors.Add(ScriptPreprocessor); config.ScriptProviders.Add(ScriptProvider); config.ScriptExecutor = ScriptExecutor; config.Journal = VersionTracker; config.Log = Log; DbUpgrader = new ScriptExecutingEngine(config); }
/// <summary> /// Uses a custom journal for recording which scripts were executed. /// </summary> /// <param name="builder">The builder.</param> /// <param name="journal">The custom journal.</param> /// <returns> /// The same builder /// </returns> public static UpgradeEngineBuilder JournalTo(this UpgradeEngineBuilder builder, IJournal journal) { builder.Configure(c => c.Journal = journal); return builder; }
private static IMemorialBooking getNewCashDividendBooking(IDalSession session, IJournal journal, DateTime transactionDate) { string nextJournalEntryNumber = JournalEntryMapper.GetNextJournalEntryNumber(session, journal); IMemorialBooking newMemorialBooking = new MemorialBooking(journal, nextJournalEntryNumber); newMemorialBooking.TransactionDate = transactionDate; JournalEntryMapper.Insert(session, newMemorialBooking); return newMemorialBooking; }
public MemorialBooking(IJournal journal, string journalEntryNumber) : base(journal, journalEntryNumber) { }
public void Initialize(Dispatcher dispatcher, UnitSettings settings, IPollManager manager, IJournal journal, UnitGeneralCompleteHandler complete) { MainThread.Initialize(dispatcher); Settings = settings; Journal = journal; Manager = manager; ThreadPool.QueueUserWorkItem(delegate(object target) { Processing = new Processing(this); Processing.ProcessingAlarmUpdateEvent += AlarmUpdateEvent; Processing.ProcessingParamUpdateEvent += ParamUpdateEvent; ManualResetEvent ContinueEvent = new ManualResetEvent(false); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category0, "Схема подстанции", "Общий контроль состояния", new Prism.Units.Controls.SchematicControl(this, "схема подстанции"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category3, "ЛА №1", "Контроль и управление", new Prism.Units.Controls.LswControl(this, 1, "линейный автомат №1"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category3, "ЛА №2", "Контроль и управление", new Prism.Units.Controls.LswControl(this, 2, "линейный автомат №2"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category3, "ЛА №3", "Контроль и управление", new Prism.Units.Controls.LswControl(this, 3, "линейный автомат №3"))); PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category3, "ЛА №4", "Контроль и управление", new Prism.Units.Controls.LswControl(this, 4, "линейный автомат №4"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category3, "ЛА №5", "Контроль и управление", new Prism.Units.Controls.LswControl(this, 5, "линейный автомат №5"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category3, "АЗ", "Контроль и управление", new Prism.Units.Controls.Lsw9Control(this, "запасной автомат"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category2, "ВА №1", "Контроль и управление", new Prism.Units.Controls.RectControl(this, 1, "выпрямительный агрегат №1"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category2, "ВА №2", "Контроль и управление", new Prism.Units.Controls.RectControl(this, 2, "выпрямительный агрегат №2"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category2, "ВА №3", "Контроль и управление", new Prism.Units.Controls.RectControl(this, 3, "выпрямительный агрегат №3"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category1, "Рабочий ввод", "Контроль и управление", new Prism.Units.Controls.LeadinControl(this, 1, "рабочий ввод"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category1, "Резервный ввод", "Контроль и управление", new Prism.Units.Controls.LeadinControl(this, 2, "резервный ввод"))); }); MainThread.EnqueueTask(delegate() { PresentationControlsInternal.Add(new PresentationControl(PresentationControlCategory.Category1, "Отходящая линия", "Контроль и управление", new Prism.Units.Controls.LeadinControl(this, 3, "отходящая линия"))); }); MainThread.EnqueueTask(delegate() { ContinueEvent.Set(); }); ContinueEvent.WaitOne(); complete(); }, null); }
private static ITradingJournalEntry getNewBooking(IDalSession session, IJournal journal, DateTime transactionDate) { string nextJournalEntryNumber = JournalEntryMapper.GetNextJournalEntryNumber(session, journal); ITradingJournalEntry newTradingJournalEntry = new TradingJournalEntry(journal, nextJournalEntryNumber, transactionDate); return newTradingJournalEntry; }
private static bool createMgtFeeTransactionForMP(IJournal journalMgmtFee, IGLLookupRecords lookups, int mgtPeriodId, int year, int quarter, ManagementTypes managementType, FeeFactory feeFactory, DateTime minDate, DateTime maxDate, decimal taxPercentage, bool createCashInitiatedOrders) { bool retVal = false; IDalSession session = NHSessionFactory.CreateSession(); Hashtable parameterLists = new Hashtable(1); Hashtable parameters = new Hashtable(2); Util.GetDatesFromQuarter(year, quarter, out minDate, out maxDate); parameterLists.Add("periods", Util.GetPeriodsFromQuarter(year, quarter)); parameters.Add("mgtPeriodId", mgtPeriodId); parameters.Add("managementType", managementType); IList<IManagementPeriodUnit> unitsUnsorted = session.GetTypedListByNamedQuery<IManagementPeriodUnit>( "B4F.TotalGiro.ApplicationLayer.Fee.ManagementPeriodUnitsForMgtFeeTransactionCreation", parameters, parameterLists); if (unitsUnsorted != null && unitsUnsorted.Count > 0) { var unitsByMP = from a in unitsUnsorted group a by a.ManagementPeriod into g select new { ManagementPeriod = g.Key, Units = g.ToList() }; if (unitsByMP.Count() != 1) throw new ApplicationException("The number of management periods is not what is expected."); IManagementPeriod managementPeriod = unitsByMP.First().ManagementPeriod; IList<IManagementPeriodUnit> units = unitsByMP.First().Units; DateTime feeStartDate = minDate; DateTime feeEndDate = maxDate; if (managementPeriod.StartDate > minDate) feeStartDate = managementPeriod.StartDate; if (Util.IsNotNullDate(managementPeriod.EndDate) && managementPeriod.EndDate < maxDate) feeEndDate = managementPeriod.EndDate.Value; if (feeStartDate.Year != feeEndDate.Year) throw new ApplicationException("The year of the start date and end date for the management fee should equal"); string mgtFeeDescription; decimal mgtFeeThreshold; getMgtFeeInfo(managementPeriod, feeEndDate, year, quarter, out mgtFeeDescription, out mgtFeeThreshold); if (units != null && units.Count > 0) { // check the number of units int expectedUnitCount = Util.DateDiff(DateInterval.Month, feeStartDate, feeEndDate) + 1; if (expectedUnitCount != units.Count) throw new ApplicationException(string.Format("The number of units {0} does not equal the number of expected units {1}.", units.Count, expectedUnitCount)); // check if all have the same management period var mps = from a in units group a by a.ManagementPeriod into g select g.Key; if (mps.Count() != 1) throw new ApplicationException("Not all units belong to the same management period."); if (mps.First().Key != managementPeriod.Key) throw new ApplicationException("The management period is not ok."); if (Util.GetPeriodFromDate(managementPeriod.StartDate) == Util.GetPeriodFromDate(feeStartDate) && managementPeriod.StartDate.Day != feeStartDate.Day) throw new ApplicationException(string.Format("The start date of the management period ({0}) does not equal the presented start date ({1}).", managementPeriod.StartDate.ToString("yyyy-MM-dd"), feeStartDate.ToString("yyyy-MM-dd"))); if (managementPeriod.EndDate.HasValue) { if (feeEndDate > managementPeriod.EndDate) throw new ApplicationException(string.Format("The end date of the management period ({0}) does not equal the presented end date ({1}).", managementPeriod.EndDate.Value.ToString("yyyy-MM-dd"), feeEndDate.ToString("yyyy-MM-dd"))); else if (Util.GetPeriodFromDate(managementPeriod.EndDate.Value) == Util.GetPeriodFromDate(feeEndDate) && managementPeriod.EndDate.Value.Day != feeEndDate.Day) throw new ApplicationException(string.Format("The end date of the management period ({0}) does not equal the presented end date ({1}).", managementPeriod.EndDate.Value.ToString("yyyy-MM-dd"), feeEndDate.ToString("yyyy-MM-dd"))); } IAccountTypeCustomer account = (IAccountTypeCustomer)managementPeriod.Account; if (!account.ExitFeePayingAccount.Equals(account)) mgtFeeDescription += string.Format(" voor {0}", account.Number); string nextJournalEntryNumber = JournalEntryMapper.GetNextJournalEntryNumber(session, journalMgmtFee); IMemorialBooking memorialBooking = new MemorialBooking(journalMgmtFee, nextJournalEntryNumber); memorialBooking.TransactionDate = feeEndDate.AddDays(1); memorialBooking.Description = mgtFeeDescription; IManagementFee mgtFee = new ManagementFee(account, feeStartDate, feeEndDate, units, memorialBooking, taxPercentage, lookups); if (mgtFee != null && mgtFee.NettAmount != null && mgtFee.NettAmount.IsNotZero) { if (mgtFee.NettAmount.Quantity < mgtFeeThreshold) { ITradeableInstrument instrument; account = account.ExitFeePayingAccount; if (createCashInitiatedOrders && mgtFee.NeedToCreateCashInitiatedOrder(out instrument)) { if (instrument != null) { OrderAmountBased order = new OrderAmountBased(account, mgtFee.Components.TotalAmount, instrument, true, feeFactory, true); order.OrderInfo = mgtFeeDescription; mgtFee.CashInitiatedOrder = order; } else { // Sell from the biggest position IFundPosition pos = account.Portfolio.PortfolioInstrument.Where(x => x.Size.IsGreaterThanZero).OrderByDescending(x => x.CurrentValue).FirstOrDefault(); if (pos != null && (pos.CurrentBaseValue + mgtFee.NettAmount).IsGreaterThanOrEqualToZero) { OrderAmountBased order = new OrderAmountBased(account, mgtFee.Components.TotalAmount, pos.Instrument, true, feeFactory, true); order.OrderInfo = mgtFeeDescription; mgtFee.CashInitiatedOrder = order; } } } if (mgtFee.CashInitiatedOrder == null && (account.Portfolio.TotalValue() + mgtFee.TotalAmount).IsLessThanZero) throw new ApplicationException(string.Format("Could not create a management fee booking for account {0} since the total portfolio value ({1}) is insufficient.", account.DisplayNumberWithName, account.Portfolio.TotalValue().DisplayString)); mgtFee.BookLines(); GeneralOperationsBookingMapper.Update(session, mgtFee); retVal = true; } } } } session.Close(); return retVal; }
protected void fillFromInstruction(IInstruction instruction, ICounterAccount counterAccount, Money amount) { this.CreatedBy = B4F.TotalGiro.Security.SecurityManager.CurrentUser; ICustomerAccount transfereeAccount = (ICustomerAccount)instruction.Account; if (transfereeAccount == null) throw new ApplicationException(err_def + "the account is mandatory"); string errMessage = err_def + string.Format("Could not create money transfer order for account {0}: ", transfereeAccount.DisplayNumberWithName); IEffectenGiro stichtingDetails = transfereeAccount.AccountOwner.StichtingDetails; if (stichtingDetails == null) throw new ApplicationException(errMessage + "the stichting details are mandatory"); this.TransferorJournal = stichtingDetails.DefaultWithdrawJournal; this.NarDebet1 = stichtingDetails.StichtingName; this.NarDebet2 = stichtingDetails.ResidentialAddress.AddressLine1; this.NarDebet3 = stichtingDetails.ResidentialAddress.AddressLine2; this.NarDebet4 = stichtingDetails.ResidentialAddress.Country.CountryName; this.ProcessDate = DateTime.Today; this.Amount = amount; this.TransfereeAccount = transfereeAccount; this.TransfereeCounterAccount = counterAccount; this.NarBenef1 = getMaxLengthString(counterAccount.AccountName, 35); this.BenefBankAcctNr = counterAccount.Number; Address address = null; if (counterAccount.BeneficiaryAddress != null && !counterAccount.BankAddress.IsEmpty) address = counterAccount.BeneficiaryAddress; else if (transfereeAccount.PrimaryAccountHolder != null && transfereeAccount.PrimaryAccountHolder.Contact != null && transfereeAccount.PrimaryAccountHolder.Contact.CurrentNAW != null) { IContactsNAW contactsNaw = transfereeAccount.PrimaryAccountHolder.Contact.CurrentNAW; if (contactsNaw.ResidentialAddress != null && !contactsNaw.ResidentialAddress.IsEmpty) address = contactsNaw.ResidentialAddress; else address = contactsNaw.PostalAddress; } if (address != null && !address.IsEmpty) { this.NarBenef2 = getAddressLine(address, 1); this.NarBenef3 = getAddressLine(address, 2); this.NarBenef4 = getAddressLine(address, 3); } }
private DatabaseUpgradeResult Upgrade(string connectionString, IScriptProvider scriptProvider, ILog log, IJournal journal, string schema) { var upgrader = new DatabaseUpgrader( connectionString, scriptProvider, journal, new SqlScriptExecutor(connectionString, log, schema)); var result = upgrader.PerformUpgrade(); return result; }
public TradingJournalEntry(IJournal journal, string journalEntryNumber, DateTime transactionDate) : base(journal, journalEntryNumber) { this.TransactionDate = transactionDate; }
public bool Settle(IJournal journal, string nextJournalEntryNumber, IGLAccount settleDiffGLAccount) { bool success = false; if ((TradeStatements != null && TradeStatements.Count > 0) && (BankSettlements != null && BankSettlements.Count > 0)) { // TODO -> What if not in base currency???? Money diff = SettleDifference; foreach (ITradingJournalEntry journalEntry in TradeStatements) { ((IOrderExecution)journalEntry.Trade).SettleExternal(SettlementDate); } if (diff != null && diff.IsNotZero) { MemorialBooking = new MemorialBooking(journal, nextJournalEntryNumber); MemorialBooking.TransactionDate = SettlementDate; MemorialBooking.Description = "Settlement Difference"; IGLAccount glAcctA = BankSettlements[0].GLAccount; IGLAccount glAcctB = settleDiffGLAccount; IJournalEntryLine sideA = new JournalEntryLine(); sideA.GLAccount = glAcctA; sideA.Balance = diff.Negate(); sideA.Description = MemorialBooking.Description; sideA.IsSettledStatus = true; sideA.ValueDate = SettlementDate; MemorialBooking.Lines.AddJournalEntryLine(sideA); IJournalEntryLine sideB = new JournalEntryLine(); sideB.GLAccount = glAcctB; sideB.Balance = diff; sideB.Description = MemorialBooking.Description; sideB.IsSettledStatus = true; sideB.ValueDate = SettlementDate; MemorialBooking.Lines.AddJournalEntryLine(sideB); MemorialBooking.BookLines(); } success = true; } return success; }