internal PersistenceContextEnlistment(PersistenceContext context, Transaction transaction)
        {
            this.transaction = transaction;

            this.enlistedContexts = new List<PersistenceContext>();
            this.enlistedContexts.Add(context);
        }
        internal TransactionWaitAsyncResult(Transaction transaction, PersistenceContext persistenceContext, TimeSpan timeout, AsyncCallback callback, object state)
            : base(callback, state)
        {
            bool completeSelf = false;
            TransactionException exception = null;
            this.PersistenceContext = persistenceContext;
            this.thisLock = new object();

            if (null != transaction)
            {
                // We want an "blocking" dependent transaction because we want to ensure the transaction
                // does not commit successfully while we are still waiting in the queue for the PC transaction
                // lock.
                this.dependentTransaction = transaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
            }
            else
            {
                this.dependentTransaction = null;
            }

            // Put a lock around this and Complete() in case the transaction we are queueing up behind
            // finishes and we end up calling Complete() before we actually finish constructing this
            // object by creating the DependentClone and setting up the IOThreadTimer.
            lock (ThisLock)
            {
                if (persistenceContext.QueueForTransactionLock(transaction, this))
                {
                    // If we were given a transaction in our constructor, we need to 
                    // create a volatile enlistment on it and complete the
                    // dependent clone that we created. This will allow the transaction to commit
                    // successfully when the time comes.
                    if (null != transaction)
                    {
                        // We are not going async, so we need to complete our dependent clone now.
                        this.dependentTransaction.Complete();

                        exception = this.CreateVolatileEnlistment(transaction);
                    }
                    completeSelf = true;
                }
                else
                {
                    // If the timeout value is not TimeSpan.MaxValue, start a timer.
                    if (timeout != TimeSpan.MaxValue)
                    {
                        this.timer = new IOThreadTimer(TimeoutCallbackAction, this, true);
                        this.timer.Set(timeout);
                    }
                }
            }

            // We didn't want to call Complete while holding the lock.
            if (completeSelf)
            {
                base.Complete(true, exception);
            }
        }
Esempio n. 3
0
 private static void Main(string[] args)
 {
     var context = new PersistenceContext();
     new DbDataDeleter(context).DeleteAllData();
     new DbMigrator(new MigrationConfiguration()).Update();
     new DataGenerator(context, EnvironmentEnum.Dev).Generate();
     Console.Out.WriteLine("Press any key to continue...");
     Console.ReadKey();
 }
 internal void AddToEnlistment(PersistenceContext context)
 {
     lock (this.ThisLock)
     {
         if (this.tooLateForMoreUndo)
         {
             throw FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activities.SR.PersistenceTooLateToEnlist));
         }
         this.enlistedContexts.Add(context);
     }
 }
 private WorkflowServiceInstance(Activity workflowDefinition, Guid instanceId, WorkflowServiceHost serviceHost, PersistenceContext persistenceContext) : base(workflowDefinition)
 {
     this.serviceHost = serviceHost;
     this.instanceId = instanceId;
     this.persistTimeout = serviceHost.PersistTimeout;
     this.trackTimeout = serviceHost.TrackTimeout;
     this.bufferedReceiveManager = serviceHost.Extensions.Find<System.ServiceModel.Activities.Dispatcher.BufferedReceiveManager>();
     if (persistenceContext != null)
     {
         this.persistenceContext = persistenceContext;
         this.persistenceContext.Closed += new EventHandler(this.OnPersistenceContextClosed);
     }
     this.thisLock = new object();
     this.pendingRequests = new List<WorkflowOperationContext>();
     this.executorLock = new WorkflowExecutionLock(this);
     this.activeOperationsLock = new object();
     this.acquireReferenceSemaphore = new ThreadNeutralSemaphore(1);
     this.acquireLockTimeout = TimeSpan.MaxValue;
     this.referenceCount = 1;
     this.TryAddReference();
 }
        internal void RemoveAssociations(PersistenceContext context, IEnumerable<InstanceKey> keys)
        {
            Fx.Assert(context != null, "RemoveAssociation cannot have a null context.");
            Fx.Assert(keys != null, "Cannot call RemoveAssociation with empty keys.");

            lock (ThisLock)
            {
                if (context.IsPermanentlyRemoved)
                {
                    return;
                }
                Fx.Assert(context.IsVisible, "Cannot remove associations from a context that's not visible.");

                foreach (InstanceKey key in keys)
                {
                    if (context.AssociatedKeys.Remove(key))
                    {
                        Fx.AssertAndThrow(this.instanceCache != null, "Since the context must be visible, it must still be in the cache.");

                        Fx.Assert(this.keyMap[key.Value] == context, "Context's keys must be in the map.");
                        this.keyMap.Remove(key.Value);
                    }
                }
            }
        }
            bool AddToCache()
            {
                Fx.Assert(!this.context.IsVisible, "Adding context which has already been added.");
                Fx.Assert(!this.context.IsPermanentlyRemoved, "Context could not already have been removed.");

                lock (this.ppd.ThisLock)
                {
                    this.ppd.ThrowIfClosedOrAborted();

                    // The InstanceStore is responsible for detecting and resolving ----s between creates.  If there is no store, we
                    // do it here, taking advantage of the lock.  We don't do it as part of the initial lookup in order to avoid
                    // holding the lock while acquiring the throttle.  Instead, we recheck here.  If we find it, we didn't need the
                    // throttle after all - it is released in cleanup (as is the PersistenceContext that got created).  If we don't
                    // find it, we add it atomically under the same lock.
                    if (this.ppd.store == null)
                    {
                        if (this.key == null)
                        {
                            this.ppd.instanceCache.TryGetValue(this.suggestedIdOrId, out this.result);
                        }
                        else
                        {
                            this.ppd.keyMap.TryGetValue(this.key.Value, out this.result);
                        }

                        if (this.result != null)
                        {
                            return true;
                        }

                        // In the case when there is no store, if key collision is detected, the current instance will be aborted later.
                        // We should not add any of its keys to the keyMap.
                        foreach (InstanceKey instanceKey in this.context.AssociatedKeys)
                        {
                            PersistenceContext conflictingContext;
                            if (this.ppd.keyMap.TryGetValue(instanceKey.Value, out conflictingContext))
                            {
                                throw FxTrace.Exception.AsError(new InstanceKeyCollisionException(null, this.context.InstanceId, instanceKey, conflictingContext.InstanceId));
                            }
                        }
                    }

                    if (!this.context.IsHandleValid)
                    {
                        // If the handle is already invalid, don't boot other instances out of the cache.
                        // If the handle is valid here, that means any PersistenceContexts in the cache under this lock
                        // must be stale - the persistence framework doesn't allow multiple valid handles.
                        throw FxTrace.Exception.AsError(new OperationCanceledException(SR.HandleFreedInDirectory));
                    }

                    this.context.IsVisible = true;

                    PersistenceContext contextToAbort;
                    if (this.ppd.instanceCache.TryGetValue(this.context.InstanceId, out contextToAbort))
                    {
                        // This is a known race condition. An instace we have loaded can get unlocked, get keys
                        // added to it, then get loaded a second time by one of the new keys.  We don't realize
                        // its happened until this point.
                        //
                        // The guarantee we give is that the old copy will be aborted before we return.  The
                        // new instance should not be processed (resumed) until after Load returns.
                        //
                        // For new instances, this could happen because the instance was deleted
                        // through a management interface or cleaned up.
                        this.ppd.DetachContext(contextToAbort, ref this.contextsToAbort);
                    }

                    foreach (InstanceKey loadedKey in this.context.AssociatedKeys)
                    {
                        if (this.ppd.keyMap.TryGetValue(loadedKey.Value, out contextToAbort))
                        {
                            Fx.Assert(this.ppd.store != null, "When there is no store, exception should have already been thrown before we get here.");
                            this.ppd.DetachContext(contextToAbort, ref this.contextsToAbort);
                        }
                        this.ppd.keyMap.Add(loadedKey.Value, this.context);
                    }

                    try
                    {
                    }
                    finally
                    {
                        this.ppd.instanceCache.Add(this.context.InstanceId, this.context);
                        this.loadPending = false;
                    }
                }

                this.addedToCacheResult = true;
                this.result = this.context;
                this.context = null;

                return true;
            }
        protected override GenerateTestDataResponse RunInContext(GenerateTestDataRequest request, PersistenceContext context)
        {
            var session = context.Session;

            session.Delete("from Invoice");
            session.Delete("from Product");
            session.Delete("from Customer");
            session.Delete("from Enterprise");

            session.Flush();
            //IQuery q1 = session.CreateQuery("from Enterprise");
            //var l1 = q1.List<Enterprise>();



            //IQuery q2 = session.CreateQuery("from Enterprise");
            //var l2 = q2.List<Enterprise>();



            Enterprise e1 = new Enterprise()
            {
                Code = "1",
                Name = "Roca Computacion"
            };

            session.Save(e1);

            //IQuery q3 = session.CreateQuery("from Enterprise");
            //var l3 = q3.List<Enterprise>();

            Customer c1 = new Customer()
            {
                Name       = "Andrés Moschini",
                Address    = "Calle Falsa 123",
                Code       = "1",
                FiscalId   = "20-26937659-8",
                FiscalType = "MONOTRIBUTISTA"
            };

            session.Save(c1);

            Product p1 = new Product()
            {
                Code  = "1",
                Name  = "Arroz",
                Taxes = 0.2
            };

            session.Save(p1);

            Invoice i1 = new Invoice()
            {
                Enterprise = e1,
                Customer   = c1,
                Date       = DateTime.Now,
                FiscalType = "A",
                Number     = "123456",
                Items      = new List <InvoiceItem>()
                {
                    new InvoiceItem()
                    {
                        Price    = 10,
                        Product  = p1,
                        Quantity = 10
                    }
                }
            };

            session.Save(i1);

            return(new GenerateTestDataResponse());
        }
Esempio n. 9
0
 protected override ListProductsResponse RunInContext(ListProductsRequest request, PersistenceContext context)
 {
     //IList<Lines.ILineProduct> list = context.Session.CreateCriteria(typeof(Entities.Product)).List<Lines.ILineProduct>();
     //return new ListProductsResponse() { List = list };
     /***/
     return(new ListProductsResponse());
 }
Esempio n. 10
0
        public MergeOrderResponse MergeOrder(MergeOrderRequest request)
        {
            Platform.CheckForNullReference(request, "request");
            Platform.CheckMemberIsSet(request.SourceOrderRefs, "SourceOrderRefs");
            Platform.CheckTrue(request.SourceOrderRefs.Count > 0, "SourceOrderRefs.Count > 0");
            Platform.CheckMemberIsSet(request.DestinationOrderRef, "DestinationOrderRef");

            var response = new MergeOrderResponse();

            DryRunHelper(request.DryRun,
                         delegate
            {
                var destinationOrder = this.PersistenceContext.Load <Order>(request.DestinationOrderRef);
                var sourceOrders     = CollectionUtils.Map(request.SourceOrderRefs, (EntityRef r) => PersistenceContext.Load <Order>(r));
                var mergeInfo        = new OrderMergeInfo(this.CurrentUserStaff, Platform.Time, destinationOrder);

                MergeOrderHelper(destinationOrder, sourceOrders, mergeInfo, request.ValidationOnly);

                if (request.DryRun)
                {
                    var orderAssembler = new OrderAssembler();
                    var orderDetail    = orderAssembler.CreateOrderDetail(destinationOrder,
                                                                          OrderAssembler.CreateOrderDetailOptions.GetVerboseOptions(), PersistenceContext);
                    response.DryRunMergedOrder = orderDetail;
                }
            });
            return(response);
        }
        // note: this operation is not protected with ClearCanvas.Ris.Application.Common.AuthorityTokens.ExternalPractitionerAdmin
        // because it is used in non-admin situations - perhaps we need to create a separate operation???
        public ListExternalPractitionersResponse ListExternalPractitioners(ListExternalPractitionersRequest request)
        {
            var assembler = new ExternalPractitionerAssembler();

            var criteria = new ExternalPractitionerSearchCriteria();

            if (request.SortByLastVerifiedTime)
            {
                if (request.SortAscending)
                {
                    criteria.LastVerifiedTime.SortAsc(0);
                }
                else
                {
                    criteria.LastVerifiedTime.SortDesc(0);
                }
            }
            else if (request.SortByLastEditedTime)
            {
                if (request.SortAscending)
                {
                    criteria.LastEditedTime.SortAsc(0);
                }
                else
                {
                    criteria.LastEditedTime.SortDesc(0);
                }
            }
            else
            {
                criteria.Name.FamilyName.SortAsc(0);
            }

            if (!string.IsNullOrEmpty(request.FirstName))
            {
                criteria.Name.GivenName.StartsWith(request.FirstName);
            }
            if (!string.IsNullOrEmpty(request.LastName))
            {
                criteria.Name.FamilyName.StartsWith(request.LastName);
            }

            switch (request.VerifiedState)
            {
            case VerifiedState.Verified:
                criteria.IsVerified.EqualTo(true);
                break;

            case VerifiedState.NotVerified:
                criteria.IsVerified.EqualTo(false);
                break;
            }

            if (request.LastVerifiedRangeFrom != null && request.LastVerifiedRangeUntil != null)
            {
                criteria.LastVerifiedTime.Between(request.LastVerifiedRangeFrom, request.LastVerifiedRangeUntil);
            }
            else if (request.LastVerifiedRangeFrom != null)
            {
                criteria.LastVerifiedTime.MoreThanOrEqualTo(request.LastVerifiedRangeFrom);
            }
            else if (request.LastVerifiedRangeUntil != null)
            {
                criteria.LastVerifiedTime.LessThanOrEqualTo(request.LastVerifiedRangeUntil);
            }

            if (!request.IncludeMerged)
            {
                criteria.MergedInto.IsNull();
            }

            if (!request.IncludeDeactivated)
            {
                criteria.Deactivated.EqualTo(false);
            }

            var results = new List <ExternalPractitionerSummary>();

            if (request.QueryItems)
            {
                results = CollectionUtils.Map <ExternalPractitioner, ExternalPractitionerSummary, List <ExternalPractitionerSummary> >(
                    PersistenceContext.GetBroker <IExternalPractitionerBroker>().Find(criteria, request.Page),
                    s => assembler.CreateExternalPractitionerSummary(s, PersistenceContext));
            }

            var itemCount = -1;

            if (request.QueryCount)
            {
                itemCount = (int)PersistenceContext.GetBroker <IExternalPractitionerBroker>().Count(criteria);
            }

            return(new ListExternalPractitionersResponse(results, itemCount));
        }
        public WorkflowServiceInstance InitializeInstance(Guid instanceId, PersistenceContext context, IDictionary<XName, InstanceValue> instance, WorkflowCreationContext creationContext)
        {
            Activity workflowDefinition = null;
            this.workflowDefinitionProvider.TryGetDefinition(this.workflowDefinitionProvider.DefaultDefinitionIdentity, out workflowDefinition);
            Fx.Assert(workflowDefinition != null, "Default definition shouldn't be null.");

            return WorkflowServiceInstance.InitializeInstance(context, instanceId, workflowDefinition, this.workflowDefinitionProvider.DefaultDefinitionIdentity, instance, creationContext,
                WorkflowSynchronizationContext.Instance, this.serviceHost);
        }
Esempio n. 13
0
 public KeywordRepository(PersistenceContext context) : base(context)
 {
 }
        protected override void RunInContextEmptyResponse(UpdateCompleteAccountTreeRequest request, PersistenceContext context)
        {
            foreach (Guid id in request.DeletedTreesIds)
            {
                AccountTree entity = context.Session.Load <AccountTree>(id);
                entity.MarkAsDelete();
            }

            context.Session.Flush(); //por los uniques

            foreach (UI.AccountTreeListItem ui in request.UpdatedTrees)
            {
                AccountTree entity = context.Session.Load <AccountTree>(ui.Id);
                ui.CopyTo(entity);
            }

            context.Session.Flush(); //por los uniques

            foreach (UI.AccountTreeListItem ui in request.CreatedTrees)
            {
                AccountTree entity = new AccountTree(ui.Id);
                ui.CopyTo(entity);
                context.Session.Save(entity);
            }

            foreach (UI.ContableAccount ui in request.UpdatedAccounts)
            {
                ContableAccount entity = context.Session.Load <ContableAccount>(ui.Id);
                ui.CopyTo(entity); //las modificaciones sin cambio de padres
                entity.AccountTree = context.Session.Load <AccountTree>(ui.AccountTreeId);
            }

            foreach (UI.ContableAccount ui in request.CreatedAccounts)
            {
                ContableAccount entity = new ContableAccount(ui.Id);
                ui.CopyTo(entity);
                entity.AccountTree = context.Session.Load <AccountTree>(ui.AccountTreeId);
                context.Session.Save(entity); //los grabo sin padre
            }

            //para cada una de las modificadas o creadas les pongo el padre
            foreach (UI.ContableAccount ui in request.UpdatedAccounts.Union(request.CreatedAccounts))
            {
                ContableAccount entity = context.Session.Load <ContableAccount>(ui.Id);
                if (ui.ParentAccountId.HasValue)
                {
                    entity.ParentAccount = context.Session.Load <ContableAccount>(ui.ParentAccountId.Value);
                }
                else
                {
                    entity.ParentAccount = null;
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Updates a material's price table entry
        /// </summary>
        /// <param name="modelView">model view with the update information</param>
        /// <returns></returns>
        public static GetMaterialPriceModelView update(UpdatePriceTableEntryModelView modelView, IHttpClientFactory clientFactory)
        {
            string             defaultCurrency    = CurrencyPerAreaConversionService.getBaseCurrency();
            string             defaultArea        = CurrencyPerAreaConversionService.getBaseArea();
            MaterialRepository materialRepository = PersistenceContext.repositories().createMaterialRepository();
            long materialId = modelView.entityId;

            bool performedAtLeastOneUpdate = false;

            Material material = materialRepository.find(materialId);

            if (material == null)
            {
                throw new ResourceNotFoundException(MATERIAL_NOT_FOUND);
            }

            MaterialPriceTableRepository materialPriceTableRepository = PersistenceContext.repositories().createMaterialPriceTableRepository();
            long materialPriceTableEntryId = modelView.tableEntryId;

            IEnumerable <MaterialPriceTableEntry> allEntries = materialPriceTableRepository.findAll();

            if (allEntries == null || !allEntries.Any())
            {
                throw new ResourceNotFoundException(NO_ENTRIES_FOUND);
            }

            MaterialPriceTableEntry tableEntryToUpdate = materialPriceTableRepository.find(materialPriceTableEntryId);

            if (tableEntryToUpdate == null)
            {
                throw new ResourceNotFoundException(ENTRY_NOT_FOUND);
            }

            if (tableEntryToUpdate.entity.Id != modelView.entityId)
            {
                throw new InvalidOperationException(ENTRY_DOESNT_BELONG_TO_MATERIAL);
            }

            LocalDateTime currentTime = NodaTime.LocalDateTime.FromDateTime(SystemClock.Instance.GetCurrentInstant().ToDateTimeUtc());

            if (modelView.priceTableEntry.endingDate != null && !LocalDateTimePattern.GeneralIso.Format(tableEntryToUpdate.timePeriod.startingDate).Equals(modelView.priceTableEntry.startingDate))
            {
                if (tableEntryToUpdate.timePeriod.startingDate.CompareTo(currentTime) < 0)
                {
                    throw new InvalidOperationException(PAST_DATE);
                }
            }

            if (modelView.priceTableEntry.startingDate != null && !LocalDateTimePattern.GeneralIso.Format(tableEntryToUpdate.timePeriod.endingDate).Equals(modelView.priceTableEntry.endingDate))
            {
                if (tableEntryToUpdate.timePeriod.endingDate.CompareTo(currentTime) < 0)
                {
                    throw new InvalidOperationException(PAST_DATE);
                }
            }

            if (modelView.priceTableEntry.price != null)
            {
                CurrenciesService.checkCurrencySupport(modelView.priceTableEntry.price.currency);
                AreasService.checkAreaSupport(modelView.priceTableEntry.price.area);

                Price newPrice = null;
                try
                {
                    if (defaultCurrency.Equals(modelView.priceTableEntry.price.currency) && defaultArea.Equals(modelView.priceTableEntry.price.area))
                    {
                        newPrice = Price.valueOf(modelView.priceTableEntry.price.value);
                    }
                    else
                    {
                        Task <double> convertedValueTask = new CurrencyPerAreaConversionService(clientFactory)
                                                           .convertCurrencyPerAreaToDefaultCurrencyPerArea(
                            modelView.priceTableEntry.price.currency,
                            modelView.priceTableEntry.price.area,
                            modelView.priceTableEntry.price.value);
                        convertedValueTask.Wait();
                        double convertedValue = convertedValueTask.Result;
                        newPrice = Price.valueOf(convertedValue);
                    }
                }
                catch (HttpRequestException)
                {
                    newPrice = Price.valueOf(modelView.priceTableEntry.price.value);
                }

                tableEntryToUpdate.changePrice(newPrice);
                performedAtLeastOneUpdate = true;
            }

            if (modelView.priceTableEntry.endingDate != null)
            {
                LocalDateTime newEndingDate;
                try
                {
                    string newEndingDateAsString = modelView.priceTableEntry.endingDate;
                    newEndingDate = LocalDateTimePattern.GeneralIso.Parse(newEndingDateAsString).GetValueOrThrow();
                    tableEntryToUpdate.changeTimePeriod(TimePeriod.valueOf(tableEntryToUpdate.timePeriod.startingDate, newEndingDate));
                    performedAtLeastOneUpdate = true;
                }
                catch (UnparsableValueException)
                {
                    throw new UnparsableValueException(DATES_WRONG_FORMAT + LocalDateTimePattern.GeneralIso.PatternText);
                }
            }

            if (modelView.priceTableEntry.startingDate != null)
            {
                LocalDateTime newStartingDate;
                try
                {
                    string newStartingDateAsString = modelView.priceTableEntry.startingDate;
                    newStartingDate = LocalDateTimePattern.GeneralIso.Parse(newStartingDateAsString).GetValueOrThrow();
                    tableEntryToUpdate.changeTimePeriod(TimePeriod.valueOf(newStartingDate, tableEntryToUpdate.timePeriod.endingDate));
                    performedAtLeastOneUpdate = true;
                }
                catch (UnparsableValueException)
                {
                    throw new UnparsableValueException(DATES_WRONG_FORMAT + LocalDateTimePattern.GeneralIso.PatternText);
                }
            }

            if (performedAtLeastOneUpdate)
            {
                MaterialPriceTableEntry updatedTableEntry = materialPriceTableRepository.update(tableEntryToUpdate);

                if (updatedTableEntry == null)
                {
                    throw new InvalidOperationException(UPDATE_NOT_SUCCESSFUL);
                }

                GetMaterialPriceModelView updatedTableEntryModelView = new GetMaterialPriceModelView();

                updatedTableEntryModelView.id           = updatedTableEntry.Id;
                updatedTableEntryModelView.materialId   = updatedTableEntry.entity.Id;
                updatedTableEntryModelView.value        = updatedTableEntry.price.value;
                updatedTableEntryModelView.currency     = defaultCurrency;
                updatedTableEntryModelView.area         = defaultArea;
                updatedTableEntryModelView.startingDate = LocalDateTimePattern.GeneralIso.Format(updatedTableEntry.timePeriod.startingDate);
                updatedTableEntryModelView.endingDate   = LocalDateTimePattern.GeneralIso.Format(updatedTableEntry.timePeriod.endingDate);

                return(updatedTableEntryModelView);
            }
            throw new InvalidOperationException(UPDATE_NOT_SUCCESSFUL);
        }
Esempio n. 16
0
        private static void _NoteSeed(PersistenceContext context)
        {
            var ian  = context.Users.Where(u => u.UserId == "ian").FirstOrDefault();
            var zach = context.Users.Where(u => u.UserId == "zach").FirstOrDefault();

            var kauffman = new Models.Pin()
            {
                Latitude  = 40.819661,
                Longitude = -96.70041,
                Name      = "Kauffman",
                PinId     = "kauf"
            };

            var fuse = new Models.Pin()
            {
                Latitude  = 40.81442,
                Longitude = -96.710235,
                Name      = "FUSE",
                PinId     = "fuse"
            };

            var destinations = new Models.Pin()
            {
                Latitude  = 40.826233,
                Longitude = -96.70155,
                Name      = "Destinations",
                PinId     = "dest",
            };

            kauffman.Notes = new List <Models.Note>
            {
                new Models.Note()
                {
                    Added   = DateTime.Now,
                    Content = "Make sure to teach class",
                    Pin     = kauffman,
                    NoteId  = "TN1"
                },
                new Models.Note()
                {
                    Added   = DateTime.Now,
                    Content = "Attend the weekly standup on Thursday",
                    Pin     = kauffman,
                    NoteId  = "TN2"
                },
                new Models.Note()
                {
                    Added   = DateTime.Now,
                    Content = "Don't eat the donuts",
                    Pin     = kauffman,
                    NoteId  = "TN3"
                },
            };

            fuse.Notes = new List <Models.Note>
            {
                new Models.Note()
                {
                    Added   = DateTime.Now,
                    Content = "Use the FUSE wifi, it is faster than DPL",
                    Pin     = fuse,
                    NoteId  = "TN4"
                },
                new Models.Note()
                {
                    Added   = DateTime.Now,
                    Content = "Avoid the elevator",
                    Pin     = fuse,
                    NoteId  = Guid.NewGuid().ToString()
                }
            };

            destinations.Notes = new List <Models.Note>
            {
                new Models.Note()
                {
                    Added   = DateTime.Now,
                    Content = "Grab a coffee before heading to Kauffman, you'll thank yourself later",
                    Pin     = destinations,
                    NoteId  = "TN5"
                },
                new Models.Note()
                {
                    Added   = DateTime.Now,
                    Content = "It's a longer walk than you think",
                    Pin     = destinations,
                    NoteId  = "TN6"
                }
            };

            ian.Pins = new List <Models.Pin> {
                kauffman, fuse
            };
            zach.Pins = new List <Models.Pin> {
                destinations
            };

            context.Entry(ian).State  = EntityState.Modified;
            context.Entry(zach).State = EntityState.Modified;

            context.SaveChanges();
        }
Esempio n. 17
0
 public static void Seed(PersistenceContext context)
 {
     // seed some data
     _UserSeed(context);
     _NoteSeed(context);
 }
        /// <summary>
        /// Transforms and creates a finish price table entry
        /// </summary>
        /// <param name="modelView">model view with the necessary info to create a finish price table entry</param>
        /// <param name="clientFactory">injected client factory</param>
        /// <returns></returns>
        public static GetMaterialFinishPriceModelView create(AddFinishPriceTableEntryModelView modelView, IHttpClientFactory clientFactory)
        {
            string             defaultCurrency    = CurrencyPerAreaConversionService.getBaseCurrency();
            string             defaultArea        = CurrencyPerAreaConversionService.getBaseArea();
            MaterialRepository materialRepository = PersistenceContext.repositories().createMaterialRepository();
            long materialId = modelView.entityId;

            Material material = materialRepository.find(materialId);

            if (material == null)
            {
                throw new ResourceNotFoundException(MATERIAL_NOT_FOUND);
            }

            //TODO Is this null check enough? Should we check ,if an entry exists, that the time period of the price entry is valid?
            MaterialPriceTableEntry materialPriceTableEntry = PersistenceContext.repositories().createMaterialPriceTableRepository().find(materialId);

            if (materialPriceTableEntry == null)
            {
                throw new InvalidOperationException(MATERIAL_HAS_NO_PRICE);
            }

            foreach (Finish finish in material.Finishes)
            {
                if (finish.Id == modelView.finishId)
                {
                    string startingDateAsString = modelView.priceTableEntry.startingDate;
                    string endingDateAsString   = modelView.priceTableEntry.endingDate;

                    LocalDateTime startingDate;
                    LocalDateTime endingDate;
                    LocalDateTime currentTime = NodaTime.LocalDateTime.FromDateTime(SystemClock.Instance.GetCurrentInstant().ToDateTimeUtc());

                    try
                    {
                        startingDate = LocalDateTimePattern.GeneralIso.Parse(startingDateAsString).GetValueOrThrow();

                        if (startingDate.CompareTo(currentTime) < 0)
                        {
                            throw new InvalidOperationException(PAST_DATE);
                        }
                    }
                    catch (UnparsableValueException)
                    {
                        throw new UnparsableValueException(DATES_WRONG_FORMAT + LocalDateTimePattern.GeneralIso.PatternText);
                    }

                    TimePeriod timePeriod = null;

                    if (endingDateAsString != null)
                    {
                        try
                        {
                            endingDate = LocalDateTimePattern.GeneralIso.Parse(endingDateAsString).GetValueOrThrow();

                            if (endingDate.CompareTo(currentTime) < 0)
                            {
                                throw new InvalidOperationException(PAST_DATE);
                            }

                            timePeriod = TimePeriod.valueOf(startingDate, endingDate);
                        }
                        catch (UnparsableValueException)
                        {
                            throw new UnparsableValueException(DATES_WRONG_FORMAT + LocalDateTimePattern.GeneralIso.PatternText);
                        }
                    }
                    else
                    {
                        timePeriod = TimePeriod.valueOf(startingDate);
                    }

                    CurrenciesService.checkCurrencySupport(modelView.priceTableEntry.price.currency);
                    AreasService.checkAreaSupport(modelView.priceTableEntry.price.area);

                    Price price = null;
                    try
                    {
                        if (defaultCurrency.Equals(modelView.priceTableEntry.price.currency) && defaultArea.Equals(modelView.priceTableEntry.price.area))
                        {
                            price = Price.valueOf(modelView.priceTableEntry.price.value);
                        }
                        else
                        {
                            Task <double> convertedValueTask = new CurrencyPerAreaConversionService(clientFactory)
                                                               .convertCurrencyPerAreaToDefaultCurrencyPerArea(
                                modelView.priceTableEntry.price.currency,
                                modelView.priceTableEntry.price.area,
                                modelView.priceTableEntry.price.value);
                            convertedValueTask.Wait();
                            double convertedValue = convertedValueTask.Result;
                            price = Price.valueOf(convertedValue);
                        }
                    }
                    catch (HttpRequestException)
                    {
                        price = Price.valueOf(modelView.priceTableEntry.price.value);
                    }

                    FinishPriceTableEntry finishPriceTableEntry      = new FinishPriceTableEntry(material.id(), finish, price, timePeriod);
                    FinishPriceTableEntry savedFinishPriceTableEntry = PersistenceContext.repositories()
                                                                       .createFinishPriceTableRepository().save(finishPriceTableEntry);

                    if (savedFinishPriceTableEntry == null)
                    {
                        throw new InvalidOperationException(PRICE_TABLE_ENTRY_NOT_CREATED);
                    }

                    GetMaterialFinishPriceModelView createdPriceModelView = new GetMaterialFinishPriceModelView();

                    createdPriceModelView.startingDate = LocalDateTimePattern.GeneralIso.Format(savedFinishPriceTableEntry.timePeriod.startingDate);
                    createdPriceModelView.endingDate   = LocalDateTimePattern.GeneralIso.Format(savedFinishPriceTableEntry.timePeriod.endingDate);
                    createdPriceModelView.value        = savedFinishPriceTableEntry.price.value;
                    createdPriceModelView.currency     = defaultCurrency;
                    createdPriceModelView.area         = defaultArea;
                    createdPriceModelView.finishId     = finish.Id;
                    createdPriceModelView.id           = savedFinishPriceTableEntry.Id;

                    return(createdPriceModelView);
                }
            }
            throw new ResourceNotFoundException(FINISH_NOT_FOUND);
        }
Esempio n. 19
0
 public MaterialDTO findMaterialByReference(string reference)
 {
     return(PersistenceContext.repositories().createMaterialRepository().find(reference).toDTO());
 }
        // For transactional uses, call this method on commit.
        internal void RemoveInstance(PersistenceContext context, bool permanent)
        {
            Fx.Assert(context != null, "RemoveInstance cannot have a null context.");

            lock (ThisLock)
            {
                if (permanent)
                {
                    context.IsPermanentlyRemoved = true;
                }
                DetachContext(context);
            }
        }
        void DetachContext(PersistenceContext contextToAbort)
        {
            if (contextToAbort.IsVisible)
            {
                Fx.Assert(this.instanceCache != null, "All contexts should not be visible if we are closed / aborted.");

                foreach (InstanceKey key in contextToAbort.AssociatedKeys)
                {
                    Fx.Assert(this.keyMap[key.Value] == contextToAbort, "Context's key must be in the map.");
                    this.keyMap.Remove(key.Value);
                }

                try
                {
                }
                finally
                {
                    if (this.instanceCache.Remove(contextToAbort.InstanceId))
                    {
                        contextToAbort.IsVisible = false;
                        this.throttle.Exit();
                    }
                    else
                    {
                        Fx.Assert("Context must be in the cache.");
                    }
                }
            }
        }
        /// <summary>
        /// Updates an instance of CustomizedProduct with the data provided in the given UpdateCustomizedProductModelView.
        /// </summary>
        /// <param name="updateCustomizedProductModelView">Instance of UpdateCustomizedProductModelView containing updated CustomizedProduct information.</param>
        /// <returns>An instance of GetCustomizedProductModelView with the updated CustomizedProduct information.</returns>
        /// <exception cref="ResourceNotFoundException">Thrown when the CustomizedProduct could not be found.</exception>
        /// <exception cref="System.ArgumentException">Thrown when none of the CustomizedProduct's properties are updated.</exception>
        public GetCustomizedProductModelView updateCustomizedProduct(UpdateCustomizedProductModelView updateCustomizedProductModelView)
        {
            CustomizedProductRepository customizedProductRepository = PersistenceContext.repositories().createCustomizedProductRepository();

            CustomizedProduct customizedProduct = customizedProductRepository.find(updateCustomizedProductModelView.customizedProductId);

            if (customizedProduct == null)
            {
                throw new ResourceNotFoundException(string.Format(ERROR_UNABLE_TO_FIND_CUSTOMIZED_PRODUCT_BY_ID, updateCustomizedProductModelView.customizedProductId));
            }

            checkUserToken(customizedProduct, updateCustomizedProductModelView.userAuthToken);

            bool performedAtLeastOneUpdate = false;

            if (updateCustomizedProductModelView.reference != null)
            {
                customizedProduct.changeReference(updateCustomizedProductModelView.reference);
                performedAtLeastOneUpdate = true;
            }

            if (updateCustomizedProductModelView.designation != null)
            {
                customizedProduct.changeDesignation(updateCustomizedProductModelView.designation);
                performedAtLeastOneUpdate = true;
            }

            if (updateCustomizedProductModelView.customizedMaterial != null)
            {
                //TODO: check if only the finish or the color are being updated
                CustomizedMaterial customizedMaterial = CreateCustomizedMaterialService.create(updateCustomizedProductModelView.customizedMaterial);

                customizedProduct.changeCustomizedMaterial(customizedMaterial);
                performedAtLeastOneUpdate = true;
            }

            if (updateCustomizedProductModelView.customizedDimensions != null)
            {
                customizedProduct.changeDimensions(CustomizedDimensionsModelViewService.fromModelView(updateCustomizedProductModelView.customizedDimensions));
                performedAtLeastOneUpdate = true;
            }

            if (updateCustomizedProductModelView.customizationStatus == CustomizationStatus.FINISHED)
            {
                customizedProduct.finalizeCustomization();
                performedAtLeastOneUpdate = true;
            }

            if (!performedAtLeastOneUpdate)
            {
                throw new ArgumentException(ERROR_NO_UPDATE_PERFORMED);
            }

            customizedProduct = customizedProductRepository.update(customizedProduct);

            if (customizedProduct == null)
            {
                throw new ArgumentException(ERROR_UNABLE_TO_SAVE_CUSTOMIZED_PRODUCT);
            }

            return(CustomizedProductModelViewService.fromEntity(customizedProduct));
        }
        public MergeDuplicateContactPointResponse MergeDuplicateContactPoint(MergeDuplicateContactPointRequest request)
        {
            Platform.CheckForNullReference(request, "request");
            Platform.CheckMemberIsSet(request.RetainedContactPointRef, "RetainedContactPointRef");
            Platform.CheckMemberIsSet(request.ReplacedContactPointRef, "ReplacedContactPointRef");

            var dest = PersistenceContext.Load <ExternalPractitionerContactPoint>(request.RetainedContactPointRef, EntityLoadFlags.Proxy);
            var src  = PersistenceContext.Load <ExternalPractitionerContactPoint>(request.ReplacedContactPointRef, EntityLoadFlags.Proxy);

            // if we are only doing a cost estimate, exit here without modifying any data
            if (request.EstimateCostOnly)
            {
                // compute cost estimate.  Need to include affected records of both src and dest, because both will be merged and deactivated.
                var cost = EstimateAffectedRecords(dest, src);
                return(new MergeDuplicateContactPointResponse(cost));
            }

            // combine all phone numbers and addresses, expiring those from the src object
            var allPhoneNumbers = CollectionUtils.Concat(
                CloneAndExpire(dest.TelephoneNumbers, tn => tn.ValidRange, false),
                CloneAndExpire(src.TelephoneNumbers, tn => tn.ValidRange, true));
            var allAddresses = CollectionUtils.Concat(
                CloneAndExpire(dest.Addresses, tn => tn.ValidRange, false),
                CloneAndExpire(src.Addresses, tn => tn.ValidRange, true));
            var allEmailAddresses = CollectionUtils.Concat(
                CloneAndExpire(dest.EmailAddresses, tn => tn.ValidRange, false),
                CloneAndExpire(src.EmailAddresses, tn => tn.ValidRange, true));

            // merge contact points
            var result = ExternalPractitionerContactPoint.MergeContactPoints(
                dest,
                src,
                dest.Name,
                dest.Description,
                dest.PreferredResultCommunicationMode,
                dest.InformationAuthority,
                allPhoneNumbers,
                allAddresses,
                allEmailAddresses);

            PersistenceContext.Lock(result, DirtyState.New);

            // if user has verify permission, verify the practitioner
            if (Thread.CurrentPrincipal.IsInRole(AuthorityTokens.Admin.Data.ExternalPractitionerVerification))
            {
                result.Practitioner.MarkVerified();
            }

            // queue work items to migrate orders
            foreach (var contactPoint in new[] { src, dest })
            {
                var queueItem = MergeWorkQueueItem.Create(contactPoint.GetRef());
                PersistenceContext.Lock(queueItem, DirtyState.New);
            }

            PersistenceContext.SynchState();

            var assembler = new ExternalPractitionerAssembler();

            return(new MergeDuplicateContactPointResponse(assembler.CreateExternalPractitionerContactPointSummary(result)));
        }
Esempio n. 24
0
        public override IEnumerable <IStreamPersister> CreatePersisters(PersistenceContext context)
        {
            var absolutePath = Path.Combine(context.TargetDirectory.FullName, _globPathFunc(), context.Filename);

            yield return(new FilePersister(absolutePath));
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     persistenceContext = PersistenceHelper.CreatePersistenceContext();
     base.OnActionExecuting(filterContext);
 }
 protected override void RunInContextEmptyResponse(CreateAccountTreeRequest request, PersistenceContext context)
 {
     context.Session.Save(request.AccountTree);
 }
Esempio n. 27
0
        private void UpdateProceduresHelper(Order order, IEnumerable <ProcedureRequisition> procedureReqs, ModifyOrderRequest request)
        {
            // do not update the procedures if the order is completed
            if (order.IsTerminated)
            {
                return;
            }

            var assembler = new OrderEntryAssembler();

            // if any procedure is in downtime recovery mode, assume the entire order is a "downtime order"
            var isDowntime = CollectionUtils.Contains(order.Procedures, p => p.DowntimeRecoveryMode);

            // separate the list into additions and updates
            var existingReqs = new List <ProcedureRequisition>();
            var addedReqs    = new List <ProcedureRequisition>();

            foreach (var req in procedureReqs)
            {
                if (CollectionUtils.Contains(order.Procedures, x => req.ProcedureNumber == x.Number))
                {
                    existingReqs.Add(req);
                }
                else
                {
                    addedReqs.Add(req);
                }
            }

            // process the additions first, so that we don't accidentally cancel an order (if all its procedures are cancelled momentarily)
            var procedureNumberBroker = PersistenceContext.GetBroker <IProcedureNumberBroker>();
            var dicomUidBroker        = PersistenceContext.GetBroker <IDicomUidBroker>();

            foreach (var req in addedReqs)
            {
                var requestedType = this.PersistenceContext.Load <ProcedureType>(req.ProcedureType.ProcedureTypeRef);

                // create a new procedure for this requisition
                var procedure = new Procedure(requestedType, procedureNumberBroker.GetNext(), dicomUidBroker.GetNewUid())
                {
                    DowntimeRecoveryMode = isDowntime
                };
                order.AddProcedure(procedure);

                // note: need to lock the new procedure now, prior to creating the procedure steps
                // otherwise may get exceptions saying the Procedure is a transient object
                this.PersistenceContext.Lock(procedure, DirtyState.New);

                // create the procedure steps
                procedure.CreateProcedureSteps();

                // apply the requisition information to the actual procedure
                assembler.UpdateProcedureFromRequisition(procedure, req, this.CurrentUserStaff, this.PersistenceContext);

                LogicalHL7Event.ProcedureCreated.EnqueueEvents(procedure);
            }

            // process updates
            foreach (var req in existingReqs)
            {
                var requestedType = this.PersistenceContext.Load <ProcedureType>(req.ProcedureType.ProcedureTypeRef);
                var procedure     = CollectionUtils.SelectFirst(order.Procedures, x => req.ProcedureNumber == x.Number);

                // validate that the type has not changed
                if (!procedure.Type.Equals(requestedType))
                {
                    throw new RequestValidationException(SR.InvalidRequest_CannotModifyProcedureType);
                }

                // If the procedure is already terminated, just move on to the next one since procedures cannot be "un-terminated".
                if (procedure.IsTerminated)
                {
                    continue;
                }

                // apply the requisition information to the actual procedure
                assembler.UpdateProcedureFromRequisition(procedure, req, this.CurrentUserStaff, this.PersistenceContext);

                (req.Cancelled ? LogicalHL7Event.ProcedureCancelled : LogicalHL7Event.ProcedureModified).EnqueueEvents(procedure);
            }
        }
Esempio n. 28
0
 public LaMetricController(PersistenceContext databaseContext, IDigitalstromStructureService dsStructure)
 {
     _dbContext   = databaseContext;
     _dsStructure = dsStructure;
 }
 private Facility GetWorkingFacility(QueryWorklistRequest request)
 {
     return(request.WorkingFacilityRef == null ? null :
            PersistenceContext.Load <Facility>(request.WorkingFacilityRef, EntityLoadFlags.Proxy));
 }
            bool AfterLoad()
            {
                if (!this.isInstanceInitialized)
                {
                    if (!this.canCreateInstance)
                    {
                        throw FxTrace.Exception.AsError(new InvalidOperationException(SR.PersistenceViolationNoCreate));
                    }

                    if (this.view == null)
                    {
                        this.context = new PersistenceContext(this.ppd, this.ppd.store, this.handle, this.suggestedIdOrId, null, true, false, null, null);
                    }
                    else
                    {
                        this.context = new PersistenceContext(this.ppd, this.ppd.store, this.handle, this.view.InstanceId, this.view.InstanceKeys.Values.Select((keyView) => new InstanceKey(keyView.InstanceKey, keyView.InstanceKeyMetadata)), true, true, this.view, null);
                    }
                    this.handle = null;
                }
                else
                {
                    EnsureWorkflowHostType();

                    // The constructor of PersistenceContext will create the WorkflowServiceInstance in this case.
                    this.context = new PersistenceContext(this.ppd, this.ppd.store, this.handle, this.view.InstanceId, this.view.InstanceKeys.Values.Select((keyView) => new InstanceKey(keyView.InstanceKey, keyView.InstanceKeyMetadata)), false, true, this.view, this.updatedIdentity);
                    this.handle = null;

                    IEnumerable<IPersistencePipelineModule> modules = this.context.GetInstance(null).PipelineModules;
                    if (modules != null)
                    {
                        this.pipeline = new PersistencePipeline(modules);

                        this.pipeline.SetLoadedValues(this.view.InstanceData);
                        this.ppd.RegisterPipelineInUse(this.pipeline);

                        IAsyncResult loadResult;
                        using (PrepareTransactionalCall(this.transaction))
                        {
                            loadResult = this.pipeline.BeginLoad(this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(LoadOrCreateAsyncResult.handleLoadPipeline), this);
                        }
                        return SyncContinue(loadResult);
                    }
                }

                return Finish();
            }
            bool ResolveHandleConflict()
            {
                Fx.Assert(this.loadPending, "How would we be here without a load pending?");

                this.result = this.loadAny ? null : this.ppd.LoadFromCache(this.key, this.suggestedIdOrId, this.canCreateInstance);
                if (this.result != null)
                {
                    return true;
                }
                else
                {
                    // A handle conflict occurred, but the instance still can't be found in the PPD's caches.  This can happen in three cases:
                    // 1.  The instance hasn't made it to the cache yet.
                    // 2.  The instance has already been removed from the cache.
                    // 3.  We're looking up by key, and a key association is in the database but not the cache because we are racing a key disassociation.
                    // All three of these cases are unstable and will resolve themselves in time, however none provide a notification that we can wait for.  So we keep
                    // trying in a loop.  This is a little scary, but should converge in all cases according to this analysis.
                    //
                    // This is issued on a new IO thread both to give the scenario some time to resolve (no use having too tight of a loop) and to avoid a stack dive.
                    ActionItem.Schedule(LoadOrCreateAsyncResult.handleLoadRetry, this);
                    return false;
                }
            }
 private bool AddToCache()
 {
     lock (this.ppd.ThisLock)
     {
         PersistenceContext context2;
         this.ppd.ThrowIfClosedOrAborted();
         if (this.ppd.store == null)
         {
             if (this.key == null)
             {
                 this.ppd.instanceCache.TryGetValue(this.suggestedIdOrId, out this.result);
             }
             else
             {
                 this.ppd.keyMap.TryGetValue(this.key.Value, out this.result);
             }
             if (this.result != null)
             {
                 return true;
             }
             foreach (InstanceKey key in this.context.AssociatedKeys)
             {
                 PersistenceContext context;
                 if (this.ppd.keyMap.TryGetValue(key.Value, out context))
                 {
                     throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InstanceKeyCollisionException(null, this.context.InstanceId, key, context.InstanceId));
                 }
             }
         }
         if (!this.context.IsHandleValid)
         {
             throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new OperationCanceledException(System.ServiceModel.Activities.SR.HandleFreedInDirectory));
         }
         this.context.IsVisible = true;
         if (this.ppd.instanceCache.TryGetValue(this.context.InstanceId, out context2))
         {
             this.ppd.DetachContext(context2, ref this.contextsToAbort);
         }
         foreach (InstanceKey key2 in this.context.AssociatedKeys)
         {
             if (this.ppd.keyMap.TryGetValue(key2.Value, out context2))
             {
                 this.ppd.DetachContext(context2, ref this.contextsToAbort);
             }
             this.ppd.keyMap.Add(key2.Value, this.context);
         }
         try
         {
         }
         finally
         {
             this.ppd.instanceCache.Add(this.context.InstanceId, this.context);
             this.loadPending = false;
         }
     }
     this.addedToCacheResult = true;
     this.result = this.context;
     this.context = null;
     return true;
 }
            bool Finish()
            {
                if (this.pipeline != null)
                {
                    this.pipeline.Publish();
                }

                // PersistenceContext.Open doesn't do anything, so it's ok to call sync.
                this.context.Open(TimeSpan.Zero);

                IAsyncResult result;
                using (PrepareTransactionalCall(this.transaction))
                {
                    result = this.context.BeginEnlist(this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(LoadOrCreateAsyncResult.handleContextEnlist), this);
                }
                return (SyncContinue(result));
            }
 private bool AfterLoad()
 {
     if (!this.isInstanceInitialized)
     {
         if (!this.canCreateInstance)
         {
             throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activities.SR.PersistenceViolationNoCreate));
         }
         if (this.view == null)
         {
             this.context = new PersistenceContext(this.ppd, this.ppd.store, this.handle, this.suggestedIdOrId, null, true, false, null);
         }
         else
         {
             this.context = new PersistenceContext(this.ppd, this.ppd.store, this.handle, this.view.InstanceId, from keyView in this.view.InstanceKeys.Values select new InstanceKey(keyView.InstanceKey, keyView.InstanceKeyMetadata), true, true, this.view);
         }
         this.handle = null;
     }
     else
     {
         this.EnsureWorkflowHostType();
         this.context = new PersistenceContext(this.ppd, this.ppd.store, this.handle, this.view.InstanceId, from keyView in this.view.InstanceKeys.Values select new InstanceKey(keyView.InstanceKey, keyView.InstanceKeyMetadata), false, true, this.view);
         this.handle = null;
         IEnumerable<IPersistencePipelineModule> pipelineModules = this.context.GetInstance(null).PipelineModules;
         if (pipelineModules != null)
         {
             IAsyncResult result;
             this.pipeline = new PersistencePipeline(pipelineModules);
             this.pipeline.SetLoadedValues(this.view.InstanceData);
             this.ppd.RegisterPipelineInUse(this.pipeline);
             using (base.PrepareTransactionalCall(this.transaction))
             {
                 result = this.pipeline.BeginLoad(this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleLoadPipeline), this);
             }
             return base.SyncContinue(result);
         }
     }
     return this.Finish();
 }
        internal bool TryAddAssociations(PersistenceContext context, IEnumerable<InstanceKey> keys, HashSet<InstanceKey> keysToAssociate, HashSet<InstanceKey> keysToDisassociate)
        {
            Fx.Assert(context != null, "TryAddAssociations cannot have a null context.");
            Fx.Assert(keys != null, "Cannot call TryAddAssociations with empty keys.");
            Fx.Assert(keysToAssociate != null, "Cannot call TryAddAssociations with null keysToAssociate.");
            // keysToDisassociate can be null if they should not be overridden by the new keys.

            List<PersistenceContext> contextsToAbort = null;
            try
            {
                lock (ThisLock)
                {
                    if (context.IsPermanentlyRemoved)
                    {
                        return false;
                    }
                    Fx.Assert(context.IsVisible, "Cannot call TryAddAssociations on an invisible context.");

                    // In the case when there is no store, if key collision is detected, the current instance will be aborted later.
                    // We should not add any of its keys to the keyMap.
                    if (this.store == null)
                    {
                        foreach (InstanceKey key in keys)
                        {
                            PersistenceContext conflictingContext;
                            if (!context.AssociatedKeys.Contains(key) && this.keyMap.TryGetValue(key.Value, out conflictingContext))
                            {
                                throw FxTrace.Exception.AsError(new InstanceKeyCollisionException(null, context.InstanceId, key, conflictingContext.InstanceId));
                            }
                        }
                    }

                    foreach (InstanceKey key in keys)
                    {
                        Fx.Assert(key.IsValid, "Cannot call TryAddAssociations with an invalid key.");

                        if (context.AssociatedKeys.Contains(key))
                        {
                            if (keysToDisassociate != null)
                            {
                                keysToDisassociate.Remove(key);
                            }
                        }
                        else
                        {
                            Fx.AssertAndThrow(this.instanceCache != null, "Since the context must be visible, it must still be in the cache.");

                            PersistenceContext contextToAbort;
                            if (this.keyMap.TryGetValue(key.Value, out contextToAbort))
                            {
                                Fx.Assert(this.store != null, "When there is no store, exception should have already been thrown before we get here.");
                                DetachContext(contextToAbort, ref contextsToAbort);
                            }
                            this.keyMap.Add(key.Value, context);
                            context.AssociatedKeys.Add(key);
                            keysToAssociate.Add(key);
                        }
                    }

                    return true;
                }
            }
            finally
            {
                AbortContexts(contextsToAbort);
            }
        }
 private bool Finish()
 {
     IAsyncResult result;
     if (this.pipeline != null)
     {
         this.pipeline.Publish();
     }
     this.context.Open(TimeSpan.Zero);
     using (base.PrepareTransactionalCall(this.transaction))
     {
         result = this.context.BeginEnlist(this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleContextEnlist), this);
     }
     return base.SyncContinue(result);
 }
 // For transactional uses, call this method on commit.
 internal void RemoveInstance(PersistenceContext context)
 {
     RemoveInstance(context, false);
 }
 private bool Load()
 {
     IAsyncResult result;
     if (this.ppd.store == null)
     {
         this.isInstanceInitialized = false;
         this.context = new PersistenceContext(this.ppd, (this.suggestedIdOrId == Guid.Empty) ? Guid.NewGuid() : this.suggestedIdOrId, this.key, this.associatedKeys);
         return this.Finish();
     }
     if (this.canCreateInstance && !this.lockInstance)
     {
         if (this.suggestedIdOrId == Guid.Empty)
         {
             this.suggestedIdOrId = Guid.NewGuid();
         }
         this.handle = this.ppd.store.CreateInstanceHandle(this.ppd.owner, this.suggestedIdOrId);
         this.isInstanceInitialized = false;
         return this.AfterLoad();
     }
     InstancePersistenceCommand command = this.ppd.CreateLoadCommandHelper(this.key, out this.handle, this.canCreateInstance, this.suggestedIdOrId, this.associatedKeys, this.loadAny);
     try
     {
         using (base.PrepareTransactionalCall(this.transaction))
         {
             result = this.ppd.store.BeginExecute(this.handle, command, this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(new AsyncResult.AsyncCompletion(PersistenceProviderDirectory.LoadOrCreateAsyncResult.HandleExecute)), this);
         }
     }
     catch (InstanceHandleConflictException)
     {
         result = null;
     }
     catch (InstanceLockLostException)
     {
         result = null;
     }
     if (result == null)
     {
         return this.ResolveHandleConflict();
     }
     return base.SyncContinue(result);
 }
 void DetachContext(PersistenceContext contextToAbort, ref List<PersistenceContext> contextsToAbort)
 {
     if (contextsToAbort == null)
     {
         contextsToAbort = new List<PersistenceContext>();
     }
     contextsToAbort.Add(contextToAbort);
     DetachContext(contextToAbort);
 }
 private bool ResolveHandleConflict()
 {
     this.result = this.loadAny ? null : this.ppd.LoadFromCache(this.key, this.suggestedIdOrId, this.canCreateInstance);
     if (this.result != null)
     {
         return true;
     }
     ActionItem.Schedule(handleLoadRetry, this);
     return false;
 }
            // Returns true if we found an entry in the cache, or an exception occurred. The exception is returned in the out parameter.
            bool LoadFromCache()
            {
                bool completeSelf = false;
                AsyncWaitHandle waitHandle = null;

                // We need this while loop because if we end up trying to wait for the waitHandle returned by LoadInProgressWaitHandle
                // and the call to WaitAsync returns true, then the event was signaled, but the callback was not called. So we need
                // to try the load again. But we want to avoid a potential stack overflow that might result if we just called
                // the callback routine and it called us again in a vicious cycle.
                while (true)
                {
                    // loadAny requires load from store.
                    this.result = this.loadAny ? null : this.ppd.LoadFromCache(this.key, this.suggestedIdOrId, this.canCreateInstance);

                    if (this.result != null)
                    {
                        // We found the key in the cache, so we can complete the LoadOrCreateAsyncResult.
                        completeSelf = true;
                        break;  // out of the while loop because we found the instance.
                    }
                    else if (this.ppd.store == null && !this.canCreateInstance)
                    {
                        // Fail early if the instance can't be created or loaded, no need to try to take the throttle.
                        if (this.key != null)
                        {
                            throw FxTrace.Exception.AsError(new InstanceKeyNotReadyException(null, this.key));
                        }
                        else
                        {
                            throw FxTrace.Exception.AsError(new InstanceNotReadyException(null, this.suggestedIdOrId));
                        }
                    }
                    else
                    {
                        // We didn't find it in the cache. We can't complete ourself.
                        completeSelf = false;
                        waitHandle = this.ppd.LoadInProgressWaitHandle(this.key);
                        if (waitHandle != null)   // There is another load in progress. Wait for it to complete. The waitHandle completion
                        // will do LoadFromCache again.
                        {
                            if (waitHandle.WaitAsync(handleWaitForInProgressLoad, this, this.timeoutHelper.RemainingTime()))
                            {
                                // The waitHandle is signaled. So a load must have completed between the time we called LoadInProgressWaitHandle
                                // and now. Loop back up to the top and check the cache again.
                                continue;
                            }
                        }
                        else  // there wasn't a load in progress, so we can move forward with the load.
                        {
                            IAsyncResult reserveThrottleResult = this.ppd.BeginReserveThrottle(this.timeoutHelper.RemainingTime(),
                                this.PrepareAsyncCompletion(handleReserveThrottle), this);
                            completeSelf = this.SyncContinue(reserveThrottleResult);
                        }
                    }
                    // If we get here, WaitAsync returned false, so the callback will get called later or there wasn't a load
                    // in progress, so we are moving forward to do the load. So break out of the while loop
                    break;
                }

                return completeSelf;
            }
 public void each_up()
 {
     Sut = new PersistenceContext<DummyBackingStore>(new Registry(new DummyBackingStore()));
 }
            bool Load()
            {
                SetStartTime();

                if (this.ppd.store == null)
                {
                    Fx.Assert(this.canCreateInstance, "This case was taken care of in the constructor.");
                    Fx.Assert(!this.lockInstance, "Should not be able to try to async lock the instance if there's no factory/store.");

                    this.isInstanceInitialized = false;
                    this.context = new PersistenceContext(this.ppd, this.suggestedIdOrId == Guid.Empty ? Guid.NewGuid() : this.suggestedIdOrId, this.key, this.associatedKeys);
                    return Finish();
                }

                if (this.canCreateInstance && !this.lockInstance)
                {
                    if (this.suggestedIdOrId == Guid.Empty)
                    {
                        this.suggestedIdOrId = Guid.NewGuid();
                    }
                    this.handle = this.ppd.store.CreateInstanceHandle(this.ppd.owner, this.suggestedIdOrId);
                    this.isInstanceInitialized = false;
                    return AfterLoad();
                }

                Fx.Assert(this.lockInstance, "To get here async, lockInstance must be true.");

                InstancePersistenceCommand loadCommand = this.ppd.CreateLoadCommandHelper(this.key, out this.handle, this.canCreateInstance, this.suggestedIdOrId, this.associatedKeys, this.loadAny);
                IAsyncResult executeResult;
                try
                {
                    using (PrepareTransactionalCall(this.transaction))
                    {
                        executeResult = this.ppd.store.BeginExecute(this.handle, loadCommand, this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(LoadOrCreateAsyncResult.HandleExecute), this);
                    }
                }
                catch (InstanceHandleConflictException)
                {
                    executeResult = null;
                }
                catch (InstanceLockLostException)
                {
                    executeResult = null;
                }

                if (executeResult == null)
                {
                    return ResolveHandleConflict();
                }
                else
                {
                    return SyncContinue(executeResult);
                }
            }
        /// <summary>
        /// Creates a new instance of CommercialCatalogue with the data in the given instance of AddCommercialCatalogueModelView.
        /// </summary>
        /// <param name="addCommercialCatalogueModelView">AddCommercialCatalogueModelView with the CommercialCatalogue's data.</param>
        /// <returns>An instance of CommercialCatalogue.</returns>
        /// <exception cref="System.ArgumentException">
        /// Thrown when no CustomizedProductCollection or CustomizedProduct could be found with the provided identifiers.
        /// </exception>
        public static CommercialCatalogue create(AddCommercialCatalogueModelView addCommercialCatalogueModelView)
        {
            string reference   = addCommercialCatalogueModelView.reference;
            string designation = addCommercialCatalogueModelView.designation;

            //check if catalogue collections were specified
            if (!addCommercialCatalogueModelView.catalogueCollections.Any())
            {
                return(new CommercialCatalogue(reference, designation));
            }
            else
            {
                //create repositories so that customized products and collections can be fetched
                CustomizedProductCollectionRepository customizedProductCollectionRepository = PersistenceContext
                                                                                              .repositories().createCustomizedProductCollectionRepository();

                CustomizedProductRepository customizedProductRepository = PersistenceContext.repositories()
                                                                          .createCustomizedProductRepository();

                List <CatalogueCollection> catalogueCollections = new List <CatalogueCollection>();

                foreach (AddCatalogueCollectionModelView addCatalogueCollectionModelView in addCommercialCatalogueModelView.catalogueCollections)
                {
                    CatalogueCollection catalogueCollection = CreateCatalogueCollectionService.create(addCatalogueCollectionModelView);

                    catalogueCollections.Add(catalogueCollection);
                }

                return(new CommercialCatalogue(reference, designation, catalogueCollections));
            }
        }
        public MergeExternalPractitionerResponse MergeExternalPractitioner(MergeExternalPractitionerRequest request)
        {
            Platform.CheckForNullReference(request, "request");
            Platform.CheckMemberIsSet(request.LeftPractitionerRef, "LeftPractitionerRef");
            Platform.CheckMemberIsSet(request.RightPractitionerRef, "RightPractitionerRef");

            var left  = PersistenceContext.Load <ExternalPractitioner>(request.LeftPractitionerRef, EntityLoadFlags.Proxy);
            var right = PersistenceContext.Load <ExternalPractitioner>(request.RightPractitionerRef, EntityLoadFlags.Proxy);

            // if we are only doing a cost estimate, exit here without modifying any data
            if (request.EstimateCostOnly)
            {
                var cost = EstimateAffectedRecords(right, left);
                return(new MergeExternalPractitionerResponse(cost));
            }

            // unpack the request, loading all required entities
            var nameAssembler = new PersonNameAssembler();
            var name          = new PersonName();

            nameAssembler.UpdatePersonName(request.Name, name);

            var defaultContactPoint = request.DefaultContactPointRef != null?
                                      PersistenceContext.Load <ExternalPractitionerContactPoint>(request.DefaultContactPointRef) : null;

            var deactivatedContactPoints = request.DeactivatedContactPointRefs == null ? new List <ExternalPractitionerContactPoint>() :
                                           CollectionUtils.Map(request.DeactivatedContactPointRefs,
                                                               (EntityRef cpRef) => PersistenceContext.Load <ExternalPractitionerContactPoint>(cpRef));

            var cpReplacements = CollectionUtils.Map(request.ContactPointReplacements ?? (new Dictionary <EntityRef, EntityRef>()),
                                                     kvp => new KeyValuePair <ExternalPractitionerContactPoint, ExternalPractitionerContactPoint>(
                                                         PersistenceContext.Load <ExternalPractitionerContactPoint>(kvp.Key, EntityLoadFlags.Proxy),
                                                         PersistenceContext.Load <ExternalPractitionerContactPoint>(kvp.Value, EntityLoadFlags.Proxy)));


            // merge the practitioners
            var result = ExternalPractitioner.MergePractitioners(left, right,
                                                                 name,
                                                                 request.LicenseNumber,
                                                                 request.BillingNumber,
                                                                 request.ExtendedProperties,
                                                                 defaultContactPoint,
                                                                 deactivatedContactPoints,
                                                                 cpReplacements
                                                                 );

            PersistenceContext.Lock(result, DirtyState.New);

            // if user has verify permission, verify the result
            if (Thread.CurrentPrincipal.IsInRole(AuthorityTokens.Admin.Data.ExternalPractitionerVerification))
            {
                result.MarkVerified();
            }

            // queue work items to migrate orders and visits
            foreach (var practitioner in new[] { right, left })
            {
                var queueItem = MergeWorkQueueItem.Create(practitioner.GetRef());
                PersistenceContext.Lock(queueItem, DirtyState.New);
            }

            PersistenceContext.SynchState();

            var assembler = new ExternalPractitionerAssembler();

            return(new MergeExternalPractitionerResponse(assembler.CreateExternalPractitionerSummary(result, this.PersistenceContext)));
        }
        //TODO: Elimianar esta Accion
        protected override void RunInContextEmptyResponse(UpdateAccountTreeListRequest request, PersistenceContext context)
        {
            foreach (Guid id in request.DeletedIds)
            {
                AccountTree entity = context.Session.Load <AccountTree>(id);
                entity.MarkAsDelete();
            }

            context.Session.Flush();

            //Modifico los elementos modificados
            foreach (UI.AccountTreeListItem ui in request.UpdatedItems)
            {
                AccountTree entity = context.Session.Load <AccountTree>(ui.Id);

                /*
                 * if (entity.Version != ui.Version)
                 *  throw new StaleObjectStateException("AccountTree", ui.Id);
                 */

                ui.CopyTo(entity);

                /*-*
                 * entity.Active = ui.Active;
                 * entity.Code = ui.Code;
                 * entity.Description = ui.Description;
                 * entity.Name = ui.Name;
                 */
            }

            context.Session.Flush();

            //Creo los nuevos elementos
            foreach (UI.AccountTreeListItem ui in request.CreatedItems)
            {
                AccountTree entity = new AccountTree(ui.Id);
                ui.CopyTo(entity);
                context.Session.Save(entity);

                /*-*
                 * AccountTree entity = new AccountTree()
                 * {
                 *  Active = ui.Active,
                 *  Code = ui.Code,
                 *  Description = ui.Description,
                 *  Name = ui.Name
                 * };
                 * context.Session.Save(entity, ui.Id);
                 */
            }
        }
Esempio n. 47
0
 public UnitOfWork(PersistenceContext context)
 {
     this.context = context;
 }
        /// <summary>
        /// Transforms a customized product collection dto into a collection of customized products via service
        /// </summary>
        /// <param name="customizedProductCollectionDTO">CustomizedProductCollectionDTO with the customized product collection dto being transformed</param>
        /// <returns>CustomizedProductCollection with the collection of customized products transformed from the dto</returns>
        public CustomizedProductCollection transform(CustomizedProductCollectionDTO customizedProductCollectionDTO)
        {
            string name = customizedProductCollectionDTO.name;

            if (customizedProductCollectionDTO.customizedProducts == null)
            {
                return(new CustomizedProductCollection(name));
            }
            List <CustomizedProduct> customizedProducts = new List <CustomizedProduct>(PersistenceContext.repositories().createCustomizedProductRepository().findCustomizedProductsByTheirPIDS(customizedProductCollectionDTO.customizedProducts));

            return(new CustomizedProductCollection(name, customizedProducts));
        }
        /// <summary>
        /// Updates the properties of a product
        /// </summary>
        /// <param name="updateProductPropertiesModelView">UpdateProductPropertiesModelView with the data regarding the product update</param>
        /// <returns>GetProductModelView with the updated product information</returns>
        public GetProductModelView updateProductProperties(UpdateProductPropertiesModelView updateProductPropertiesModelView)
        {
            ProductRepository productRepository   = PersistenceContext.repositories().createProductRepository();
            Product           productBeingUpdated = productRepository.find(updateProductPropertiesModelView.id);

            if (productBeingUpdated == null)
            {
                throw new ResourceNotFoundException(string.Format(ERROR_UNABLE_TO_FIND_PRODUCT_BY_ID, updateProductPropertiesModelView.id));
            }

            //FetchEnsurance.ensureProductFetchWasSuccessful(productBeingUpdated);
            bool perfomedAtLeastOneUpdate = false;

            if (updateProductPropertiesModelView.reference != null)
            {
                productBeingUpdated.changeProductReference(updateProductPropertiesModelView.reference);
                perfomedAtLeastOneUpdate = true;
            }

            if (updateProductPropertiesModelView.designation != null)
            {
                productBeingUpdated.changeProductDesignation(updateProductPropertiesModelView.designation);
                perfomedAtLeastOneUpdate = true;
            }

            if (updateProductPropertiesModelView.modelFilename != null)
            {
                productBeingUpdated.changeModelFilename(updateProductPropertiesModelView.modelFilename);
                perfomedAtLeastOneUpdate = true;
            }

            if (updateProductPropertiesModelView.categoryId.HasValue)
            {
                ProductCategory categoryToUpdate = PersistenceContext.repositories().createProductCategoryRepository().find(updateProductPropertiesModelView.categoryId.Value);

                if (categoryToUpdate == null)
                {
                    throw new ArgumentException(string.Format(ERROR_UNABLE_TO_FIND_CATEGORY_BY_ID, updateProductPropertiesModelView.categoryId.Value));
                }

                productBeingUpdated.changeProductCategory(categoryToUpdate);
                perfomedAtLeastOneUpdate = true;
            }


            //?Should an error be thrown if no update was performed or should it just carry on?
            //UpdateEnsurance.ensureAtLeastOneUpdateWasPerformed(perfomedAtLeastOneUpdate);
            if (!perfomedAtLeastOneUpdate)
            {
                throw new ArgumentException(ERROR_NO_UPDATE_PERFORMED);
            }

            productBeingUpdated = productRepository.update(productBeingUpdated);

            //the updated product will only be null, if the reference was changed to match a previosuly added product
            if (productBeingUpdated == null)
            {
                throw new ArgumentException(ERROR_UNABLE_TO_UPDATE_PRODUCT);
            }

            //UpdateEnsurance.ensureProductUpdateWasSuccessful(productBeingUpdated);
            return(ProductModelViewService.fromEntity(productBeingUpdated));
        }
Esempio n. 50
0
        //TODO: use ProductBuilder here

        /// <summary>
        /// Creates a new instance of Product and saves it to the Repository.
        /// </summary>
        /// <param name="addProductMV">AddProductModelView containing the new Product's information.</param>
        /// <returns>Created instance of Product.</returns>
        /// <exception cref="System.ArgumentException">Throw </exception>
        public static Product create(AddProductModelView addProductMV)
        {
            string reference         = addProductMV.reference;
            string designation       = addProductMV.designation;
            string modelFilename     = addProductMV.modelFilename;
            long   productCategoryId = addProductMV.categoryId;

            List <AddMeasurementModelView> measurementModelViews = addProductMV.measurements;

            //NOTE: these checks are made here in order to avoid making requests to repositories unnecessarily
            if (measurementModelViews == null || !measurementModelViews.Any())
            {
                throw new ArgumentException(ERROR_NO_MEASUREMENTS_DEFINED);
            }

            List <AddProductMaterialModelView> materialViews = addProductMV.materials;

            //NOTE: these checks are made here in order to avoid making requests to repositories unnecessarily
            if (materialViews == null || !materialViews.Any())
            {
                throw new ArgumentException(ERROR_NO_MATERIALS_DEFINED);
            }

            ProductCategoryRepository categoryRepository = PersistenceContext.repositories().createProductCategoryRepository();

            ProductCategory category = categoryRepository.find(productCategoryId);

            if (category == null)
            {
                throw new ArgumentException(ERROR_CATEGORY_NOT_FOUND);
            }

            if (!categoryRepository.isLeaf(category))
            {
                throw new ArgumentException(ERROR_CATEGORY_NOT_LEAF);
            }

            List <Material>    materials          = new List <Material>();
            MaterialRepository materialRepository = PersistenceContext.repositories().createMaterialRepository();

            foreach (AddProductMaterialModelView materialModelView in materialViews)
            {
                if (materialModelView == null)
                {
                    throw new ArgumentException(ERROR_NULL_MATERIAL);
                }

                long materialId = materialModelView.materialId;

                Material material = materialRepository.find(materialId);
                if (material == null)
                {
                    throw new ArgumentException(string.Format(ERROR_MATERIAL_NOT_FOUND, materialId));
                }
                materials.Add(material);
            }

            IEnumerable <Measurement> measurements = MeasurementModelViewService.fromModelViews(addProductMV.measurements);

            List <AddComponentModelView>  componentModelViews = addProductMV.components;
            AddProductSlotWidthsModelView slotWidthsModelView = addProductMV.slotWidths;

            bool hasComponents = componentModelViews != null && componentModelViews.Any();
            bool hasSlots      = slotWidthsModelView != null;

            Product product = null;

            if (hasSlots)
            {
                ProductSlotWidths slotWidths = ProductSlotWidthsModelViewService.fromModelView(slotWidthsModelView);
                if (hasComponents)
                {
                    product = new Product(reference, designation, modelFilename, category, materials, measurements, slotWidths);
                    return(addComplementaryProducts(product, componentModelViews));
                }
                else
                {
                    return(new Product(reference, designation, modelFilename, category, materials, measurements, slotWidths));
                }
            }
            else
            {
                if (hasComponents)
                {
                    product = new Product(reference, designation, modelFilename, category, materials, measurements);
                    return(addComplementaryProducts(product, componentModelViews));
                }
                else
                {
                    return(new Product(reference, designation, modelFilename, category, materials, measurements));
                }
            }
        }
Esempio n. 51
0
        private Order PlaceOrderHelper(OrderRequisition requisition)
        {
            // get appropriate A# for this order
            var accNum = GetAccessionNumberForOrder(requisition);

            var patient           = this.PersistenceContext.Load <Patient>(requisition.Patient.PatientRef, EntityLoadFlags.Proxy);
            var orderingFacility  = this.PersistenceContext.Load <Facility>(requisition.OrderingFacility.FacilityRef, EntityLoadFlags.Proxy);
            var visit             = FindOrCreateVisit(requisition, patient, orderingFacility, accNum);
            var orderingPhysician = this.PersistenceContext.Load <ExternalPractitioner>(requisition.OrderingPractitioner.PractitionerRef, EntityLoadFlags.Proxy);
            var diagnosticService = this.PersistenceContext.Load <DiagnosticService>(requisition.DiagnosticService.DiagnosticServiceRef);
            var priority          = EnumUtils.GetEnumValue <OrderPriority>(requisition.Priority);


            var resultRecipients = CollectionUtils.Map(
                requisition.ResultRecipients ?? new List <ResultRecipientDetail>(),
                (ResultRecipientDetail s) => new ResultRecipient(
                    this.PersistenceContext.Load <ExternalPractitionerContactPoint>(s.ContactPoint.ContactPointRef, EntityLoadFlags.Proxy),
                    EnumUtils.GetEnumValue <ResultCommunicationMode>(s.PreferredCommunicationMode)));

            // generate set of procedures
            // create a temp map from procedure back to its requisition, this will be needed later
            var orderAssembler        = new OrderEntryAssembler();
            var mapProcToReq          = new Dictionary <Procedure, ProcedureRequisition>();
            var procedureNumberBroker = PersistenceContext.GetBroker <IProcedureNumberBroker>();
            var dicomUidBroker        = PersistenceContext.GetBroker <IDicomUidBroker>();
            var procedures            = CollectionUtils.Map(
                requisition.Procedures ?? new List <ProcedureRequisition>(),
                delegate(ProcedureRequisition req)
            {
                var rpt = this.PersistenceContext.Load <ProcedureType>(req.ProcedureType.ProcedureTypeRef);
                var rp  = new Procedure(rpt, procedureNumberBroker.GetNext(), dicomUidBroker.GetNewUid());
                mapProcToReq.Add(rp, req);

                // important to set this flag prior to creating the procedure steps, because it may affect
                // which procedure steps are created
                rp.DowntimeRecoveryMode = requisition.IsDowntimeOrder;
                return(rp);
            });


            // generate a new order with the default set of procedures
            var order = Order.NewOrder(
                new OrderCreationArgs(
                    Platform.Time,
                    this.CurrentUserStaff,
                    null,
                    accNum,
                    patient,
                    visit,
                    diagnosticService,
                    requisition.ReasonForStudy,
                    priority,
                    orderingFacility,
                    requisition.SchedulingRequestTime,
                    orderingPhysician,
                    resultRecipients,
                    procedures),
                procedureNumberBroker,
                dicomUidBroker);

            // note: need to lock the new order now, prior to creating the procedure steps
            // otherwise may get exceptions saying the Procedure is a transient object
            this.PersistenceContext.Lock(order, DirtyState.New);

            // create procedure steps and update from requisition
            foreach (var procedure in order.Procedures)
            {
                procedure.CreateProcedureSteps();
                if (mapProcToReq.ContainsKey(procedure))
                {
                    orderAssembler.UpdateProcedureFromRequisition(procedure, mapProcToReq[procedure], this.CurrentUserStaff, this.PersistenceContext);
                }
            }

            // add order notes
            if (requisition.Notes != null)
            {
                var noteAssembler = new OrderNoteAssembler();
                noteAssembler.SynchronizeOrderNotes(order, requisition.Notes, this.CurrentUserStaff, this.PersistenceContext);
            }

            // add attachments
            if (requisition.Attachments != null)
            {
                var attachmentAssembler = new OrderAttachmentAssembler();
                attachmentAssembler.Synchronize(order.Attachments, requisition.Attachments, this.CurrentUserStaff, this.PersistenceContext);
            }

            if (requisition.ExtendedProperties != null)
            {
                ExtendedPropertyUtils.Update(order.ExtendedProperties, requisition.ExtendedProperties);
            }

            return(order);
        }
        WorkflowServiceInstance(Activity workflowDefinition, WorkflowIdentity definitionIdentity, Guid instanceId, WorkflowServiceHost serviceHost, PersistenceContext persistenceContext)
            : base(workflowDefinition, definitionIdentity)
        {
            this.serviceHost = serviceHost;
            this.instanceId = instanceId;
            this.persistTimeout = serviceHost.PersistTimeout;
            this.trackTimeout = serviceHost.TrackTimeout;
            this.bufferedReceiveManager = serviceHost.Extensions.Find<BufferedReceiveManager>();

            if (persistenceContext != null)
            {
                this.persistenceContext = persistenceContext;
                this.persistenceContext.Closed += this.OnPersistenceContextClosed;
            }

            this.thisLock = new object();
            this.pendingRequests = new List<WorkflowOperationContext>();
            this.executorLock = new WorkflowExecutionLock(this);
            this.activeOperationsLock = new object();
            this.acquireReferenceSemaphore = new ThreadNeutralSemaphore(1);
            this.acquireLockTimeout = TimeSpan.MaxValue;

            // Two initial references are held:
            // The first referenceCount is owned by UnloadInstancePolicy (ReleaseInstance)
            this.referenceCount = 1;
            // The second referenceCount is owned by the loader / creator of the instance.
            this.TryAddReference();
        }
        protected override ListInvoicesResponse RunInContext(ListInvoicesRequest request, PersistenceContext context)
        {
            //Esto obtiene todas las facturas con sus items y realiza la suma en .net,
            //después se podría optimizar trayendo la suma desde la db, pero
            //repetimos el código en .net y en las consultas

            var response = new ListInvoicesResponse();

            response.Items = new List <UI.InvoicesListItem>(context.Session
                                                            .GetNamedQuery("InvoicesList")
                                                            .ToDTOEnumerable <UI.InvoicesListItem>("CopyFromInvoice"));

            return(response);
        }
Esempio n. 54
0
 public static UserService UserService(PersistenceContext context = null, Repository<User> repository = null)
 {
     context = context ?? MockedContext().With(new List<User>());
     return new UserService(repository ?? new Repository<User>(context), new UserQueryService(context), new UnitOfWorkFactory(context));
 }
Esempio n. 55
0
		/// <summary>
		/// Constructs an NHibernate IQuery object from this object.
		/// </summary>
		/// <param name="ctx">The persistence context that wraps the NHibernate session</param>
		/// <returns>an IQuery object</returns>
		internal IQuery BuildHibernateQueryObject(PersistenceContext ctx)
		{
			var q = ctx.Session.CreateQuery(this.Hql);

			// add the parameters to the query
			var i = 0;
			foreach (var val in _where.Parameters)
			{
				q.SetParameter(i++, val);
			}

			// if limits were specified, pass them to nhibernate
			if (_page != null)
			{
				if (_page.FirstRow > -1)
					q.SetFirstResult(_page.FirstRow);
				if (_page.MaxRows > -1)
					q.SetMaxResults(_page.MaxRows);
			}

			// configure caching
			q.SetCacheable(_cacheable);
			if (!string.IsNullOrEmpty(_cacheRegion))
				q.SetCacheRegion(_cacheRegion);

			// apply lock hints
			foreach (var kvp in _lockHints)
			{
				q.SetLockMode(kvp.Key, kvp.Value);
			}

			return q;
		}
 public override IEnumerable <IStreamPersister> CreatePersisters(PersistenceContext context)
 {
     yield return(new ActionStreamPersister(_targetStream));
 }
        public static WorkflowServiceInstance InitializeInstance(PersistenceContext persistenceContext, Guid instanceId, Activity workflowDefinition, WorkflowIdentity definitionIdentity, IDictionary<XName, InstanceValue> loadedObject, WorkflowCreationContext creationContext,
            SynchronizationContext synchronizationContext, WorkflowServiceHost serviceHost, DynamicUpdateMap updateMap = null)
        {
            Fx.Assert(workflowDefinition != null, "workflowDefinition cannot be null.");
            Fx.Assert(serviceHost != null, "serviceHost cannot be null!");
            Fx.Assert(instanceId != Guid.Empty, "instanceId cannot be empty.");

            WorkflowServiceInstance workflowInstance = new WorkflowServiceInstance(workflowDefinition, definitionIdentity, instanceId, serviceHost, persistenceContext)
            {
                SynchronizationContext = synchronizationContext
            };

            // let us initalize the instance level extensions here
            workflowInstance.SetupExtensions(serviceHost.WorkflowExtensions);

            if (loadedObject != null)
            {
                InstanceValue stateValue;
                object deserializedRuntimeState;

                if (!loadedObject.TryGetValue(WorkflowNamespace.Workflow, out stateValue) || stateValue.Value == null)
                {
                    throw FxTrace.Exception.AsError(
                        new InstancePersistenceException(SR.WorkflowInstanceNotFoundInStore(instanceId)));
                }
                deserializedRuntimeState = stateValue.Value;

                if (loadedObject.TryGetValue(WorkflowServiceNamespace.CreationContext, out stateValue))
                {
                    workflowInstance.creationContext = (WorkflowCreationContext)stateValue.Value;
                }

                if (persistenceContext.IsSuspended)
                {
                    workflowInstance.state = State.Suspended;
                }
                try
                {
                    workflowInstance.Initialize(deserializedRuntimeState, updateMap);
                }
                catch (InstanceUpdateException)
                {
                    // Need to flush the tracking record for the update failure
                    workflowInstance.ScheduleAbortTracking(true);
                    throw;
                }

                if (updateMap != null)
                {
                    workflowInstance.HasBeenUpdated = true;
                }
            }
            else
            {
                IList<Handle> rootExecutionProperties = null;
                IDictionary<string, object> workflowArguments = null;
                // Provide default CorrelationScope if root activity is not CorrelationScope
                if (!(workflowDefinition is CorrelationScope))
                {
                    rootExecutionProperties = new List<Handle>(1)
                    {
                        new CorrelationHandle()
                    };
                }

                if (creationContext != null)
                {
                    workflowArguments = creationContext.RawWorkflowArguments;
                    workflowInstance.creationContext = creationContext;
                }
                workflowInstance.Initialize(workflowArguments, rootExecutionProperties);
            }

            return workflowInstance;
        }
        public WorkflowServiceInstance InitializeInstance(Guid instanceId, PersistenceContext context, WorkflowIdentity definitionIdentity, WorkflowIdentityKey updatedIdentity, IDictionary<XName, InstanceValue> instance, WorkflowCreationContext creationContext)
        {
            Activity workflowDefinition = null;
            DynamicUpdateMap updateMap = null;
            if (updatedIdentity != null && !object.Equals(updatedIdentity.Identity, definitionIdentity))
            {
                if (!this.workflowDefinitionProvider.TryGetDefinitionAndMap(definitionIdentity, updatedIdentity.Identity, out workflowDefinition, out updateMap))
                {
                    if (this.workflowDefinitionProvider.TryGetDefinition(updatedIdentity.Identity, out workflowDefinition))
                    {
                        throw FxTrace.Exception.AsError(new FaultException(
                            OperationExecutionFault.CreateUpdateFailedFault(SR.UpdateMapNotFound(definitionIdentity, updatedIdentity.Identity))));
                    }
                    else
                    {
                        throw FxTrace.Exception.AsError(new FaultException(
                            OperationExecutionFault.CreateUpdateFailedFault(SR.UpdateDefinitionNotFound(updatedIdentity.Identity))));
                    }
                }
            }
            else if (!this.workflowDefinitionProvider.TryGetDefinition(definitionIdentity, out workflowDefinition))
            {
                throw FxTrace.Exception.AsError(new VersionMismatchException(SR.WorkflowServiceDefinitionIdentityNotMatched(definitionIdentity), null, definitionIdentity));
            }

            WorkflowIdentity definitionToLoad = updatedIdentity == null ? definitionIdentity : updatedIdentity.Identity;
            return WorkflowServiceInstance.InitializeInstance(context, instanceId, workflowDefinition, definitionToLoad, instance, creationContext,
                WorkflowSynchronizationContext.Instance, this.serviceHost, updateMap);
        }
Esempio n. 59
0
 public void SetContext(IPersistenceContext context)
 {
     _context = (PersistenceContext)context;
 }
Esempio n. 60
0
        public void TestAddPin()
        {
            INoteAccessor      accessor     = this._provider.GetService <INoteAccessor>();
            IUserAccessor      userAccessor = this._provider.GetService <IUserAccessor>();
            PersistenceContext context      = this._provider.GetService <PersistenceContext>();
            IUnitOfWork        unit         = this._provider.GetService <IUnitOfWork>();

            Assert.Equal(3, context.Pins.Count());

            var zach = userAccessor.FindUser("zach");

            accessor.AddPin(new Contracts.DTO.Pin()
            {
                BelongsTo = zach.UserId,
                Latitude  = _lincoln.North,
                Longitude = _lincoln.East,
                Name      = "Lincoln NE"
            });
            unit.Commit();

            Assert.Equal(4, context.Pins.Count());

            var zachPins = accessor.FindPins(zach);

            Assert.Equal(2, zachPins.Count);

            Assert.Throws <ArgumentException>(() =>
            {
                accessor.AddPin(null);
            });

            Assert.Throws <ArgumentException>(() =>
            {
                accessor.AddPin(new Contracts.DTO.Pin()
                {
                    PinId     = "kauf",
                    BelongsTo = zach.UserId,
                    Latitude  = 0,
                    Longitude = 0,
                    Name      = "Bad pin - duplicate"
                });
            });

            Assert.Throws <ArgumentException>(() =>
            {
                accessor.AddPin(new Contracts.DTO.Pin()
                {
                    Latitude  = 0,
                    Longitude = 0,
                    Name      = "Bad pin - no owner"
                });
            });

            Assert.Throws <ArgumentException>(() =>
            {
                accessor.AddPin(new Contracts.DTO.Pin()
                {
                    BelongsTo = zach.UserId,
                    Name      = "Bad pin - no coordinates"
                });
            });
        }