Exemplo n.º 1
0
        internal override async Task DoCommandAsync()
        {
            _code = HttpStatusCodes.SuccessOk;
            var buffer = new byte[ProgramCostants.DefautBufferSize];
            var offset = 0;

            try {
                int count;
                while (0 < (count = await _inputStream.ReadAsync(buffer, offset, buffer.Length - offset)))
                {
                    offset += count;
                }
            } catch (HttpListenerException e) {
                Console.WriteLine(e.Message);
            }
            _content = Encoding.UTF8.GetString(buffer, 0, offset);
            Logger.Trace(_content);
            _inputStream.Close();
            if (!_content.Any())
            {
                return;
            }
            LockHelper.ParseLockContent(_content, this);
            LockManager.GetInstanse()
            .LockFile(_mFileName, new LockInfo(_mFileName, _mLockType, _mLockScope, _mDepth, _mOwner, _mFileName));
        }
Exemplo n.º 2
0
        public Boolean TryAcquireLock()
        {
            if (!LockHelper.LockExists(Path))
            {
                return(AcquireLock());
            }

            FileLockContent content = LockHelper.ReadLock(Path);

            //Someone else owns the lock
            if (content.GetType() == typeof(OtherProcessOwnsFileLockContent))
            {
                return(false);
            }

            //the file no longer exists
            if (content.GetType() == typeof(MissingFileLockContent))
            {
                return(AcquireLock());
            }

            DateTime writeTime = new DateTime(content.Timestamp);

            //This lock belongs to this process - we can reacquire the lock
            if (content.PID == Process.GetCurrentProcess().Id)
            {
                return(AcquireLock());
            }

            //The lock has not timed out - we can't acquire it
            return(Math.Abs((DateTime.Now - writeTime).TotalSeconds) > Timeout.TotalSeconds && AcquireLock());
        }
Exemplo n.º 3
0
        //[Test]
        //public void TestSampleMessages()
        //{
        //   string folder = @"C:\Temp\hMailServer IssueTracker ID 342 Example EML Files";

        //   var files = Directory.GetFiles(folder, "*.eml");

        //   foreach (var file in files)
        //   {
        //      string content = File.ReadAllText(file);

        //      TestMessage(content);

        //      SetUp();
        //      TestSetup();
        //   }
        //}

        private void TestMessage(string messageContent)
        {
            FetchAccount fetchAccount;

            using (var pop3Server = CreateServer(messageContent))
            {
                pop3Server.SendBufferMode = POP3Server.BufferMode.SingleBuffer;
                pop3Server.StartListen();

                fetchAccount = CreateFetchAccount();

                // Fetch message
                fetchAccount.DownloadNow();
                pop3Server.WaitForCompletion();
                LockHelper.WaitForUnlock(fetchAccount);
            }

            // Do it again
            using (var pop3Server = CreateServer(messageContent))
            {
                pop3Server.SendBufferMode = POP3Server.BufferMode.MessageAndTerminatonTogether;
                pop3Server.StartListen();

                fetchAccount.DownloadNow();
                pop3Server.WaitForCompletion();
                LockHelper.WaitForUnlock(fetchAccount);

                POP3ClientSimulator.AssertMessageCount(_account.Address, "test", 2);
                string downloadedMessage = POP3ClientSimulator.AssertGetFirstMessageText(_account.Address, "test");
                CustomAssert.IsTrue(downloadedMessage.Contains(messageContent));
            }
        }
Exemplo n.º 4
0
        private bool CheckNotPastLockedDateTime(out TimeSpan waitFor, DateTime timeToCheck)
        {
            // If lockedDateTime doesn't have a value, storedLockedDateTime is null
            // If lockedDateTime has a value, but it is before the timeToCheck, set it to null, and set storedLockedDateTime to null
            // Otherwise, set storedLockedDateTime to the value of lockedDateTime
            var storedLockedDateTime = LockHelper.LockedCreateOrUpdate(
                ref _disabledUntilLock,
                ref _disabledUntil,
                (currentValue) => currentValue.HasValue && timeToCheck > currentValue,
                (currentValue) =>
            {
                return(null);
            }
                );

            // If storedLockedDateTime is not null, we return false (the time to check is before the lockedDateTime) and we out the remaining time difference.
            if (storedLockedDateTime.HasValue)
            {
                waitFor = storedLockedDateTime.Value - timeToCheck;
                return(false);
            }

            // Otherwise, we return false, and out 0 (as we've already passed the time stored in lockedDateTime)
            waitFor = TimeSpan.Zero;
            return(true);
        }
Exemplo n.º 5
0
        public void TestDisconnectAfterRetrCommand()
        {
            var pop3Server = CreateServer();

            pop3Server.SecondsToWaitBeforeTerminate  = 180;
            pop3Server.DisconnectAfterRetrCompletion = true;
            pop3Server.StartListen();

            // Connection will be dropped after we perform the RETR command.
            var fetchAccount = CreateFetchAccount();

            fetchAccount.DownloadNow();

            pop3Server.WaitForCompletion();
            LockHelper.WaitForUnlock(fetchAccount);

            // Simulate another download where the connection is not dropPed.
            pop3Server = CreateServer();
            pop3Server.SecondsToWaitBeforeTerminate  = 180;
            pop3Server.DisconnectAfterRetrCompletion = false;
            pop3Server.StartListen();

            fetchAccount.DownloadNow();
            pop3Server.WaitForCompletion();

            POP3ClientSimulator.AssertMessageCount(_account.Address, "test", 2);
        }
Exemplo n.º 6
0
        public void TestMessageAndTerminationInSameBuffer()
        {
            FetchAccount fetchAccount;

            using (var pop3Server = CreateServer())
            {
                pop3Server.SendBufferMode = Pop3ServerSimulator.BufferMode.MessageAndTerminatonTogether;
                pop3Server.StartListen();

                fetchAccount = CreateFetchAccount();

                // Fetch message
                fetchAccount.DownloadNow();
                pop3Server.WaitForCompletion();
                LockHelper.WaitForUnlock(fetchAccount);
            }


            // Do it again, to make sure
            using (var pop3Server = CreateServer())
            {
                pop3Server.SendBufferMode = Pop3ServerSimulator.BufferMode.MessageAndTerminatonTogether;
                pop3Server.StartListen();

                fetchAccount.DownloadNow();
                pop3Server.WaitForCompletion();
                LockHelper.WaitForUnlock(fetchAccount);
            }

            Pop3ClientSimulator.AssertMessageCount(_account.Address, "test", 2);
            string downloadedMessage = Pop3ClientSimulator.AssertGetFirstMessageText(_account.Address, "test");

            Assert.IsTrue(downloadedMessage.Contains(_message));
        }
Exemplo n.º 7
0
        public Boolean ReleaseLock()
        {
            //Need to own the lock in order to release it (and we can reacquire the lock inside the current process)
            if (LockHelper.LockExists(Path) && TryAcquireLock())
            {
                LockHelper.DeleteLock(Path);
            }

            return(true);
        }
Exemplo n.º 8
0
        public FileLock(String name, TimeSpan timeout)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name), @"Name cannot be null or empty.");
            }

            Name    = name;
            Path    = LockHelper.GetFilePath(name);
            Timeout = timeout;
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            Trace.TraceInformation("启动任务");

            AMSTask.StartAllTasks(cancellationTokenSource.Token);

            while (cancellationTokenSource.IsCancellationRequested == false)
            {
                Console.WriteLine("Please input command...");
                string cmd = Console.ReadLine();

                switch (cmd.ToLower())
                {
                case "exit":
                    cancellationTokenSource.Cancel();
                    break;

                case "clearevents":
                    DataHelper.ClearAllEvents();
                    Console.WriteLine("All events cleared");
                    break;

                case "addevent":
                    DataHelper.AddEvent(DataHelper.TestChannelName);
                    break;

                case "addtwochannelsevent":
                    DataHelper.AddEvent(DataHelper.TestChannelName, DataHelper.TestChannel2Name);
                    break;

                case "addmooncakeevent":
                    DataHelper.AddEvent(DataHelper.MooncakeTestChannelName);
                    break;

                case "clearqueue":
                    DataHelper.ClearQueue();
                    Console.WriteLine("Queue cleared");
                    break;

                case "clearlocks":
                    LockHelper.ClearAll();
                    Console.WriteLine("Lock cleared");
                    break;

                case "endevents":
                    Console.WriteLine("{0} events updated.", DataHelper.EndAllRunningEvents());
                    break;

                default:
                    Console.WriteLine("{0}是不能识别的命令", cmd);
                    break;
                }
            }
        }
Exemplo n.º 10
0
 public void UpdateMake(Guid makeId, string makeName)
 {
     makeName = makeName.Trim();
     LockHelper.LockAction(
         _makeLock,
         () => DataProvider.Makes.Any(x => x.Key == makeId),
         () =>
     {
         DataProvider.Makes[makeId].Name = makeName;
     },
         () => throw new ResourceNotFoundException(nameof(makeId), makeId.ToString()));
 }
Exemplo n.º 11
0
 /// <summary>
 /// 添加词汇进入消息队列
 /// </summary>
 /// <param name="keyword"></param>
 private static void AddQueue(string keyword)
 {
     if (keywordQueue.Contains(keyword))
     {
         return;
     }
     lock (LockHelper.GetLoker(Const.LANGUAGE))
     {
         Console.WriteLine("加入词汇:{0}", keyword);
         keywordQueue.Push(keyword);
     }
 }
Exemplo n.º 12
0
 /// <summary>
 /// See ISettableCircuitProvider
 /// </summary>
 public void SetOpenUntil(DateTime newTime)
 {
     // If lockedDateTime does not have a value OR it does have a value but that value is less than
     // the newTime passed in, set lockedDateTime to the value passed in.
     // Otherwise, leave lockedDateTime with the current value
     LockHelper.LockedCreateOrUpdate(
         ref _disabledUntilLock,
         ref _disabledUntil,
         (currentValue) => !currentValue.HasValue || (currentValue.HasValue && newTime > currentValue),
         (currentValue) => newTime
         );
 }
Exemplo n.º 13
0
 public void UpdateModel(Guid modelId, string modelName)
 {
     modelName = modelName.Trim();
     LockHelper.LockAction(
         _modelLock,
         () => DataProvider.Models.Any(x => x.Key == modelId),
         () =>
     {
         DataProvider.Models[modelId].Name = modelName;
     },
         () => throw new ResourceNotFoundException(nameof(modelId), modelId.ToString()));
 }
Exemplo n.º 14
0
        private async void SetLockScreen()
        {
            bool success = await LockHelper.SetLock(ImageUri.AbsolutePath, false);

            if (!success)
            {
                MessageBox.Show(AppResources.UserOptionNo);
            }
            else
            {
                MessageBox.Show(AppResources.UserOptionYes);
            }
        }
Exemplo n.º 15
0
 public void Execute(IJobExecutionContext context)
 {
     JobHelper.Invoke(context, () =>
     {
         using (var lockHelper = new LockHelper(LockObj))
         {
             if (lockHelper.IsTimeout)
             {
                 return;
             }
             var result = QueryException();
         }
     });
 }
Exemplo n.º 16
0
 public MakeOutputModel AddMake(string makeName)
 {
     makeName = makeName.Trim();
     return(LockHelper.LockAction <MakeOutputModel>(
                _makeLock,
                // De-duplicate the model with the same makeName...
                () => !DataProvider.Makes.Any(x => string.Equals(x.Value.Name, makeName, StringComparison.InvariantCultureIgnoreCase)),
                () =>
     {
         var newMake = new MakeInputModel(makeName);
         DataProvider.Makes.TryAdd(newMake.Id, newMake);
         return _mapper.Map <MakeOutputModel>(newMake);
     },
                () => throw new ResourceConflictException(nameof(MakeInputModel.Name), makeName)));
 }
Exemplo n.º 17
0
 public DealerModel Add(string dealerName)
 {
     dealerName = dealerName.Trim();
     return(LockHelper.LockAction <DealerModel>(
                _lock,
                () => !DataProvider.Dealers.Any(x => x.Value.Name == dealerName),
                () =>
     {
         var dealer = new DealerModel(dealerName);
         DataProvider.Dealers.TryAdd(dealer.Id, dealer);
         return dealer;
     },
                () => throw new ResourceConflictException(nameof(dealerName), dealerName)
                ));
 }
        public static DiskGroupLockResult ExtendPartition(Partition volume, long numberOfAdditionalExtentSectors)
        {
            if (volume.Disk is PhysicalDisk)
            {
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    bool isReadOnly;
                    bool isOnline = ((PhysicalDisk)volume.Disk).GetOnlineStatus(out isReadOnly);
                    if (!isOnline || isReadOnly)
                    {
                        return(DiskGroupLockResult.OneOrMoreDisksAreOfflineOrReadonly);
                    }
                }

                LockStatus status = LockHelper.LockBasicDiskAndVolumesOrNone(((PhysicalDisk)volume.Disk));
                if (status == LockStatus.CannotLockDisk)
                {
                    return(DiskGroupLockResult.CannotLockDisk);
                }
                else if (status == LockStatus.CannotLockVolume)
                {
                    return(DiskGroupLockResult.CannotLockVolume);
                }

                if (Environment.OSVersion.Version.Major >= 6)
                {
                    bool success = ((PhysicalDisk)volume.Disk).SetOnlineStatus(false);
                    if (!success)
                    {
                        return(DiskGroupLockResult.CannotTakeDiskOffline);
                    }
                }
            }

            ExtendHelper.ExtendPartition(volume, numberOfAdditionalExtentSectors);

            if (volume.Disk is PhysicalDisk)
            {
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    bool success = ((PhysicalDisk)volume.Disk).SetOnlineStatus(true);
                }
                LockHelper.UnlockBasicDiskAndVolumes((PhysicalDisk)volume.Disk);
                ((PhysicalDisk)volume.Disk).UpdateProperties();
            }

            return(DiskGroupLockResult.Success);
        }
Exemplo n.º 19
0
 void InitDependenciesAfterLibraries()
 {
     CachedImageRenderer.Init();
     FormsVideoPlayer.Init(@"1EAE2298627D7932F01F1B2E700FE4631897463C");
     BadgeColorTabbedNavigationContainerRenderer.InitRender();
     ColorTabbedNavigationContainerRenderer.InitRender();
     AdvancedTimerImplementation.Init();
     Messier16Controls.InitAll();
     AnimationViewRenderer.Init();
     CarouselViewRenderer.Init();
     new AdvancedFrameRendereriOS();
     new SfRatingRenderer();
     new SfImageEditorRenderer();
     SfImageEditorRenderer.Init();
     var t = typeof(RangeSliderRenderer);
     var l = new LockHelper();
 }
Exemplo n.º 20
0
 /// <summary>
 /// 获取缓存值(如果不存在则创建)
 /// </summary>
 /// <typeparam name="TValue"></typeparam>
 /// <param name="key"></param>
 /// <param name="timeSpan">过期时间</param>
 /// <param name="createValue"></param>
 /// <param name="isSleep">重新创建缓存之后是否暂停进程</param>
 /// <returns></returns>
 public static TValue Get <TValue>(string key, TimeSpan timeSpan, Func <TValue> createValue)
 {
     if (_cache.TryGetValue(key, out TValue result))
     {
         return(result);
     }
     lock (LockHelper.GetLoker(key))
     {
         if (_cache.TryGetValue(key, out result))
         {
             return(result);
         }
         result = createValue();
         _cache.Set(key, result, timeSpan);
         return(result);
     }
 }
Exemplo n.º 21
0
        public static LockStatus LockDynamicDiskGroup(List <DynamicDisk> disksToLock, bool lockAllDynamicVolumes)
        {
            List <DynamicVolume> volumesToLock = new List <DynamicVolume>();

            if (lockAllDynamicVolumes)
            {
                volumesToLock = WindowsDynamicVolumeHelper.GetLockableDynamicVolumes(disksToLock);
            }

            LockStatus status = LockHelper.LockAllOrNone(disksToLock, volumesToLock);

            if (status == LockStatus.Success)
            {
                m_lockedDisks.AddRange(disksToLock);
                m_lockedVolumes.AddRange(volumesToLock);
            }
            return(status);
        }
Exemplo n.º 22
0
 void InitDependenciesAfterLibraries()
 {
     CachedImageRenderer.Init();
     CachedImage.FixedAndroidMotionEventHandler = true;
     CachedImage.FixedOnMeasureBehavior         = true;
     CarouselViewRenderer.Init();
     FormsVideoPlayer.Init(@"966AC4DFAAB5D7CEAC7250857C34B76223973994");
     BadgeColorTabbedNavigationContainerRenderer.Init();
     BadgeTabbedNavigationContainerRenderer.Init();
     AdvancedTimerImplementation.Init();
     Messier16Controls.InitAll();
     UserDialogs.Init(this);
     new AdvancedFrameRendererDroid();
     new SfRatingRenderer();
     new SfImageEditorRenderer();
     var t = typeof(RangeSliderRenderer);
     var l = new LockHelper();
 }
Exemplo n.º 23
0
        /// <summary>
        /// 查询转账信息
        /// </summary>
        /// <param name="site">商户</param>
        /// <param name="game">游戏配置</param>
        /// <param name="orderId">商户的转账订单号</param>
        /// <returns></returns>
        public QueryTransferResult QueryTransfer(Site site, GameSetting game, string orderId)
        {
            // 加锁,不允许对同一个订单号进行并发查询
            lock (LockHelper.GetLoker($"{game.ID}-{orderId}"))
            {
                UserTransfer order = TransferAgent.Instance().GetUserTransfer(site.ID, game.ID, orderId);
                if (order == null)
                {
                    return(new QueryTransferResult(ResultStatus.NoOrder));
                }
                if (order.Status == TransferStatus.Paying)
                {
                    return(new QueryTransferResult(ResultStatus.OrderPaying));
                }

                if (order.Status == TransferStatus.Exception)
                {
                    UserGame user = UserAgent.Instance().GetUserGameInfo(order.UserID, game.ID);
                    // 调用API接口
                    ResultStatus status = game.Setting.QueryTransfer(new QueryTransferInfo()
                    {
                        UserName = user.Account,
                        OrderID  = orderId,
                        Currency = site.Currency
                    });
                    if (status == ResultStatus.Exception)
                    {
                        return(new QueryTransferResult(ResultStatus.Exception));
                    }

                    order.Status = status == ResultStatus.Success ? TransferStatus.Success : TransferStatus.Faild;
                    this.WriteDB.Update(order, t => t.Status);
                }

                if (order.Status == TransferStatus.Success)
                {
                    return(new QueryTransferResult(order.Money, order.CreateAt, UserAgent.Instance().GetUserName(order.UserID), order.Action, site.Currency));
                }

                return(new QueryTransferResult(ResultStatus.OrderFaild));
            }
        }
        private static ExtendFileSystemResult ExtendUnmountedFileSystem(Partition volume, long numberOfAdditionalSectors)
        {
            IExtendableFileSystem fileSystem = FileSystemHelper.ReadFileSystem(volume) as IExtendableFileSystem;

            // Windows Vista / 7 enforce various limitations on direct write operations to volumes and disks.
            // Basic disks are not needed to be taken offline for direct write operations within volume region. Only dynamic disks have to.
            if (volume.Disk is PhysicalDisk && Environment.OSVersion.Version.Major >= 6)
            {
                bool isReadOnly;
                bool isOnline = ((PhysicalDisk)volume.Disk).GetOnlineStatus(out isReadOnly);
                if (!isOnline || isReadOnly)
                {
                    return(ExtendFileSystemResult.OneOrMoreDisksAreOfflineOrReadonly);
                }

                LockStatus status = LockHelper.LockBasicDiskAndVolumesOrNone(((PhysicalDisk)volume.Disk));
                if (status == LockStatus.CannotLockDisk)
                {
                    return(ExtendFileSystemResult.CannotLockDisk);
                }
                else if (status == LockStatus.CannotLockVolume)
                {
                    return(ExtendFileSystemResult.CannotLockVolume);
                }

                bool success = ((PhysicalDisk)volume.Disk).SetOnlineStatus(false);
                if (!success)
                {
                    return(ExtendFileSystemResult.CannotTakeDiskOffline);
                }
            }

            fileSystem.Extend(numberOfAdditionalSectors);

            if (volume.Disk is PhysicalDisk && (Environment.OSVersion.Version.Major >= 6))
            {
                bool success = ((PhysicalDisk)volume.Disk).SetOnlineStatus(true);
                LockHelper.UnlockBasicDiskAndVolumes((PhysicalDisk)volume.Disk);
            }

            return(ExtendFileSystemResult.Success);
        }
Exemplo n.º 25
0
 /// <summary>
 /// 获取实体类下所有的数据库字段
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 internal static List <ColumnProperty> GetColumns(Type type)
 {
     if (columnCache.ContainsKey(type))
     {
         return(columnCache[type]);
     }
     lock (LockHelper.GetLoker(type.Name))
     {
         List <ColumnProperty> columns = new List <ColumnProperty>();
         foreach (PropertyInfo property in type.GetProperties().Where(t => t.HasAttribute <ColumnAttribute>()))
         {
             columns.Add(new ColumnProperty(property));
         }
         if (!columnCache.ContainsKey(type))
         {
             columnCache.Add(type, columns);
         }
     }
     return(columnCache[type]);
 }
Exemplo n.º 26
0
        public ModelOutputModel AddModel(Guid makeId, string modelName)
        {
            modelName = modelName.Trim();
            // The make with the id should exist in the make list
            if (!DataProvider.Makes.Any(x => x.Key == makeId))
            {
                throw new ResourceNotFoundException(nameof(makeId), makeId.ToString());
            }

            return(LockHelper.LockAction <ModelOutputModel>(
                       _modelLock,
                       // De-duplicate the model with the same name & makeId...
                       () => !DataProvider.Models.Any(x => x.Value.MakeId == makeId &&
                                                      String.Equals(x.Value.Name, modelName, StringComparison.InvariantCultureIgnoreCase)),
                       () =>
            {
                var model = new ModelInputModel(makeId, modelName);
                DataProvider.Models.TryAdd(model.Id, model);
                return _mapper.Map <ModelOutputModel>(model);
            },
                       () => throw new ResourceConflictException(nameof(modelName), modelName)));
        }
        public static void ReleaseDisk(Disk disk)
        {
            if (disk is DiskImage)
            {
                ((DiskImage)disk).ReleaseLock();
            }
            else if (disk is RAMDisk)
            {
                ((RAMDisk)disk).Free();
            }
#if Win32
            else if (disk is PhysicalDisk)
            {
                if (!DiskAccessLibrary.LogicalDiskManager.DynamicDisk.IsDynamicDisk(disk))
                {
                    LockHelper.UnlockBasicDiskAndVolumes((PhysicalDisk)disk);
                    try
                    {
                        ((PhysicalDisk)disk).UpdateProperties();
                    }
                    catch (System.IO.IOException)
                    {
                    }
                }
            }
            else if (disk is VolumeDisk)
            {
                bool skippedLock = (Environment.OSVersion.Version.Major >= 6 && VolumeInfo.IsOffline(((VolumeDisk)disk).Volume));
                if (!skippedLock)
                {
                    Guid?windowsVolumeGuid = WindowsVolumeHelper.GetWindowsVolumeGuid(((VolumeDisk)disk).Volume);
                    if (windowsVolumeGuid.HasValue)
                    {
                        WindowsVolumeManager.ReleaseLock(windowsVolumeGuid.Value);
                    }
                }
            }
#endif
        }
Exemplo n.º 28
0
        /// <summary>
        /// 数字档案文件分片全部上传好后保存
        /// </summary>
        /// <param name="sourceFilePath">源文件路径</param>
        /// <returns></returns>
        public FileUploadInfo SaveFileOrdinaryChunk(string sourceFilePath)
        {
            try
            {
                var result = new FileUploadInfo();

                LockHelper.Open(sourceFilePath);
                var docService      = new DocService();
                var newFileNamePath = GetDocFileName(docService, sourceFilePath);

                if (newFileNamePath == "FileExists")
                {  // 文件存在,则直接返回
                    LockHelper.Dispose(sourceFilePath);
                    return(result);
                }

                string rentdoctbDetailId = Request["rentdoctbDetailId"];

                // 如果已经有详情了,则直接保存到数据库。
                if (!string.IsNullOrEmpty(rentdoctbDetailId))
                {
                    result = docService.SaveDocFile(sourceFilePath, newFileNamePath, rentdoctbDetailId);
                }
                else
                {
                    //新增的部分,存为临时文件,以.kyee 做为临时文件
                    FileInfo file = new FileInfo(sourceFilePath);
                    file.MoveTo(newFileNamePath);
                }
                LockHelper.Dispose(sourceFilePath);
                return(result);
            }
            catch (Exception ex)
            {
                LockHelper.Dispose(sourceFilePath);
                throw ex;
            }
        }
Exemplo n.º 29
0
        public WopiJsonResponse Handle()
        {
            var requestData = WopiRequest.ParseRequest(_request);

            var responseData = new PutRelativeResponse();

            var documentId      = Convert.ToInt64(requestData.Id);
            var relativeTarget  = _request.Headers[WopiHeaders.RelativeTarget];
            var suggestedTarget = _request.Headers[WopiHeaders.SuggestedTarget];

            // make sure we don't have both headers present:
            if (!string.IsNullOrEmpty(relativeTarget) && !string.IsNullOrEmpty(suggestedTarget))
            {
                return(new WopiJsonResponse()
                {
                    StatusCode = 501,
                    Json = new PutRelativeResponse()
                });
            }

            var    overwriteRelative = _request.Headers[WopiHeaders.OverwriteRelativeTarget];
            string extension;

            if (!string.IsNullOrEmpty(relativeTarget))
            {
                // check if we have a file matching the target name
                // and if so, return 409 conflict w/ lock response
                extension         = relativeTarget.Substring(relativeTarget.LastIndexOf(".") + 1);
                responseData.Name = IOHelper.Utf7Encode(relativeTarget); // extension should already be here, we just need to get it for below

                var overwriteExisting = !string.IsNullOrEmpty(overwriteRelative) && overwriteRelative.ToLower().Equals("true");
                var relativeDocument  = FB.GetDocumentByNameAndExtension(responseData.Name, extension, documentId);

                // does this document already exist?
                if (relativeDocument != null)
                {
                    // lock check - make sure the existing document isn't locked:
                    var currentLock = "";
                    if (LockHelper.IsLockMismatch(_request, relativeDocument, out currentLock))
                    {
                        return(new WopiJsonResponse()
                        {
                            StatusCode = 409, Json = responseData
                        });
                    }

                    // not locked - but the document exists, so make sure the overwrite existing header is set:
                    if (!overwriteExisting)
                    {
                        return(new WopiJsonResponse()
                        {
                            StatusCode = 409,
                            Json = responseData
                        });
                    }
                }
            }
            else
            {
                // suggested mode:
                // save the file with whatever name we want, and return that name:
                extension         = suggestedTarget.Substring(suggestedTarget.LastIndexOf(".") + 1);
                responseData.Name = "wopitest_putrelative." + extension;
            }

            var binary        = IOHelper.StreamToBytes(_request.InputStream);
            var newDocumentId = FB.SaveNewDocument(binary, extension, responseData.Name, documentId);
            var newToken      = FB.GetAccessToken(newDocumentId);

            responseData.Url = $"{Constants.WopiApiUrl}wopi/files/{newDocumentId}?access_token={newToken}";

            return(new WopiJsonResponse()
            {
                StatusCode = 200,
                Json = responseData
            });
        }
Exemplo n.º 30
0
        public void BuildProfile(WorldObject wo, Player examiner, bool success = true)
        {
            //Console.WriteLine("Appraise: " + wo.Guid);
            Success = success;

            // get wielder, if applicable
            var wielder = GetWielder(wo, examiner);

            BuildProperties(wo, wielder);
            BuildSpells(wo);

            // Help us make sure the item identify properly
            NPCLooksLikeObject = wo.GetProperty(PropertyBool.NpcLooksLikeObject) ?? false;

            if (PropertiesIID.ContainsKey(PropertyInstanceId.AllowedWielder))
            {
                if (!PropertiesBool.ContainsKey(PropertyBool.AppraisalHasAllowedWielder))
                {
                    PropertiesBool.Add(PropertyBool.AppraisalHasAllowedWielder, true);
                }
            }

            if (PropertiesIID.ContainsKey(PropertyInstanceId.AllowedActivator))
            {
                if (!PropertiesBool.ContainsKey(PropertyBool.AppraisalHasAllowedActivator))
                {
                    PropertiesBool.Add(PropertyBool.AppraisalHasAllowedActivator, true);
                }
            }

            // armor / clothing / shield
            if (wo is Clothing || wo.IsShield)
            {
                BuildArmor(wo);
            }

            if (wo is Creature creature)
            {
                BuildCreature(creature);
            }

            if (wo is MeleeWeapon || wo is Missile || wo is MissileLauncher || wo is Ammunition || wo is Caster)
            {
                BuildWeapon(wo, wielder);
            }

            if (wo is Door || wo is Chest)
            {
                // If wo is not locked, do not send ResistLockpick value. If ResistLockpick is sent for unlocked objects, id panel shows bonus to Lockpick skill
                if (!wo.IsLocked && PropertiesInt.ContainsKey(PropertyInt.ResistLockpick))
                {
                    PropertiesInt.Remove(PropertyInt.ResistLockpick);
                }

                // If wo is locked, append skill check percent, as int, to properties for id panel display on chances of success
                if (wo.IsLocked)
                {
                    var resistLockpick = LockHelper.GetResistLockpick(wo);

                    if (resistLockpick != null)
                    {
                        PropertiesInt[PropertyInt.ResistLockpick] = (int)resistLockpick;

                        var pickSkill = examiner.Skills[Skill.Lockpick].Current;

                        var successChance = SkillCheck.GetSkillChance((int)pickSkill, (int)resistLockpick) * 100;

                        if (!PropertiesInt.ContainsKey(PropertyInt.AppraisalLockpickSuccessPercent))
                        {
                            PropertiesInt.Add(PropertyInt.AppraisalLockpickSuccessPercent, (int)successChance);
                        }
                    }
                }
            }

            if (wo is Corpse)
            {
                PropertiesBool.Clear();
                PropertiesDID.Clear();
                PropertiesFloat.Clear();
                PropertiesInt64.Clear();

                var discardInts = PropertiesInt.Where(x => x.Key != PropertyInt.EncumbranceVal && x.Key != PropertyInt.Value).Select(x => x.Key).ToList();
                foreach (var key in discardInts)
                {
                    PropertiesInt.Remove(key);
                }
                var discardString = PropertiesString.Where(x => x.Key != PropertyString.LongDesc).Select(x => x.Key).ToList();
                foreach (var key in discardString)
                {
                    PropertiesString.Remove(key);
                }
            }

            if (wo is Portal)
            {
                if (PropertiesInt.ContainsKey(PropertyInt.EncumbranceVal))
                {
                    PropertiesInt.Remove(PropertyInt.EncumbranceVal);
                }
            }

            if (wo is Hook)
            {
                // If the hook has any inventory, we need to send THOSE properties instead.
                var hook = wo as Container;
                if (hook.Inventory.Count == 1)
                {
                    WorldObject hookedItem = hook.Inventory.First().Value;

                    // Hooked items have a custom "description", containing the desc of the sub item and who the owner of the house is (if any)
                    BuildProfile(hookedItem, examiner, success);
                    string baseDescString = "";
                    if (wo.ParentLink.HouseOwner != null)
                    {
                        // This is for backwards compatibility. This value was not set/saved in earlier versions.
                        // It will get the player's name and save that to the HouseOwnerName property of the house. This is now done when a player purchases a house.
                        if (wo.ParentLink.HouseOwnerName == null)
                        {
                            var houseOwnerPlayer = PlayerManager.FindByGuid((uint)wo.ParentLink.HouseOwner);
                            if (houseOwnerPlayer != null)
                            {
                                wo.ParentLink.HouseOwnerName = houseOwnerPlayer.Name;
                                wo.ParentLink.SaveBiotaToDatabase();
                            }
                        }
                        baseDescString = "This hook is owned by " + wo.ParentLink.HouseOwnerName + ". "; //if house is owned, display this text
                    }
                    if (PropertiesString.ContainsKey(PropertyString.LongDesc) && PropertiesString[PropertyString.LongDesc] != null)
                    {
                        PropertiesString[PropertyString.LongDesc] = baseDescString + "It contains: \n" + PropertiesString[PropertyString.LongDesc];
                    }
                    else if (PropertiesString.ContainsKey(PropertyString.ShortDesc) && PropertiesString[PropertyString.ShortDesc] != null)
                    {
                        PropertiesString[PropertyString.LongDesc] = baseDescString + "It contains: \n" + PropertiesString[PropertyString.ShortDesc];
                    }

                    BuildHookProfile(hookedItem);
                }
            }

            BuildFlags();
        }
Exemplo n.º 31
0
 public btreenode(int val, LockHelper lockhelper)
 {
     value = val;
     srwlck = lockhelper;
 }
Exemplo n.º 32
0
 public btree(LockHelper lockhelper)
 {
     srwlck = lockhelper;
 }