Exemple #1
0
        public LockResponse Lock(LockRequest request)
        {
            LockResponse response = new LockResponse();

            response.Errors = new List <BusinessRule>();

            User user = _repository
                        .FindBy(request.UserId);

            if (user != null)
            {
                try
                {
                    user.Status = 0;
                    _repository.Save(user);
                    _uow.Commit();

                    response.Result = true;
                }
                catch (Exception ex)
                {
                    response.Errors.Add(new BusinessRule("Error", ex.Message));
                    response.Result = false;
                }
            }
            else
            {
                response.Result = false;
            }

            return(response);
        }
Exemple #2
0
        /// <summary>
        /// Checks the lock state and locks if required
        /// </summary>
        /// <param name="category">Category of the lock</param>
        /// <param name="id">Id of the resource</param>
        /// <param name="lockIfFree">true if the resource should be locked if its free</param>
        /// <returns>Lock Response</returns>
        private async Task <IActionResult> CheckLockInternal(string category, string id, bool lockIfFree)
        {
            GoNorthUser currentUser = await _userManager.GetUserAsync(User);

            LockResponse response = new LockResponse();

            response.LockedByOtherUser   = false;
            response.LockValidForMinutes = LockTimespan;

            LockEntry existingLock = await _lockServiceDbAccess.GetResourceLockEntry(category, id);

            if (existingLock != null)
            {
                if (existingLock.UserId != currentUser.Id && existingLock.ExpireDate > DateTimeOffset.UtcNow)
                {
                    GoNorthUser lockedByUser = await _userManager.FindByIdAsync(existingLock.UserId);

                    response.LockedByUserName  = lockedByUser.DisplayName;
                    response.LockedByOtherUser = true;
                    return(Ok(response));
                }
            }

            if (lockIfFree)
            {
                await _lockServiceDbAccess.LockResource(category, id, currentUser.Id, DateTimeOffset.UtcNow.AddMinutes(LockTimespan));
            }

            return(Ok(response));
        }
Exemple #3
0
        /// <summary>
        /// LockAsync acquires a distributed shared lock on a given named lock.
        /// On success, it will return a unique key that exists so long as the
        /// lock is held by the caller. This key can be used in conjunction with
        /// transactions to safely ensure updates to etcd only occur while holding
        /// lock ownership. The lock is held until Unlock is called on the key or the
        /// lease associate with the owner expires.
        /// </summary>
        /// <param name="request">The request to send to the server</param>
        /// <returns></returns>
        public async Task <LockResponse> LockAsync(LockRequest request, Metadata headers = null)
        {
            LockResponse response   = new LockResponse();
            bool         success    = false;
            int          retryCount = 0;

            while (!success)
            {
                try
                {
                    response = await _balancer.GetConnection().lockClient.LockAsync(request, headers);

                    success = true;
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable)
                {
                    retryCount++;
                    if (retryCount >= _balancer._numNodes)
                    {
                        throw ex;
                    }
                }
            }
            return(response);
        }
Exemple #4
0
        /// <summary>
        /// Checks the lock state and locks if required
        /// </summary>
        /// <param name="category">Category of the lock</param>
        /// <param name="id">Id of the resource</param>
        /// <param name="userIdentifier">User identifier to use for locking. If none is specified, no lock is acquired</param>
        /// <param name="lockIfFree">true if the resource should be locked if its free</param>
        /// <param name="appendProjectIdToKey">True if the project id must be appended to the key</param>
        /// <returns>Lock Response</returns>
        private async Task <IActionResult> CheckExternalLockInternal(string category, string id, string userIdentifier, bool lockIfFree, bool appendProjectIdToKey)
        {
            id = await AppendProjectIdIfRequired(id, appendProjectIdToKey);

            LockResponse response = new LockResponse();

            response.LockedByOtherUser   = false;
            response.LockValidForMinutes = LockTimespan;

            LockEntry existingLock = await _lockServiceDbAccess.GetResourceLockEntry(category, id);

            if (existingLock != null)
            {
                if ((existingLock.UserId != ExternalUserConstants.ExternalUserId || (existingLock.UserId == ExternalUserConstants.ExternalUserId && existingLock.ExternalUserId != userIdentifier)) &&
                    existingLock.ExpireDate > DateTimeOffset.UtcNow)
                {
                    response.LockedByUserName  = _localizer["ExternalUser"];
                    response.LockedByOtherUser = true;
                    return(Ok(response));
                }
            }

            if (lockIfFree)
            {
                await _lockServiceDbAccess.LockResource(category, id, ExternalUserConstants.ExternalUserId, userIdentifier, DateTimeOffset.UtcNow.AddMinutes(LockTimespan));
            }

            return(Ok(response));
        }
Exemple #5
0
        /// <summary>
        /// Lock acquires a distributed shared lock on a given named lock.
        /// On success, it will return a unique key that exists so long as the
        /// lock is held by the caller. This key can be used in conjunction with
        /// transactions to safely ensure updates to etcd only occur while holding
        /// lock ownership. The lock is held until Unlock is called on the key or the
        /// lease associate with the owner expires.
        /// </summary>
        /// <param name="request">The request to send to the server</param>
        /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
        /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
        /// <param name="cancellationToken">An optional token for canceling the call.</param>
        /// <returns>The response received from the server.</returns>
        public LockResponse Lock(LockRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null,
                                 CancellationToken cancellationToken             = default)
        {
            LockResponse response   = new LockResponse();
            bool         success    = false;
            int          retryCount = 0;

            while (!success)
            {
                try
                {
                    response = _balancer.GetConnection().lockClient.Lock(request, headers, deadline, cancellationToken);
                    success  = true;
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable)
                {
                    retryCount++;
                    if (retryCount >= _balancer._numNodes)
                    {
                        throw;
                    }
                }
            }

            return(response);
        }
Exemple #6
0
 public static Entity.LockResponse FromProto(this LockResponse response)
 {
     return(new Entity.LockResponse()
     {
         Header = response.Header.FromProto(),
         Key = response.Key.FromProto()
     });
 }
        /// <summary>
        /// Sets the sites.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public LockResponse SetLock(LockRequest request)
        {
            var response = new LockResponse();

            if (request.LoadOptions.Contains("ExcuteLock"))
            {
                response.Message = LockDao.ExcuteUnLock(request.Lock);
            }

            return(response);
        }
Exemple #8
0
        public LockResponse Lock(ByteSequence name, long leaseId)
        {
            V3Lockpb.LockRequest request = new V3Lockpb.LockRequest();
            request.Name  = name.GetByteString();
            request.Lease = leaseId;
            var          rsp      = lockClient.Lock(request);
            LockResponse response = new LockResponse(rsp);

            return(response);
            //   return Util.ToCompletableFutureWithRetry(
            //    stub.Lock(request),
            //    new FunctionResponse<V3Lockpb.LockRequest, LockResponse>(),
            //    Util.IsRetriable

            //);
        }
Exemple #9
0
        public bool LockData(DatabaseConstant.Module module,
                             DatabaseConstant.Function function,
                             DatabaseConstant.Table table,
                             DatabaseConstant.Action action,
                             List <int> listLockId)
        {
            // Truongnx: test performance
            //return true;

            // Kiểm tra kết nối, server, service trước khi request
            Common.Utilities.IsRequestAllow(ApplicationConstant.SystemService.UtilitiesService.layGiaTri());

            //Khởi tạo và gán các giá trị cho request
            LockRequest  request  = Common.Utilities.PrepareRequest(new LockRequest());
            LockResponse response = new LockResponse();

            request.Module     = module;
            request.Function   = function;
            request.Table      = table;
            request.Action     = action;
            request.ListLockId = listLockId.ToArray();

            // Lấy kết quả trả về
            response = Client.LockData(request);

            // Kiểm tra kết quả trả về
            Common.Utilities.ValidResponse(request, response);

            //return response.ListLockedId.ToList();
            if (response.ResponseStatus == ApplicationConstant.ResponseStatus.THANH_CONG)
            {
                return(true);
            }
            else
            {
                if (ClientInformation.ClientType.Equals(ApplicationConstant.ClientType.DESKTOP.layGiaTri()))
                {
                    LMessage.ShowMessage("M.ResponseMessage.Common.LockDataInvalid", LMessage.MessageBoxType.Information);
                }
                return(false);
            }
        }
Exemple #10
0
        public LockResponse GetLock(LockRequest request)
        {
            var response = new LockResponse();

            if (request.LoadOptions.Contains("Get"))
            {
                response.Lock = LockDao.GetLock();
            }
            if (request.LoadOptions.Contains("CheckPostedDate"))
            {
                response.Lock = LockDao.CheckLock(request.RefId, request.RefTypeId, request.RefDate);
            }

            if (request.LoadOptions.Contains("CheckRefID"))
            {
                response.Lock = LockDao.CheckLock(request.RefId, request.RefTypeId);
            }

            return(response);
        }
Exemple #11
0
        /// <summary>
        /// Get all locked OrderItems for Current Member
        /// </summary>
        /// <returns>JSON result</returns>
        public ActionResult GetLocksForCurrentMember()
        {
            // Response JSON
            var json = new LockResponse();

            try
            {
                // Get current member
                int memberId = _memberInfoManager.GetCurrentMemberId(Request, Response);

                var items = _orderItemManager.GetLockedOrderItems(memberId.ToString());

                // Set response metadata.
                json.MemberId   = memberId;
                json.MemberName = _memberInfoManager.GetCurrentMemberText(Request, Response);
                json.List       = new List <Lock>();

                foreach (var item in items)
                {
                    var lockItem = new Lock();
                    lockItem.NodeId = item.NodeId;
                    // Missing data for the Lock model, but this data is currently not used.
                    json.List.Add(lockItem);
                }

                json.Message = String.Format("Found {0} locked OrderItems for Current Member.", json.List.Count);

                // Return JSON to client.
                json.Success = true;
            }
            catch (Exception e)
            {
                // Return JSON to client.
                json.Success = false;
                json.Message = "Error reading locked OrderItems: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
        //Locks the given Resource and returns the LockToken
        //if the locking was successfull
        //If not null will be returned
        public string LockResource(WebDavClient client, string destUri, LockScope lockScope)
        {
            _logger.Debug("Locking remote element " + destUri);
            LockResponse lockResponse = client.Lock(destUri, new LockParameters()
            {
                LockScope = lockScope,
                Owner     = _owner,
            }).Result;

            if (lockResponse.IsSuccessful)
            {
                _logger.Debug("Successfully locked");
                ActiveLock ActiveLock = lockResponse.ActiveLocks.Where(x => x.Owner.Value.Equals(_owner.Value)).FirstOrDefault();
                return(ActiveLock.LockToken);
            }
            else
            {
                _logger.Error("Locking ressource failed! description: " + lockResponse.Description);
            }

            return(null);
        }
Exemple #13
0
        public JsonResult LockUser(string userID)
        {
            LockResponse response = _userService.LockUser(userID);

            return(Json(new { ErrorCode = response.ErrorCode, Message = response.Message, Locked = response.Locked }, JsonRequestBehavior.AllowGet));
        }