Esempio n. 1
0
 private static List<Locker> GetLockers()
 {
     var lockers = new List<Locker>();
     for (int i = 1; i <= 100; i++)
     {
         var locker = new Locker(i);
         lockers.Add((locker));
     }
     return lockers;
 }
Esempio n. 2
0
 private void AddList(Locker l)
 {
     foreach (Locker lo in LockList)
     {
         if (lo.Is(l))
         {
             lo.LockObj = l.LockObj;
             return;
         }
     }
     LockList.Add(l);
 }
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             Locker.Dispose();
             Context.Dispose();
         }
     }
     _disposed = true;
 }
Esempio n. 4
0
        /// <summary>
        /// 退款结果
        /// </summary>
        /// <param name="localRefundNo">本地退款单号</param>
        /// <param name="refundStatus">退款状态</param>
        /// <param name="realRefundAmount">实际退款金额</param>
        /// <param name="successTime">成功退款时间</param>
        /// <param name="failReason">退款失败的原因</param>
        /// <param name="originData">http原始数据</param>
        /// <returns></returns>
        public async Task DoRefundResult(string refundNo, string localRefundNo, RefundStatus refundStatus,
                                         int realRefundAmount,
                                         long?successTime, string failReason, string originData)
        {
            if (refundStatus == RefundStatus.RefundProcessing)
            {
                return;
            }

            var refund = await DbContext.Set <RefundOrders>().Include(r => r.PrepayOrder)
                         .FirstOrDefaultAsync(r => r.LocalRefundNo == localRefundNo);

            if (refund == null)
            {
                throw new Exception($"退款订单不存在,localRefundNo: {localRefundNo}");
            }

            if (refund.RefundStatus != RefundStatus.RefundProcessing)
            {
                throw new Exception($"退款异常,状态错误,localRefundNo: {localRefundNo},数据库状态: {refund.RefundStatus}");
            }

            refund.RefundStatus     = refundStatus;
            refund.SuccessTime      = successTime;
            refund.RealRefundAmount = realRefundAmount;
            refund.FailReason       = failReason;
            refund.OriginalData     = originData;
            refund.RefundNo         = refundNo;

            using var locker = Locker.Lock(Lockers.RefundOrderCreate.Format(refund.Id), 3);
            using var tran   = DbContext.Database.BeginTransaction();
            try
            {
                await DbContext.SaveChangesAsync();

                await EventPublisher.PublishAsync(new RefundOrderResultEvent
                {
                    FailReason       = failReason,
                    RealRefundAmount = realRefundAmount,
                    SourceType       = refund.PrepayOrder.SourceType,
                    SourceSn         = refund.PrepayOrder.SourceSn,
                    Status           = refundStatus,
                    SuccessTime      = successTime
                });

                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                throw ex;
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 转帐
        /// </summary>
        /// <param name="sourceAccountId"></param>
        /// <param name="targetAccountId"></param>
        /// <param name="value"></param>
        /// <param name="memo"></param>
        /// <returns></returns>
        public DataDefinition.TradeState Transfer(Guid sourceAccountId, Guid targetAccountId, int value, string memo)
        {
            if (value <= 0)
            {
                throw new ArgumentOutOfRangeException("value");
            }
            if (sourceAccountId == targetAccountId)
            {
                throw new ArgumentException("sourceAccountId = targetAccountId");
            }

            var walletRepository  = Factory.CreateWalletRepository();
            var billingRepository = Factory.CreateBillingRepository();

            using (Locker.Lock(sourceAccountId, targetAccountId))
            {
                var source = LoadWallet(walletRepository, sourceAccountId);
                var target = LoadWallet(walletRepository, targetAccountId);

                if (!source.Enough(value))
                {
                    return(DataDefinition.TradeState.InsufficientBalance);
                }
                else if (source.IsLocked())
                {
                    return(DataDefinition.TradeState.Locked);
                }

                source.StartTrade();
                target.StartTrade();
                walletRepository.Replace(source);
                walletRepository.Replace(target);
                Factory.GetUnitOfWork().Commit();

                var sourceBillingId = Generator.Next();
                var targetBillingId = Generator.Next();

                Domain.Billing sourceBilling;
                Domain.Billing targetBilling;
                Domain.Billing.CreateTransfer(value, memo, source, target, sourceBillingId, targetBillingId, out sourceBilling, out targetBilling);
                billingRepository.Add(sourceBilling);
                billingRepository.Add(targetBilling);
                Factory.GetUnitOfWork().Commit();

                source.FinishTrade(sourceBilling);
                target.FinishTrade(targetBilling);
                walletRepository.Replace(source);
                walletRepository.Replace(target);

                Factory.GetUnitOfWork().Commit();
                return(DataDefinition.TradeState.Success);
            }
        }
        public ActionResult Create(Locker locker)
        {
            if (ModelState.IsValid)
            {
                locker.LockerID = Guid.NewGuid();
                LockerDB.Add(locker);
                LockerDB.Commit();
                return(RedirectToAction("Index"));
            }

            return(View(locker));
        }
        public void should_return_bag_when_pick_if_bag_is_stored_into_locker()
        {
            var locker  = new Locker(1);
            var manager = new Manager(locker);

            var storedBag = new Bag();
            var ticket    = manager.Store(storedBag);

            var pickedBag = manager.Pick(ticket);

            Assert.AreEqual(pickedBag, storedBag);
        }
        public void should_get_a_valid_ticket_when_give_bag_to_strategy_robot()
        {
            Bag           bag    = new Bag();
            Locker        locker = new Locker(1);
            StrategyRobot robot  = new StrategyRobot(new List <Locker> {
                locker
            });
            var ticket = robot.Receive(bag);
            Bag bag2   = locker.Pick(ticket);

            Assert.Same(bag, bag2);
        }
 public static bool ValidateViewHistory()
 {
     if (!Container.GetLockSettings().IsEnabled)
     {
         return(false);
     }
     if (Selection.activeObject == null)
     {
         return(false);
     }
     return(Locker.IsAssetTypeValid(Selection.activeObject));
 }
 public static void EndLock(int id)
 {
     lock (DictionaryLocker)
     {
         Locker locker = Locks[id];
         --locker._num;
         if (locker._num == 0)
         {
             Locks.Remove(id);
         }
     }
 }
Esempio n. 11
0
 public void SetTop(DeletedBlockInfo value)
 {
     Locker.Lock();
     if (!MoveFirst())
     {
         Locker.Unlock();
         return;
     }
     Remove();
     Add(value);
     Locker.Unlock();
 }
        public static IFluentApi <Locker> StubbedApi(Locker stubbedLockerToReturn)
        {
            var fluentApi = MockRepository.GenerateStub <IFluentApi <Locker> >();

            fluentApi.Stub(x => x.ForUser("", "")).IgnoreArguments().Return(fluentApi);
            fluentApi.Stub(x => x.WithParameter("", "")).IgnoreArguments().Return(fluentApi);
            fluentApi.Stub(x => x.WithPageNumber(0)).IgnoreArguments().Return(fluentApi);
            fluentApi.Stub(x => x.WithPageSize(0)).IgnoreArguments().Return(fluentApi);
            fluentApi.Stub(x => x.Sort(LockerSortColumn.PurchaseDate, SortOrder.Descending)).IgnoreArguments().Return(fluentApi);
            fluentApi.Stub(x => x.Please()).Return(stubbedLockerToReturn);
            return(fluentApi);
        }
Esempio n. 13
0
 static public Locker GetLocker(object obj)
 {
     lock (Object2Locker)
     {
         Locker lockr;
         if (!Object2Locker.TryGetValue(obj, out lockr))
         {
             lockr = Object2Locker[obj] = new Locker(obj);
         }
         return(lockr);
     }
 }
Esempio n. 14
0
        public ActionResult Create(Locker item)
        {
            if (ModelState.IsValid)
            {
                item.LockerID = Guid.NewGuid();
                ItemDB.Add(item);
                ItemDB.Commit();
                return(RedirectToAction("Index"));
            }

            return(View(item));
        }
Esempio n. 15
0
 /// <summary>
 /// Read config
 /// </summary>
 /// <returns>Task with config string</returns>
 public async Task <string> ReadConfigAsync()
 {
     if (UseFile)
     {
         return(await Locker.LockFunctionAsync(async() => await File.ReadAllTextAsync(Path)));
     }
     else if (string.IsNullOrWhiteSpace(GlobalConfigString))
     {
         throw new IOException("If not using file, globalConfigString must be populated before reading");
     }
     return(GlobalConfigString);
 }
Esempio n. 16
0
        public void TestIsFresh()
        {
            var jsonContent = GetJsonContent();
            var locker      = new Locker(io, jsonFile.Object, installationManager.Object, jsonContent);

            jsonFile.Setup((o) => o.Read <ConfigLocker>()).Returns(new ConfigLocker()
            {
                ContentHash = Security.Md5(jsonContent),
            });

            Assert.IsTrue(locker.IsFresh());
        }
Esempio n. 17
0
        public void TestIsLocked()
        {
            var locker = new Locker(io, jsonFile.Object, installationManager.Object, GetJsonContent());

            jsonFile.Setup((o) => o.Exists()).Returns(true);
            jsonFile.Setup((o) => o.Read <ConfigLocker>()).Returns(new ConfigLocker
            {
                Packages = Array.Empty <ConfigLockerPackage>(),
            });

            Assert.IsTrue(locker.IsLocked());
        }
Esempio n. 18
0
        public void Add(TKey key, TValue value, bool save = false, bool update = true)
        {
            lock (Locker.Get("Data"))
            {
                Data.Add(key, value, update);
            }

            if (save)
            {
                this.PaceMaker();
            }
        }
Esempio n. 19
0
        public void BeginSetLockDataWithMinimal()
        {
            var jsonContent = GetJsonContent();
            var locker      = new Locker(io, jsonFile.Object, installationManager.Object, jsonContent);

            var packageFooMock = new Mock <IPackage>();
            var packageBarMock = new Mock <IPackage>();

            packageFooMock.Setup((o) => o.GetNamePretty()).Returns("foo");
            packageFooMock.Setup((o) => o.GetVersionPretty()).Returns("1.0.0-beta");
            packageFooMock.Setup((o) => o.GetVersion()).Returns("1.0.0.0-beta");

            packageBarMock.Setup((o) => o.GetNamePretty()).Returns("bar");
            packageBarMock.Setup((o) => o.GetVersionPretty()).Returns("0.2.0");
            packageBarMock.Setup((o) => o.GetVersion()).Returns("0.2.0.0");

            var contentHash = Security.Md5(jsonContent.Trim());

            jsonFile.Setup((o) => o.Write(It.IsAny <object>())).Callback <object>((data) =>
            {
                data = JObject.FromObject(data);
                StringAssert.Contains(data.ToString(), contentHash);
                var expected =
                    @"{
  '_readme': 'This file is generated automatically',
  'content-hash': '59eedf9c4842dd75d51e100343398439',
  'packages': [
    {
      'name': 'bar',
      'version': '0.2.0'
    },
    {
      'name': 'foo',
      'version': '1.0.0-beta'
    }
  ],
  'packages-dev': [],
  'aliases': [],
  'minimum-stability': 'stable',
  'stability-flags': {},
  'prefer-stable': true,
  'prefer-lowest': false,
  'platform': {}
}";
                Assert.AreEqual(expected.Replace("'", "\"", StringComparison.Ordinal), data.ToString());
            });

            var ret = locker.BeginSetLockData(new[] { packageFooMock.Object, packageBarMock.Object })
                      .Save();

            Assert.AreEqual(true, ret);
            jsonFile.Verify((o) => o.Write(It.IsAny <object>()), Times.Once);
        }
Esempio n. 20
0
        public void should_store_bag_in_locker_which_has_more_capacity()
        {
            var locker1 = new Locker(1);
            var locker2 = new Locker(2);

            smartRobot = new SmartRobot(new List <Locker>()
            {
                locker1, locker2
            });
            smartRobot.Store(new Bag());
            Assert.Equal(1, locker2.AvailableCount);
        }
Esempio n. 21
0
 private Locker GetSelectedLocker()
 {
     if (lockersGrid.SelectedRows.Count == 1)
     {
         Locker locker = lockersGrid.SelectedRows[0].DataBoundItem as Locker;
         return(locker);
     }
     else
     {
         return(null);
     }
 }
Esempio n. 22
0
        public CheckReport Check(List <CheckRequest> requests, Guid processId)
        {
            var ids    = requests.Select(r => r.Id).ToList();
            var rests  = GetRests(ids);
            var result = CheckResult.Success;

            try
            {
                foreach (var checkRequest in requests)
                {
                    if (!Locker.TryLock(checkRequest.Id, processId))
                    {
                        result = CheckResult.LimitBlocked;
                        break;
                    }
                    var period =
                        Periods.FirstOrDefault(
                            p => p.Alias.Equals(checkRequest.PeriodAlias, StringComparison.InvariantCultureIgnoreCase));


                    var rest =
                        rests.FirstOrDefault(
                            r =>
                            period != null &&
                            ((r as DynamicEntity).GetProperty(AccountObject.RestEntitySearchProperty)
                             .Equals(checkRequest.Id) &&
                             (r as DynamicEntity).GetProperty(AccountObject.RestEntityPeriodProperty)
                             .Equals(period.Id)));

                    if (rest == null)
                    {
                        result = CheckResult.RestNotFound;
                        break;
                    }

                    result = Check(rest, checkRequest);

                    if (result != CheckResult.Success)
                    {
                        break;
                    }
                }
            }
            finally
            {
                ids.ForEach(id => Locker.Unlock(id, processId));
            }

            return(new CheckReport()
            {
                Result = result
            });
        }
Esempio n. 23
0
        public ActionResult CreateLocker(Locker locker)
        {
            int id = 0;

            if (ModelState.IsValid)
            {
                db.Lockers.Add(locker);
                db.SaveChanges();
                id = locker.ID;
            }
            return(Json(id, JsonRequestBehavior.AllowGet));
        }
Esempio n. 24
0
        // Constructor for View Rental
        public SelectLockerForm(int rentalId)
        {
            InitializeComponent();

            // Get all data related to the rental
            _rental     = Rental.Get(rentalId);
            _locker     = Locker.Get(_rental.LockerId);
            _cabinet    = Cabinet.Get(_locker.CabinetId);
            _lockerType = LockerType.Get(_cabinet.LockerTypeId);

            // Set the start date and end date of rental
            _startDate = _rental.StartDate;
            _endDate   = _rental.EndDate;

            // Clear combo box  & locker type dictonary to avoid error
            _lockerTypeDictonary.Clear();

            // Only add the involved locker type into the directonary
            _lockerTypeDictonary.Add(_lockerType.Id, _lockerType.Name);

            // Bind locker type dictonary onto combo box locker type locker cabinet (In Locker Module)
            comboBoxLockerTypeLockerCabinet.DataSource = new BindingSource(_lockerTypeDictonary, null);

            // Display the Locker Type Name and Set the Locker Type Id as ValueMember
            comboBoxLockerTypeLockerCabinet.DisplayMember = "Value";
            comboBoxLockerTypeLockerCabinet.ValueMember   = "Key";

            // Trigger SelectedIndexChanged event
            comboBoxLockerTypeLockerCabinet.SelectedIndex = -1;

            // Select the invloved locker type
            comboBoxLockerTypeLockerCabinet.SelectedIndex = 0;

            // Disable the comboBox
            comboBoxLockerTypeLockerCabinet.Enabled = false;

            // Load all cabinet list
            _lockerCabinetPage.PageNumber = 1;
            LockerCabinetPage();

            //Default select the involved cabinet to load
            textBoxCabinetCode.Text = _cabinet.Code;

            // Get the available lockers for the selected cabinet
            CabinetLockerController cabinetLockerController = new CabinetLockerController();
            List <Locker>           availableLockers        = cabinetLockerController.GetAvailableLockers(_cabinet.Id, _startDate, _endDate);

            textBoxEmptyLockerNo.Text = availableLockers.Count.ToString();

            _lockerPage.PageNumber = 1;
            LockerPage(availableLockers);
        }
Esempio n. 25
0
        public static int DisplayKeys(DisplayArguments arguments)
        {
            int    result = 0;
            Locker locker = GetLocker(arguments);

            System.Console.WriteLine("List of Keys and values");
            System.Console.WriteLine("----------------------------------------");
            foreach (var pair in locker.Keys)
            {
                System.Console.WriteLine($"{pair.Key}     {pair.Value}");
            }
            return(result);
        }
 private bool TryPick(Locker locker, Ticket ticket, out Bag bag)
 {
     try
     {
         bag = locker.Pick(ticket);
         return(true);
     }
     catch (InvalidOperationException)
     {
         bag = null;
         return(false);
     }
 }
Esempio n. 27
0
        public void Add(TValue value, bool save = false)
        {
            lock (Locker.Get("Data"))
            {
                Data.Add(value);
                this.UpdateTime = DateTime.Now;
            }

            if (save)
            {
                this.PaceMaker();
            }
        }
Esempio n. 28
0
        internal Database(DatabaseSystem system, string name, IConfiguration configuration)
            : base(system, KnownScopes.Database)
        {
            System        = system;
            Name          = name;
            Configuration = configuration;

            Locker = new Locker(this);

            Scope.AsContainer().RegisterInstance <IDatabase>(this);

            transactions = new OpenTransactionCollection();
        }
        public bool Contains(long studentId, long courseId) => Locker.RunReadAction(() =>
        {
            Logger.LogQueryStarted();
            if (!Accepted.ContainsKey(studentId))
            {
                Logger.LogQueryFinished();
                return(false);
            }

            bool result = Accepted[studentId]?.Contains(courseId) ?? false;
            Logger.LogQueryFinished();
            return(result);
        });
Esempio n. 30
0
        private Locker <List <LockerKey> > CreateAndSaveLockerWithOneKey(string lockerPath, string password, byte[] salt, string key, string value)
        {
            AESEncryptor encryptor = new AESEncryptor(salt, 1234);
            GenericBinarySerializer <List <LockerKey> > serializer = new GenericBinarySerializer <List <LockerKey> >();

            var keyLocker = new Locker <List <LockerKey> >(encryptor, serializer, password);

            keyLocker.Keys.Add(new LockerKey {
                Key = key, Value = value
            });
            keyLocker.Save(lockerPath);
            return(keyLocker);
        }
Esempio n. 31
0
        public void should_return_the_bag_stored_in_smartrobot_by_the_ticket()
        {
            var lockers = new List <Locker>();
            var locker  = new Locker(1);

            lockers.Add(locker);

            var robot  = Robot.CreateSmartRobot(lockers);
            var bag    = new Bag();
            var ticket = robot.Store(bag);

            Assert.AreSame(robot.Pick(ticket), bag);
        }
 public void LockObject(string objectId, string objectFullType)
 {
     objectId = objectId.ToLowerInvariant();
     if (objectId.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
     {
         throw new ArgumentException("objectId has invalid filename characters and would not be saveable");
     }
     if (Path.HasExtension(objectId))
     {
         var extension = Path.GetExtension(objectId);
         if (extension.Equals(FileExtension, StringComparison.OrdinalIgnoreCase)
             || extension.Equals(FileExtensionNew, StringComparison.OrdinalIgnoreCase)
             || extension.Equals(FileExtensionOld, StringComparison.OrdinalIgnoreCase))
             throw new ArgumentException("objectId cannot have a name that ends with .pdata, .new or .old");
     }
     if (objectId.Length > 200)
     {
         throw new ArgumentException("objectId cannot have more than 200 characters");
     }
     Locker locker;
     if (lockBox.TryGetValue(objectId, out locker))
     {
         if (locker.Locked)
         {
             throw new InvalidOperationException(
                 "This objectId is already locked by another Persistent, " 
                 + "dispose old instance before creating new one");
         }
         if (!string.IsNullOrEmpty(locker.FullType) && locker.FullType != objectFullType)
         {
             throw new InvalidOperationException(
                 "This objectId was used with different runtime type during this session, " +
                 "this may indicate a bug");
         }
         locker = locker.Lock();
     }
     else
     {
         locker = new Locker()
         {
             FullType = objectFullType,
             Locked = true
         };
     }
     lockBox[objectId] = locker;
 }
Esempio n. 33
0
        public void should_pick_bag_given_existing_ticket()
        {
            var locker = new Locker(1);
            var lockers = new List<Locker> { locker };
            var smartRobot = new SmartRobot(new List<Locker> {new Locker(1)});
            var superRobot = new SuperRobot(new List<Locker> {new Locker(1)});

            var robots = new List<SmartRobot> {
                smartRobot,
                superRobot
            };
            var manager = new Manager(lockers, robots);
            var expectedBag = new Bag();
            var ticket = manager.Store(expectedBag);
            var actualBag = manager.Pick(ticket);

            Assert.Equal(expectedBag, actualBag);
        }
Esempio n. 34
0
        public void should_store_bag_in_sequence_given_all_kinds_of_robots_and_lockers()
        {
            var locker = new Locker(1);
            var lockers = new List<Locker> { locker };
            var smartRobot = new SmartRobot(new List<Locker> {new Locker(1)});
            var superRobot = new SuperRobot(new List<Locker> {new Locker(1)});

            var robots = new List<SmartRobot> {
                smartRobot,
                superRobot
            };

            var manager = new Manager(lockers, robots);
            var bag1 = new Bag();
            var bag2 = new Bag();
            var bag3 = new Bag();
            var ticket1 = manager.Store(bag1);
            var ticket2 = manager.Store(bag2);
            var ticket3 = manager.Store(bag3);

            Assert.Equal(bag1, locker.Pick(ticket1));
            Assert.Equal(bag2, smartRobot.Pick(ticket2));
            Assert.Equal(bag3, superRobot.Pick(ticket3));
        }
Esempio n. 35
0
		/// <summary>
		/// Lock the log.
		/// </summary>
		/// <returns>A disposable that will unlock a block.</returns>
		public IDisposable Lock()
		{
			if (_locker == null || _locker.Disposed)
				_locker = new Locker();
			return _locker;
		}
		public Log4NetFileRepositoryMock(ILogManager logManager, Locker locker):base(logManager, locker)
		{
			_removedFiles = new List<string>();
			_removedFolders = new List<string>();
		}
		public ActivityLoggerFactory(ILoggerFactory factory, Locker locker)
		{
			_factory = factory;
			_locker = locker;
			_path = ObjectFactory.GetInstance<IActivityLogPathProvider>();
		}
		public PluginRollingFileAppender(PluginRollingFileAppender baseAppender, IActivityLogPathProvider path, Locker locker,
		                                 string accountName, string profileName) : this()
		{
			_locker = locker;
			_accountName = accountName;
			_profileName = profileName;
			Initialize(baseAppender, path);
		}
 public AnonymousClassLock1(string name, int time, Locker enclosingInstance)
     : base(name, time)
 {
     this.enclosingInstance = enclosingInstance;
 }
Esempio n. 40
0
        public static Locker lockString(string str)
        {
            lock (locker)
            {
                Locker returnvalue = new Locker("");
                Boolean pathAlreadyLocked = false;
                ArrayList stringToDelete = new ArrayList();
                foreach (Locker path in lockersList)
                {
                    if (String.Equals(path.lockStr, str))
                    {
                        if (pathAlreadyLocked)
                        {
                            stringToDelete.Add(path);
                        }
                        else
                        {
                            pathAlreadyLocked = true;
                            returnvalue = path;
                        }
                    }
                }
                foreach (Locker item in stringToDelete)
                {
                    lockersList.Remove(item);
                }
                if (!pathAlreadyLocked)
                {
                    returnvalue = new Locker(str);
                    lockersList.Add(returnvalue);
                }

                return returnvalue;
            }
        }