Ejemplo n.º 1
0
 private IEnumerator Appear()
 {
     // 出現アニメーションの終了を待機して歩行モーションに遷移
     yield return new WaitForSeconds (1.733f);
     GetComponent<Animator> ().SetBool ("isRunning", true);
     execute = Move;
 }
Ejemplo n.º 2
0
        public void Start(Action action, int sec)
        {
            Random rand = new Random();

            while (true)
            {
                string colorName = colorNames[rand.Next(numColors)];

                // Get ConsoleColor from string name
                ConsoleColor color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorName);

                colorName = colorNames[rand.Next(numColors)];
                ConsoleColor color2 = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorName);

                // Assuming you want to set the Foreground here, not the Background
                Console.ForegroundColor = color;
                Console.BackgroundColor = color2;

                Thread.Sleep(sec * 1000);

                Console.WriteLine("{0} seconds passed.", sec);

                Execute e = new Execute(action);

                e();
            }
        }
Ejemplo n.º 3
0
        static void Main()
        {
            DateTime date;
            Execute ex;
            while (true)
            {
                date = DateTime.Now;

                if (date.Second == 0)
                {
                    ex = new Execute(PrintZero);
                }
                else if (date.Second == 20)
                {
                    ex = new Execute(PrintTwenty);
                }
                else if (date.Second == 40)
                {
                    ex = new Execute(PrintFourty);
                }
                else
                {
                    ex = new Execute(Print);
                }
                ex(date.Second);
                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 4
0
 private IEnumerator KnockBack()
 {
     // ノックバックアニメーションの終了を待機して歩行モーションに遷移
     yield return new WaitForSeconds (0.567f);
     GetComponent<Animator> ().SetBool ("isHitDamage", false);
     isKnockingBack = false;
     execute = Move;
 }
Ejemplo n.º 5
0
 public void test()
 {
     var execute = new Execute();
     execute.startStop("a001 TCPサーバの 起動・停止時のSockState()の確認", ProtocolKind.Tcp);
     execute.startStop("a002 UDPサーバの 起動・停止時のSockState()の確認", ProtocolKind.Udp);
     execute.getLocalAddress("a003 TCPサーバのgetLocalAddress()の確認", ProtocolKind.Tcp);
     execute.getLocalAddress("a004 UDPサーバのgetLocalAddress()の確認", ProtocolKind.Udp);
 }
Ejemplo n.º 6
0
        public Execute Send(string to, string replyTo, string subject, string body)
        {
            Execute result = new Execute();

            Mails.Add(new MailInMemoryEntity(to, replyTo, subject, body));

            return result;
        }
Ejemplo n.º 7
0
 public void Vegrehajt(Execute parancs, IsDone fixedUpdateFeltetel = null)
 {
     lock(this)
     {
         execute = parancs;
         isDone = fixedUpdateFeltetel;
     }
     _waitHandle.WaitOne();
 }
        public void ComplexSpecificationWithExecute(PersonEntity data, bool valid, string message)
        {
            ComplexSpecificationValidation validation = new ComplexSpecificationValidation();
            Execute execute = new Execute();
            bool result = validation.IsSatisfiedBy(data, execute);

            valid.Should().Be(result, message);
            valid.Should().Be(!execute.HasErro, message);
        }
Ejemplo n.º 9
0
    private void Move()
    {
        // ターゲット方向へ移動
        transform.position = Vector3.Lerp (startPos, endPos, movingTime / arrivalTime_secs);
        movingTime += Time.deltaTime;

        // ターゲット方向へ移動を終了したら攻撃
        if (movingTime >= arrivalTime_secs) {
            GetComponent<Animator> ().SetBool ("isRunning", false);
            execute = Attack;
        }
    }
Ejemplo n.º 10
0
        public void ConstructorUser()
        {
            Execute execute = new Execute(SampleUser);

            execute.HasErro.Should().Be(false, "There isn't messages to have error");
            execute.HasWarning.Should().Be(false, "There isn't messages to have warning");
            execute.HasException.Should().Be(false, "There isn't messages to have exception");

            execute.User.Should().NotBeNull("The user was infomed");

            execute.Messages.Should().NotBeNull("Messages never can be null");
            execute.Messages.Count.Should().Be(0, "There isn't messages");
        }
Ejemplo n.º 11
0
        public void ConstructorNullParameters()
        {
            Execute execute = new Execute(null, null);

            execute.HasErro.Should().Be(false, "There isn't messages to have error");
            execute.HasWarning.Should().Be(false, "There isn't messages to have warning");
            execute.HasException.Should().Be(false, "There isn't messages to have exception");

            execute.User.Should().Be(null, "Just assing a user when it is infomed");

            execute.Messages.Should().NotBeNull("Messages never can be null");
            execute.Messages.Count.Should().Be(0, "There isn't messages");
        }
Ejemplo n.º 12
0
 public void Elenged(float kezdetiSebesseg = 0)
 {        
     lock (this)
     {
             execute = delegate
             {
                 if (lifting != null)
                 {
                     lifting.transform.parent = null;
                     lifting.transform.rotation = Quaternion.identity;
                     lifting.velocity = kezdetiSebesseg * transform.forward;
                     lifting.angularVelocity = Vector3.zero;
                     lifting.isKinematic = false;
                 }
             };
     }
     _waitHandle.WaitOne();
 }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Execute callback = new Execute(Print);
            callback += new Execute(Print);
            callback += Save;
            callback += new Execute(Console.WriteLine);

            callback += new Execute(new AndereClass().ShowDialog);
            callback += delegate(string message)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(message);
                Console.ForegroundColor = ConsoleColor.Gray;
            };

            callback += message => Console.WriteLine(message + " vanuit een lambda");

            callback("Hoi");
        }
Ejemplo n.º 14
0
		/// <summary>
		/// Adds command text to the command buffer.
		/// </summary>
		/// <param name="exec"></param>
		/// <param name="text"></param>
		public void BufferCommandText(Execute exec, string text)
		{
			if(text.EndsWith("\n") == false)
			{
				text += "\n";
			}

			switch(exec)
			{
				case Execute.Now:
					ExecuteCommandText(text);
					break;

				case Execute.Insert:
					InsertCommandText(text);
					break;

				case Execute.Append:
					AppendCommandText(text);
					break;
			}
		}
Ejemplo n.º 15
0
        public string DoanhThuPhat(string thang, string nam)
        {
            string query = "select sum(tg.TienPhat) as tientragop from PhieuTraGop tg where YEAR(tg.NgayTra) = " + nam + " and MONTH(tg.NgayTra)= " + thang + "";

            return(Execute.ExcuteQuery(query));
        }
Ejemplo n.º 16
0
        public void SyncData(object o)
        {
            var _tickets   = o;
            var notHnadled = DS.db.GetAll <PosTicket>(a => a.isHandled == 0 && a.FromTablet) as IEnumerable <PosTicket>;

            if (notHnadled == null)
            {
                return;
            }

            foreach (var item in notHnadled)
            {
                item.FromTablet = false;
                var here = Tickets.Where(a => a.NameTicket == item.NameTicket).FirstOrDefault();
                if (here != null)
                {
                    here.CarteLines = item.CarteLines;
                }
                else
                {
                    Tickets.Add(item);
                }

                if (item.DoPrintFromTablet)
                {
                    item.Position = this.Position;
                    this.Position++;
                    item.EnvoyerCuisine();
                    item.DoPrintFromTablet = false;
                    item.isLocal           = false;
                    item.Save();
                }
            }
            foreach (var item in Tickets.Reverse())
            {
                item.FromTablet = false;
                try{
                    var result = item.Save();
                    if (!result)
                    {
                        var isThere = DS.db.GetOne <PosTicket>(a => a.Id == item.Id);
                        if (isThere == null)
                        {
                            Tickets.Remove(item);
                        }
                    }
                }
                catch (Exception s) { Console.WriteLine("=======> " + s.Message); continue; }
            }


            NotifyOfPropertyChange("CurrentTicket");
            if (SelectedCartLine == null)
            {
                Execute.OnUIThread(CreateCartLines);
            }


            if (ShowTicketsVisible)
            {
                Execute.OnUIThread(ShowTickets);
            }
        }
Ejemplo n.º 17
0
 public override void Up()
 {
     Execute.EmbeddedScript("insert_Icd.sql");
 }
Ejemplo n.º 18
0
        public void DoiMatKhau(string password)
        {
            string query = "Update Admin set passAdmin='" + password + "' where userAdmin='Admin'";

            Execute.ExcuteNonquery(query);
        }
Ejemplo n.º 19
0
        public string DoanhThuOnline(string thang, string nam)
        {
            string query = "select sum(CTHDOnline.thanhTien) as doanhThuOnline from CTHDOnline where CTHDOnline.MaHD in(select hd.MaHD from HDOnline hd where YEAR(hd.NgayGiao)= " + nam + " and MONTH(hd.NgayGiao)= " + thang + ")";

            return(Execute.ExcuteQuery(query));
        }
 public override void Up()
 {
     Execute.Code(UpdatePropertyTypesAndGroupsDo);
 }
Ejemplo n.º 21
0
        public async Task ScanLabelAsync(List <int> ids, BpViewModel bpViewModel, ScanSide side, CancellationToken cancellationToken)
        {
            try
            {
                OcrAsyncChecker.CheckThread(OcrAsyncChecker.ScanLabelAsyncChecker);

                var finder = new Finder();

                float rotation = side == ScanSide.Left ? (float)29.7 : (float)-29.7;

                var bpVm       = new Dictionary <int, HeroSelectorViewModel>();
                var checkedDic = new Dictionary <int, bool>();
                foreach (var id in ids)
                {
                    var vm = bpViewModel.HeroSelectorViewModels.First(v => v.Id == id);
                    if (vm == null)
                    {
                        return;
                    }

                    bpVm[id] = vm;
                }

                for (var i = 0; i < ids.Count; ++i)
                {
                    checkedDic[i] = false;
                }

                var logUtil = new LogUtil(@".\logPick" + string.Join("&", ids) + ".txt");
                logUtil.Log("PickChecked");

                int  bpScreenFail = 0;
                bool warned       = false;
                bool awaitFlag    = false;
                while (checkedDic.Any(c => !c.Value))
                {
                    var sb        = new StringBuilder();
                    var sbConfirm = new StringBuilder();
                    var i         = checkedDic.FirstOrDefault(l => !l.Value).Key;

                    if (awaitFlag)
                    {
                        await Task.Delay(1000, cancellationToken).ConfigureAwait(false);

                        awaitFlag = false;
                    }

                    if (checkedDic.ContainsKey(i) && checkedDic[i])
                    {
                        continue;
                    }

                    if (bpVm[ids[i]].Selected)
                    {
                        checkedDic[i] = true;
                        continue;
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    if (SuspendScanning)
                    {
                        await Task.Delay(1000).ConfigureAwait(false);

                        continue;
                    }

                    logUtil.Log("Starting detect quit");
                    var processedResult = ProcessedResult.Fail;

                    int realPositionId = ids[i];

                    // first attempt
                    lock (ImageProcessingHelper.GDILock)
                    {
                        using (var bitmap = new ImageUtils().CaptureScreen())
                        {
                            if (!warned && bpViewModel.BpStatus.CurrentStep < 11 &&
                                StageFinder.ProcessStageInfo(bitmap).Step == -1)
                            {
                                bpScreenFail++;
                                if (bpScreenFail == 5)
                                {
                                    warned = true;
                                    bpViewModel.WarnNotInBp();
                                }
                            }
                            else
                            {
                                bpScreenFail = 0;
                            }

                            if (CheckIsOverlap(side, logUtil, bitmap))
                            {
                                awaitFlag = true;
                                continue;
                            }

                            sb.Clear();
                            sbConfirm.Clear();

                            foreach (var scanSideId in IdList[side].Where(id => !ProcessedPositions.ContainsKey(id)))
                            {
                                using (var bitMap = finder.AddNewTemplateBitmap(scanSideId, bitmap))
                                {
                                    logUtil.Log("Capture Complete " + scanSideId);
                                    processedResult = _recognizer.Recognize(bitMap, rotation, sb,
                                                                            _trustableThreashold);
                                    if (processedResult != ProcessedResult.Fail)
                                    {
                                        realPositionId = scanSideId;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    logUtil.Log("Checked " + ids[i] + " (" + sb + ")");

                    if (sb.ToString() == _recognizer.PickingText || string.IsNullOrEmpty(sb.ToString()) || processedResult == ProcessedResult.Fail)
                    {
                        continue;
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    if (SuspendScanning)
                    {
                        logUtil.Log("SuspendScanning delay 1000 " + ids[i]);
                        await Task.Delay(1000).ConfigureAwait(false);

                        continue;
                    }

                    // second attempt
                    FilePath tempscreenshotPath = null;
                    if (processedResult != ProcessedResult.Trustable)
                    {
                        logUtil.Log("Delay 500 " + ids[i]);
                        await Task.Delay(500).ConfigureAwait(false);

                        if (cancellationToken.IsCancellationRequested)
                        {
                            return;
                        }
                        if (SuspendScanning)
                        {
                            await Task.Delay(1000).ConfigureAwait(false);

                            continue;
                        }

                        lock (ImageProcessingHelper.GDILock)
                        {
                            tempscreenshotPath = finder.CaptureScreen();
                            using (var bitMap = finder.AddNewTemplateBitmap(realPositionId, tempscreenshotPath))
                            {
                                logUtil.Log("Capture Complete " + realPositionId);
                                _recognizer.Recognize(bitMap, rotation, sbConfirm,
                                                      _trustableThreashold);
                            }
                        }
                    }

                    logUtil.Log("Second checked " + ids[i] + " (" + sbConfirm.ToString() + ")");

                    if (SuspendScanning)
                    {
                        logUtil.Log("SuspendScanning delay 1000 " + ids[i]);
                        await Task.Delay(1000).ConfigureAwait(false);

                        continue;
                    }

                    if (bpVm[ids[i]].Selected)
                    {
                        logUtil.Log("Vm already selected delay 1000 " + ids[i]);
                        checkedDic[i] = true;
                        continue;
                    }

                    if (processedResult == ProcessedResult.Trustable)
                    {
                        bpScreenFail = 0;
                    }

                    if ((processedResult == ProcessedResult.Trustable || sb.ToString() == sbConfirm.ToString()) &&
                        !cancellationToken.IsCancellationRequested && CheckIfInFocus())
                    {
                        bpScreenFail = 0;
                        tempscreenshotPath?.DeleteIfExists();
                        var text  = sb.ToString();
                        var index = ids[checkedDic.First(l => !l.Value).Key];

                        if (ids.Contains(realPositionId) && !checkedDic[ids.IndexOf(realPositionId)])
                        {
                            index = realPositionId;
                        }

                        Execute.OnUIThread(() => { bpViewModel.ShowHeroSelector(index, text); });
                        ProcessedPositions[realPositionId] = true;
                        checkedDic[ids.IndexOf(index)]     = true;
                        logUtil.Log("Confirmed " + index + " " + text);
                    }
                }
                logUtil.Flush();
            }
            catch (Exception e)
            {
                File.WriteAllText(@".\error" + string.Join("&", ids) + ".txt", e.Message + e.StackTrace + e);
                throw;
            }
            finally
            {
                OcrAsyncChecker.CleanThread(OcrAsyncChecker.ScanLabelAsyncChecker);
            }
        }
 public override void Up()
 {
     Execute.EmbeddedScript("201407071024_SP_UpdatePersonCareerInformation.sql");
     Execute.EmbeddedScript("201407071024_SP_UpdatePersonCurrentPosition.sql");
 }
Ejemplo n.º 23
0
        public void UpdateNhanVien(string username, string password, string tenAdmin, int loai)
        {
            string query = "Update Admin set passAdmin= '" + password + "',tenAdmin='" + tenAdmin + "',Loai=" + loai + " where userAdmin='" + username + "'";

            Execute.ExcuteNonquery(query);
        }
 public override void Up()
 {
     Execute.EmbeddedScript("2_InsertMasterData.sql");
 }
Ejemplo n.º 25
0
 public override void Up()
 {
     // defer, because we are making decisions based upon what's in the database
     Execute.Code(MigrationCode);
 }
Ejemplo n.º 26
0
        public string GetNhanVien()
        {
            string query = "select * from Admin where Loai=2 or Loai =3";

            return(Execute.ExcuteQuery(query));
        }
Ejemplo n.º 27
0
 public void Fordul(GameObject cel)
 {
     lock (this)
     {
         execute = delegate
         {
             Vector3 c = cel.transform.position;
             c.y = transform.position.y;
             transform.LookAt(c);
         };
     }
     _waitHandle.WaitOne();
 }
Ejemplo n.º 28
0
 public override void Up()
 {
     Execute.EmbeddedScript("1_CustomerTable.sql");
 }
Ejemplo n.º 29
0
 public void Elore(float tavolsag)
 {
     lock (this)
     {
         execute = delegate
         {
             Vector3 dir = transform.forward.normalized;
             Vector3 t = target + tavolsag * dir;
             SetTarget(t.x, t.y, t.z);                                
         };
         isDone = delegate { return IsClose(); };
     }
     _waitHandle.WaitOne();
 }
        private TLUploadFileBase GetCdnFile(TLUploadFileCdnRedirect redirect, int dcId, TLInputDocumentFileLocation location, int offset, int limit, out TLRPCError er, out bool isCanceled)
        {
            var manualResetEvent      = new ManualResetEvent(false);
            TLUploadFileBase result   = null;
            TLRPCError       outError = null;
            var outIsCanceled         = false;

            var req = new TLUploadGetCdnFile();

            req.FileToken = redirect.FileToken;
            req.Limit     = limit;
            req.Offset    = offset;

            _mtProtoService.SendRequestAsync <TLUploadCdnFileBase>("upload.getCdnFile", req, redirect.DCId, true, callback =>
            {
                if (callback is TLUploadCdnFile file)
                {
                    var iv      = redirect.EncryptionIV;
                    var counter = offset / 16;
                    iv[15]      = (byte)(counter & 0xFF);
                    iv[14]      = (byte)((counter >> 8) & 0xFF);
                    iv[13]      = (byte)((counter >> 16) & 0xFF);
                    iv[12]      = (byte)((counter >> 24) & 0xFF);

                    var key = CryptographicBuffer.CreateFromByteArray(redirect.EncryptionKey);

                    var ecount_buf = new byte[0];
                    var num        = 0u;
                    var bytes      = Utils.AES_ctr128_encrypt(file.Bytes, key, ref iv, ref ecount_buf, ref num);

                    result = new TLUploadFile {
                        Bytes = bytes
                    };
                    manualResetEvent.Set();

                    _statsService.IncrementReceivedBytesCount(_mtProtoService.NetworkType, _dataType, file.Bytes.Length + 4);
                }
                else if (callback is TLUploadCdnFileReuploadNeeded reupload)
                {
                    result = ReuploadFile(redirect, reupload.RequestToken, dcId, location, offset, limit, out outError, out outIsCanceled);
                    while (result == null)
                    {
                        result = ReuploadFile(redirect, reupload.RequestToken, dcId, location, offset, limit, out outError, out outIsCanceled);
                        if (outIsCanceled)
                        {
                            break;
                        }
                    }

                    manualResetEvent.Set();
                }
            },
                                                                   error =>
            {
                outError = error;

                if (error.CodeEquals(TLErrorCode.INTERNAL) ||
                    (error.CodeEquals(TLErrorCode.BAD_REQUEST) && (error.TypeEquals(TLErrorType.LOCATION_INVALID) || error.TypeEquals(TLErrorType.VOLUME_LOC_NOT_FOUND))) ||
                    (error.CodeEquals(TLErrorCode.NOT_FOUND) && error.ErrorMessage != null && error.ErrorMessage.ToString().StartsWith("Incorrect dhGen")))
                {
                    outIsCanceled = true;

                    manualResetEvent.Set();
                    return;
                }

                int delay;
                lock (_randomRoot)
                {
                    delay = _random.Next(1000, 3000);
                }

                Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set());
            });

            manualResetEvent.WaitOne();
            er         = outError;
            isCanceled = outIsCanceled;

            return(result);
        }
Ejemplo n.º 31
0
    void FixedUpdate () {

        Vector3 g = new Vector3(0, 9.81f, 0);
        Vector3 p = target - rb.transform.position;
        Vector3 v = -1*rb.velocity;
        
        Vector3 f = g+Vector3.Scale(Kv, v) +Vector3.Scale(Kp, p);

        f = Vector3.Min(f, maximalisToloEro);
        f = Vector3.Max(f, -maximalisToloEro);

        rb.AddForce(engineOn*f, ForceMode.Force);

        Debug.DrawLine(transform.position, target, Color.red);

        lock(this)
        {
            if (execute != null)
            {
                execute();
                execute = null;
                if (isDone == null)
                    _waitHandle.Set();
            }
            if (isDone != null)
            {
                if (isDone())
                {
                    isDone = null;
                    _waitHandle.Set();
                }
            }
        }
        if (engine != null)
        {
            ParticleSystem.EmissionModule emission = engine.emission;
            emission.enabled = engineOn > 0;            
            engine.transform.rotation = Quaternion.LookRotation(-f);
            engine.startSize = f.magnitude / 9.81f;

        }

    }
        private void OnDownloading(object state)
        {
            DownloadablePart part = null;

            lock (_itemsSyncRoot)
            {
                for (var i = 0; i < _items.Count; i++)
                {
                    var item = _items[i];
                    if (item.IsCancelled)
                    {
                        _items.RemoveAt(i--);
                        try
                        {
                            //_eventAggregator.Publish(new UploadingCanceledEventArgs(item));
                        }
                        catch (Exception e)
                        {
                            TLUtils.WriteException(e);
                        }
                    }
                }

                foreach (var item in _items)
                {
                    part = item.Parts.FirstOrDefault(x => x.Status == PartStatus.Ready);
                    if (part != null)
                    {
                        part.Status = PartStatus.Processing;
                        break;
                    }
                }
            }

            if (part == null)
            {
                var currentWorker = (Worker)state;
                currentWorker.Stop();
                return;
            }

            var partName = part.ParentItem.InputDocumentLocation.GetPartFileName(part.Number);//string.Format("document{0}_{1}_{2}.dat", part.ParentItem.InputDocumentLocation.Id, part.ParentItem.InputDocumentLocation.AccessHash, part.Number);

            TLRPCError error;
            bool       canceled;

            do
            {
                TLUploadFileBase result;
                if (part.ParentItem.CdnRedirect != null)
                {
                    result = GetCdnFile(part.ParentItem.CdnRedirect, part.ParentItem.DCId, part.ParentItem.InputDocumentLocation, part.Offset, part.Limit, out error, out canceled);
                }
                else
                {
                    result = GetFile(part.ParentItem.DCId, part.ParentItem.InputDocumentLocation, part.Offset, part.Limit, out error, out canceled);
                }

                if (result is TLUploadFileCdnRedirect redirect)
                {
                    part.ParentItem.CdnRedirect = redirect;
                    continue;
                }
                else
                {
                    part.File = result as TLUploadFile;
                }

                if (canceled)
                {
                    lock (_itemsSyncRoot)
                    {
                        part.ParentItem.IsCancelled = true;
                        part.Status = PartStatus.Processed;
                        _items.Remove(part.ParentItem);
                    }

                    return;
                }
            } while (part.File == null);

            // indicate progress
            // indicate complete
            bool isComplete;
            bool isCanceled;
            var  progress = 0.0;

            lock (_itemsSyncRoot)
            {
                part.Status = PartStatus.Processed;

                if (!part.ParentItem.SuppressMerge)
                {
                    FileUtils.CheckMissingPart(_itemsSyncRoot, part, partName);
                }

                isCanceled = part.ParentItem.IsCancelled;

                isComplete = part.ParentItem.Parts.All(x => x.Status == PartStatus.Processed);
                if (!isComplete)
                {
                    var downloadedCount = part.ParentItem.Parts.Count(x => x.Status == PartStatus.Processed);
                    var count           = part.ParentItem.Parts.Count;
                    progress = downloadedCount / (double)count;
                }
                else
                {
                    //var id = part.ParentItem.InputDocumentLocation.Id;
                    //var accessHash = part.ParentItem.InputDocumentLocation.AccessHash;
                    //var fileExtension = Path.GetExtension(part.ParentItem.FileName.ToString());
                    //var fileName = string.Format("document{0}_{1}{2}", id, accessHash, fileExtension);

                    //if (fileName.EndsWith(".mp4"))
                    //{
                    //    Logs.Log.SyncWrite("FileManager.IsComplete " + fileName + " hash=" + part.ParentItem.GetHashCode());
                    //}

                    _items.Remove(part.ParentItem);
                }
            }

            if (!isCanceled)
            {
                if (isComplete)
                {
                    //var id = part.ParentItem.InputDocumentLocation.Id;
                    //var accessHash = part.ParentItem.InputDocumentLocation.AccessHash;
                    //var version = part.ParentItem.InputDocumentLocation.Version;
                    var fileExtension = Path.GetExtension(part.ParentItem.FileName.ToString());
                    var fileName      = GetFileName(part.ParentItem.InputDocumentLocation, fileExtension);
                    Func <DownloadablePart, string> getPartName = x => part.ParentItem.InputDocumentLocation.GetPartFileName(x.Number);

                    if (!part.ParentItem.SuppressMerge)
                    {
                        FileUtils.MergePartsToFile(getPartName, part.ParentItem.Parts, fileName);
                    }

                    part.ParentItem.IsoFileName = fileName;
                    if (part.ParentItem.Callback != null)
                    {
                        //Execute.BeginOnThreadPool(() =>
                        //{
                        //    part.ParentItem.Callback(part.ParentItem);
                        //    if (part.ParentItem.Callbacks != null)
                        //    {
                        //        foreach (var callback in part.ParentItem.Callbacks)
                        //        {
                        //            callback?.Invoke(part.ParentItem);
                        //        }
                        //    }
                        //});

                        part.ParentItem.Progress.Report(1.0);
                        part.ParentItem.Callback.TrySetResult(part.ParentItem);
                    }
                    else
                    {
                        Execute.BeginOnThreadPool(() => _eventAggregator.Publish(part.ParentItem));
                    }

                    _statsService.IncrementReceivedItemsCount(_mtProtoService.NetworkType, _dataType, 1);
                }
                else
                {
                    if (part.ParentItem.Callback != null)
                    {
                        part.ParentItem.Progress.Report(progress);
                    }
                    else
                    {
                        Execute.BeginOnThreadPool(() => _eventAggregator.Publish(new DownloadProgressChangedEventArgs(part.ParentItem, progress)));
                    }
                }
            }
        }
Ejemplo n.º 33
0
 internal void Share(string text = "", long gid = 0, string groupName = "")
 {
     if (this._wallPostData == null)
     {
         return;
     }
     this._wallPostData.WallPost.reposts.user_reposted = 1;
     this.UpdateCanSomethingProperties();
     WallService.Current.Repost(this._ownerId, this._postId, text, this._wallPostData.WallPost.GetRepostObjectType(), gid, (Action <BackendResult <RepostResult, ResultCode> >)(res => Execute.ExecuteOnUIThread((Action)(() =>
     {
         if (res.ResultCode == ResultCode.Succeeded)
         {
             GenericInfoUC.ShowPublishResult(GenericInfoUC.PublishedObj.WallPost, gid, groupName);
             if (gid != 0L || this.Liked)
             {
                 return;
             }
             this.Liked = true;
             EventAggregator current = EventAggregator.Current;
             WallItemLikedUnliked itemLikedUnliked = new WallItemLikedUnliked();
             itemLikedUnliked.OwnerId = this._wallPostData.WallPost.to_id;
             itemLikedUnliked.WallPostId = this._wallPostData.WallPost.id;
             int num = 1;
             itemLikedUnliked.Liked = num != 0;
             current.Publish((object)itemLikedUnliked);
         }
         else
         {
             new GenericInfoUC().ShowAndHideLater(CommonResources.Error, null);
         }
     }))));
 }
Ejemplo n.º 34
0
        /// <summary>
        /// The queue processor queue completed event handler.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void QueueProcessorQueueCompleted(object sender, QueueCompletedEventArgs e)
        {
            if (e.WasManuallyStopped)
            {
                return;
            }

            if (this.userSettingService.GetUserSetting <bool>(UserSettingConstants.PlaySoundWhenQueueDone))
            {
                this.PlayWhenDoneSound();
            }

            if (this.userSettingService.GetUserSetting <int>(UserSettingConstants.WhenCompleteAction) == (int)WhenDone.DoNothing)
            {
                return;
            }

            // Give the user the ability to cancel the shutdown. Default 60 second timer.
            bool isCancelled = false;

            if (!this.userSettingService.GetUserSetting <bool>(UserSettingConstants.WhenDonePerformActionImmediately))
            {
                ICountdownAlertViewModel titleSpecificView = IoC.Get <ICountdownAlertViewModel>();
                Execute.OnUIThread(
                    () =>
                {
                    titleSpecificView.SetAction((WhenDone)this.userSettingService.GetUserSetting <int>(UserSettingConstants.WhenCompleteAction));
                    this.windowManager.ShowDialog(titleSpecificView);
                    isCancelled = titleSpecificView.IsCancelled;
                });
            }

            if (!isCancelled)
            {
                this.ServiceLogMessage(string.Format("Performing 'When Done' Action: {0}", this.userSettingService.GetUserSetting <int>(UserSettingConstants.WhenCompleteAction)));

                // Do something when the encode ends.
                switch ((WhenDone)this.userSettingService.GetUserSetting <int>(UserSettingConstants.WhenCompleteAction))
                {
                case WhenDone.Shutdown:
                    ProcessStartInfo shutdown = new ProcessStartInfo("Shutdown", "-s -t 60");
                    shutdown.UseShellExecute = false;
                    Process.Start(shutdown);
                    Execute.OnUIThread(() => System.Windows.Application.Current.Shutdown());
                    break;

                case WhenDone.LogOff:
                    this.scanService.Dispose();
                    Win32.ExitWindowsEx(0, 0);
                    break;

                case WhenDone.Sleep:
                    Application.SetSuspendState(PowerState.Suspend, true, true);
                    break;

                case WhenDone.Hibernate:
                    Application.SetSuspendState(PowerState.Hibernate, true, true);
                    break;

                case WhenDone.LockSystem:
                    Win32.LockWorkStation();
                    break;

                case WhenDone.QuickHandBrake:
                    Execute.OnUIThread(() => System.Windows.Application.Current.Shutdown());
                    break;

                case WhenDone.EjectDisc:
                    mciSendString("set cdaudio door open", null, 0, IntPtr.Zero);
                    break;
                }
            }

            // Allow the system to sleep again.
            Execute.OnUIThread(() =>
            {
                if (this.userSettingService.GetUserSetting <bool>(UserSettingConstants.PreventSleep))
                {
                    Win32.AllowSleep();
                }
            });
        }
        public static void GenerateClass(MemoryObject obj)
        {
            var cts = new CancellationTokenSource();
            var ct  = cts.Token;

            var dialog = new MemoryObjectClassGeneratorDialog();

            dialog.HeaderText         = "Generating class...";
            dialog.StatusText         = "";
            dialog.ProgressPercentage = 0;
            dialog.Closed            += (s, e) =>
                                        cts.Cancel();

            var task = new Task <StringBuilder>(() =>
            {
                var type         = obj.GetType();
                var size         = type.SizeOf();
                string hexFormat = "X" + Math.Max(2, size.ToString("X").Length);
                var sb           = new StringBuilder();
                sb.AppendLine(string.Format("public class {0} : MemoryObject", type.Name));
                sb.AppendLine("{");

                int offset = 0;
                while (offset < size && !ct.IsCancellationRequested)
                {
                    Execute.OnUIThreadAsync(() =>
                    {
                        dialog.ProgressPercentage = 100d * offset / size;
                        dialog.StatusText         = string.Format("Scanning {0} / {1}", offset, size);
                    });

                    var ctx = new TypeMatchContext(obj, offset);
                    if (false ||
                        ctx.TryAsList() ||
                        ctx.TryAsAllocator() ||
                        ctx.TryAsBasicAllocator() ||
                        ctx.TryAsMap() ||
                        ctx.TryAsVector() ||
                        ctx.TryAsZeroInt32() ||                         // Anything that might be valid if first 4 bytes are zero must be above this check!
                        ctx.TryAsUIReference() ||
                        ctx.TryAsSno() ||
                        ctx.TryAsRefString() ||
                        ctx.TryAsText() ||
                        ctx.TryAsFloat() ||
                        ctx.TryAsPointer() ||
                        false)
                    {
                        if (ctx.Name == null)
                        {
                            ctx.Name = ctx.FieldType;
                        }
                    }
                    else
                    {
                        ctx.Prefix    = "_";
                        ctx.FieldType = "int";
                        ctx.Name      = "";
                        ctx.FieldSize = sizeof(int);
                        ctx.Comment   = ctx.Read <int>(0x00).ToString();
                    }

                    string line = string.Format("\t/* 0x{5:X8} */ public {0} {1}x{2}{3} {{ get {{ return Read<{0}>(0x{2}); }} }}{4}",
                                                ctx.FieldType,
                                                ctx.Prefix,
                                                ctx.Offset.ToString(hexFormat),
                                                ctx.Name == string.Empty ? string.Empty : ("_" + ctx.Name + ctx.Postfix),
                                                string.IsNullOrEmpty(ctx.Comment) ? string.Empty : " // " + ctx.Comment,
                                                ctx.MemoryObject.Address + ctx.Offset);
                    sb.AppendLine(line);

                    offset += ctx.FieldSize;
                }
                sb.AppendLine("}");
                return(sb);
            }, ct);

            task.ContinueWith(t =>
            {
                var sb = t.Result;
                Execute.OnUIThread(() =>
                {
                    dialog.Close();
                    var menu = new ContextMenu();
                    var item = new MenuItem {
                        Header = "Copy to clipboard"
                    };
                    item.Click += (s, e) => Clipboard.SetText(sb.ToString());
                    menu.Items.Add(item);
                    new Window()
                    {
                        Content = new ScrollViewer
                        {
                            Content = new TextBox
                            {
                                IsReadOnly  = true,
                                Text        = sb.ToString(),
                                FontFamily  = new FontFamily("Consolas"),
                                ContextMenu = menu
                            }
                        }
                    }.ShowDialog();
                });
            });
            task.Start();
            dialog.ShowDialog();
        }
Ejemplo n.º 36
0
        private async void ReceiveAsync(double timeout)
        {
            while (true)
            {
                if (Closed)
                {
                    return;
                }

                int bytesTransferred = 0;
                try
                {
                    bytesTransferred = (int)await _dataReader.LoadAsync(64);  //WithTimeout(timeout);
                }
                catch (Exception ex)
                {
                    //Log.Write(string.Format("  TCPTransport.ReceiveAsync transport={0} LoadAsync exception={1}", Id, ex));
                    var status = SocketError.GetStatus(ex.HResult);
                    WRITE_LOG("ReceiveAsync DataReader.LoadAsync " + status, ex);

                    if (ex is ObjectDisposedException)
                    {
                        return;
                    }
                }

                if (bytesTransferred > 0)
                {
                    //Log.Write(string.Format("  TCPTransport.ReceiveAsync transport={0} bytes_transferred={1}", Id, bytesTransferred));

                    var now = DateTime.Now;

                    if (!FirstReceiveTime.HasValue)
                    {
                        FirstReceiveTime = now;
                        RaiseConnectedAsync();
                    }

                    LastReceiveTime = now;

                    var buffer = new byte[_dataReader.UnconsumedBufferLength];
                    _dataReader.ReadBytes(buffer);

#if TCP_OBFUSCATED_2
                    buffer = Decrypt(buffer);
#endif

                    OnBufferReceived(buffer, 0, bytesTransferred);
                }
                else
                {
                    //Log.Write(string.Format("  TCPTransport.ReceiveAsync transport={0} bytes_transferred={1} closed={2}", Id, bytesTransferred, Closed));
                    if (!Closed)
                    {
                        Closed = true;
                        RaiseConnectionLost();
                        Execute.ShowDebugMessage("TCPTransportWinRT ReceiveAsync connection lost bytesTransferred=0; close transport");
                    }
                }
            }
        }
        public override void Up()
        {
            var script = Path.Combine(AppContext.BaseDirectory, "Scripts", "CreateAuthorTableUp.sql");

            Execute.Script(script);
        }
Ejemplo n.º 38
0
        public override void SendPacketAsync(string caption, byte[] data, Action <bool> callback, Action <TcpTransportResult> faultCallback = null)
        {
            var now = DateTime.Now;

            if (!FirstSendTime.HasValue)
            {
                FirstSendTime = now;
            }

            Execute.BeginOnThreadPool(async() =>
            {
                bool connect = false;
                bool isConnected;
                lock (_isConnectedSyncRoot)
                {
                    isConnected = _isConnected;
                    if (!_isConnected && !_isConnecting)
                    {
                        _isConnecting = true;
                        connect       = true;
                    }

                    if (connect &&
                        caption.StartsWith("msgs_ack"))
                    {
                        Execute.ShowDebugMessage("TCPTransportWinRT connect on msgs_ack");
                        connect = false;
                    }
                }

                if (!isConnected)
                {
                    if (connect)
                    {
                        var connectResult = await ConnectAsync(_timeout, faultCallback);
                        if (!connectResult)
                        {
                            return;
                        }

                        //var buffer = GetInitBuffer();
                        //var sendResult = await SendAsync(_timeout, buffer, faultCallback);
                        //if (!sendResult) return;

                        ReceiveAsync(_timeout);

                        SendQueue(_timeout);
                    }
                    else
                    {
                        Enqueue(caption, data, faultCallback);
                        return;
                    }
                }

                var sendPacketResult = await SendAsync(_timeout, CreatePacket(data), faultCallback);
                if (!sendPacketResult)
                {
                    return;
                }

                callback?.Invoke(true);
            });
        }
Ejemplo n.º 39
0
        private void InvokeCommand(string commandName, InvokeCommandMessage message)
        {
            ICommand command = commands[commandName];

            if (command.Async)
            {
                var worker = new Execute(command.Execute);
                var callback = new AsyncCallback(CommandCompletedCallback);

                AsyncOperation async = AsyncOperationManager.CreateOperation(message);

                log.DebugFormat("Starting asynchronous exeucution of \"{0}\"", message.Command);
                worker.BeginInvoke(message.IrcEventArgs, callback, async);
            }
            else
            {
                IEnumerable<string> response = commands[commandName].Execute(message.IrcEventArgs);
                log.DebugFormat("Synchronous execution of \"{0}\" complete. Sending response...", message.Command);

                if (response != null && response.Any())
                    SendIrcResponse(message, response);
            }
        }
 public override void Up()
 {
     Execute.EmbeddedScript("20160509094242_CREATE_CSP_INSERT_JOB_METRICS.sql");
 }
Ejemplo n.º 41
0
		public void BufferCommandArgs(Execute exec, idCmdArgs args)
		{
			switch(exec)
			{
				case Execute.Now:
					ExecuteTokenizedString(args);
					break;

				case Execute.Append:
					AppendCommandText("_execTokenized\n");
					_tokenizedCommands.Add(args);
					break;
			}
		}
Ejemplo n.º 42
0
 public void Kidob(GameObject objektum)
 {
     if (objektum != null)
     {
         lock (this)
         {
             execute = delegate
             {
                 Vector3 pos = transform.position + Vector3.down;
                 Instantiate(objektum, pos, Quaternion.identity);
             };
         }
         _waitHandle.WaitOne();
     }
 }
Ejemplo n.º 43
0
        public string DoanhThuOffline(string thang, string nam)
        {
            string query = "select sum(CTHDOff.thanhTien) as doanhthuoff from CTHDOff where CTHDOff.MaHD in(select hd.MaHD from HDOffLine hd where YEAR(hd.NgayMua)= " + nam + " and MONTH(hd.NgayMua)= " + thang + ")";

            return(Execute.ExcuteQuery(query));
        }
Ejemplo n.º 44
0
    public void Elmozdul(float deltaX, float deltaY, float deltaZ)
    {
        lock (this)
        {
            execute = delegate { SetTarget(target.x+ deltaX, target.y+ deltaY, target.z+ deltaZ); };
            isDone = delegate { return IsClose(); };
        }
        _waitHandle.WaitOne();

    }
Ejemplo n.º 45
0
 public GameObject[] Keres(string tag)
 {
     GameObject[] result = null;
     lock (this)
     {
         execute = delegate
         {
             result = GameObject.FindGameObjectsWithTag(tag);
             //Debug.Log("Keres: " + result);
         };
     }
     _waitHandle.WaitOne();
     return result;
 }
Ejemplo n.º 46
0
    public void Menj(float x, float y, float z)
    {
        lock(this)
        {
            execute = delegate { SetTarget(x, y, z); };
            isDone = delegate { return IsClose(); };
        }
        _waitHandle.WaitOne();

    }
Ejemplo n.º 47
0
 public void Fordul(float yRot)
 {
     lock(this)
     {
         execute = delegate
         {
             transform.Rotate(0, yRot, 0);
         };
     }
     _waitHandle.WaitOne();
 }
Ejemplo n.º 48
0
        public string GetPass(string password)
        {
            string query = "select * from Admin where userAdmin='Admin' and passAdmin='" + password + "'";

            return(Execute.ExcuteQuery(query));
        }
Ejemplo n.º 49
0
 public void Motor(bool on)
 {
     lock(this)
     {
         execute = delegate {
             engineOn = on ? 1.0f : 0.0f;
         };
     }
     _waitHandle.WaitOne();
 }
Ejemplo n.º 50
0
 private void DoReadOperation(Execute operation)
 {
     if (m_lock.TryEnterReadLock(m_Timeout))
     {
         try
         {
             operation();
         }
         finally
         {
             if (m_lock.IsReadLockHeld)
                 m_lock.ExitReadLock();
         }
     }
 }
Ejemplo n.º 51
0
    public void Menj(GameObject o, float deltaX, float deltaY, float deltaZ)
    {
        lock (this)
        {
            execute = delegate { SetTarget(o.transform.position.x + deltaX, o.transform.position.y + deltaY, o.transform.position.z + deltaZ); };
            isDone = delegate { return IsClose(); };
        }
        _waitHandle.WaitOne();


    }
Ejemplo n.º 52
0
 public void LoadMoreCommentsInUI()
 {
     if (this._wallResponseData != null)
     {
         if (this._wallPostData == null)
         {
             this._wallPostData = new NewsItemDataWithUsersAndGroupsInfo()
             {
                 WallPost = this._wallResponseData.WallPost,
                 Profiles = this._wallResponseData.Users,
                 Groups   = this._wallResponseData.Groups
             }
         }
         ;
         this.AddNewsItemIfItIsNotThere();
     }
     if (this.AllLoaded())
     {
         this.CallLoadedCallback();
     }
     else if (this.HaveInBuffer())
     {
         this.LoadCommentsFromBuffer();
         if (this._loadingInBuffer)
         {
             return;
         }
         this._loadingInBuffer = true;
         this.LoadMoreCommentsInBuffer((Action <bool>)(success => Execute.ExecuteOnUIThread((Action)(() =>
         {
             this._loadingInBuffer = false;
             if (!this._loadMoreInUIFlag)
             {
                 return;
             }
             this._loadMoreInUIFlag = false;
             if (!success)
             {
                 return;
             }
             this.LoadMoreCommentsInUI();
         }))));
     }
     else if (this._loadingInBuffer)
     {
         this._loadMoreInUIFlag = true;
     }
     else
     {
         this._loadingInBuffer = true;
         this.LoadMoreCommentsInBuffer((Action <bool>)(success => Execute.ExecuteOnUIThread((Action)(() =>
         {
             this._loadingInBuffer = false;
             if (!success)
             {
                 return;
             }
             this.LoadMoreCommentsInUI();
         }))));
     }
 }
Ejemplo n.º 53
0
 public void Felirat(string value)
 {
     if (text != null)
     {
         lock (this)
         {
             execute = delegate { text.text = value; };                
         }
         _waitHandle.WaitOne();
     }
 }
Ejemplo n.º 54
0
        private void LoadMoreCommentsInBuffer(Action <bool> completionCallback)
        {
            int            countToRead  = this._commentsCount != -1 ? this._countToReload : this._countToLoad;
            bool           needWallPost = this._wallPostData == null;
            LikeObjectType likeObjType  = LikeObjectType.post;

            if (this._wallPostData != null && this._wallPostData.WallPost != null)
            {
                likeObjType = this._wallPostData.WallPost.GetLikeObjectType();
            }
            if (needWallPost || !this.IsWallPostAddedToUI)
            {
                this.SetInProgress(true, CommonResources.Loading);
            }
            WallService.Current.GetWallPostByIdWithComments(this._postId, this._ownerId, this._fetchedComments.Count, countToRead, this._commentsCount, needWallPost, (Action <BackendResult <GetWallPostResponseData, ResultCode> >)(res => Execute.ExecuteOnUIThread((Action)(() =>
            {
                this.SetInProgress(false, "");
                if (res.ResultCode != ResultCode.Succeeded)
                {
                    completionCallback(false);
                }
                else
                {
                    if (this._commentsCount == -1)
                    {
                        EventAggregator.Current.Publish((object)new WallCommentsLikesUpdated()
                        {
                            OwnerId = this._ownerId,
                            WallPostId = this._postId,
                            CommentsCount = res.ResultData.Count,
                            LikesCount = res.ResultData.LikesAll.count
                        });
                        this._commentsCount = res.ResultData.Count;
                        this._runningCountOfComments = this._commentsCount;
                    }
                    this._user1List.AddRange((IEnumerable <User>)res.ResultData.Users);
                    this._user2List.AddRange((IEnumerable <User>)res.ResultData.Users2);
                    if (AppGlobalStateManager.Current.GlobalState.LoggedInUser != null)
                    {
                        this._user1List.Add(AppGlobalStateManager.Current.GlobalState.LoggedInUser);
                        this._user2List.Add(AppGlobalStateManager.Current.GlobalState.LoggedInUser);
                    }
                    this._groupsList.AddRange((IEnumerable <Group>)res.ResultData.Groups);
                    List <Comment> commentList = this._fetchedComments;
                    this._fetchedComments = res.ResultData.Comments;
                    foreach (Comment comment1 in commentList)
                    {
                        Comment comment = comment1;
                        if (!this._fetchedComments.Any <Comment>((Func <Comment, bool>)(c => c.cid == comment.cid)))
                        {
                            this._fetchedComments.Add(comment);
                        }
                    }
                    this._wallResponseData = res.ResultData;
                    if (this._wallResponseData.WallPost.to_id == 0L && this._wallPostData != null)
                    {
                        this._wallResponseData.WallPost = this._wallPostData.WallPost;
                    }
                    completionCallback(true);
                    if (!this._wallPostData.WallPost.IsNotExist)
                    {
                        return;
                    }
                    int num = (int)MessageBox.Show(CommonResources.WallPostIsNotAvailable, CommonResources.Error, MessageBoxButton.OK);
                    Navigator.Current.GoBack();
                }
            }))), this.PollId, this.PollOwnerId, likeObjType);
        }
Ejemplo n.º 55
0
        //public String getFileName()
        //{
        //    if (this.location != null)
        //    {
        //        return this.location.volume_id + "_" + this.location.local_id + "." + this.ext;
        //    }

        //    return Utils.ComputeMD5(this.webLocation.Url) + "." + this.ext;
        //}

        public bool Start()
        {
            if (state != stateIdle)
            {
                return(false);
            }
            if (location == null && webLocation == null)
            {
                onFail(true, 0);
                return(false);
            }

            String fileNameFinal;
            String fileNameTemp;
            String fileNameIv = null;

            if (webLocation != null)
            {
                String md5 = Utils.MD5(webLocation.Url);
                fileNameTemp  = md5 + ".temp";
                fileNameFinal = md5 + ext;
                if (key != null)
                {
                    fileNameIv = md5 + ".iv";
                }
            }
            else
            {
                var volume_id = 0L;
                var local_id  = 0;
                var id        = 0L;

                if (location is TLInputFileLocation fileLocation)
                {
                    volume_id = fileLocation.VolumeId;
                    local_id  = fileLocation.LocalId;
                }
                else if (location is TLInputDocumentFileLocation documentLocation)
                {
                    id = documentLocation.Id;
                }

                if (volume_id != 0 && local_id != 0)
                {
                    if (datacenter_id == int.MinValue || volume_id == int.MinValue || datacenter_id == 0)
                    {
                        onFail(true, 0);
                        return(false);
                    }

                    fileNameTemp  = volume_id + "_" + local_id + ".temp";
                    fileNameFinal = volume_id + "_" + local_id + ext;
                    if (key != null)
                    {
                        fileNameIv = volume_id + "_" + local_id + ".iv";
                    }
                }
                else
                {
                    if (datacenter_id == 0 || id == 0)
                    {
                        onFail(true, 0);
                        return(false);
                    }

                    fileNameTemp  = datacenter_id + "_" + id + ".temp";
                    fileNameFinal = datacenter_id + "_" + id + ext;
                    if (key != null)
                    {
                        fileNameIv = datacenter_id + "_" + id + ".iv";
                    }
                }
            }
            currentDownloadChunkSize   = totalBytesCount >= bigFileSizeFrom ? downloadChunkSizeBig : downloadChunkSize;
            currentMaxDownloadRequests = totalBytesCount >= bigFileSizeFrom ? maxDownloadRequestsBig : maxDownloadRequests;
            requestInfos        = new List <RequestInfo>(currentMaxDownloadRequests);
            delayedRequestInfos = new List <RequestInfo>(currentMaxDownloadRequests - 1);
            state = stateDownloading;

            cacheFileFinal = new FileInfo(Path.Combine(storePath, fileNameFinal));
            bool exist = cacheFileFinal.Exists;

            if (exist && totalBytesCount != 0 && totalBytesCount != cacheFileFinal.Length)
            {
                cacheFileFinal.Delete();
            }

            if (!cacheFileFinal.Exists)
            {
                cacheFileTemp = new FileInfo(Path.Combine(tempPath, fileNameTemp));
                if (cacheFileTemp.Exists)
                {
                    downloadedBytes    = (int)cacheFileTemp.Length;
                    nextDownloadOffset = downloadedBytes = downloadedBytes / currentDownloadChunkSize * currentDownloadChunkSize;
                }

                //if (BuildVars.DEBUG_VERSION)
                //{
                //    FileLog.d("start loading file to temp = " + cacheFileTemp + " final = " + cacheFileFinal);
                //}

                if (fileNameIv != null)
                {
                    cacheIvTemp = new FileInfo(Path.Combine(tempPath, fileNameIv));
                    try
                    {
                        //fiv = new RandomAccessFile(cacheIvTemp, "rws");
                        fiv = new FileStream(cacheIvTemp.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                        long len = cacheIvTemp.Length;
                        if (len > 0 && len % 32 == 0)
                        {
                            fiv.Read(iv, 0, 32);
                        }
                        else
                        {
                            downloadedBytes = 0;
                        }
                    }
                    catch (Exception e)
                    {
                        //FileLog.e(e);
                        downloadedBytes = 0;
                    }
                }
                try
                {
                    //fileOutputStream = new RandomAccessFile(cacheFileTemp, "rws");
                    fileOutputStream = new FileStream(cacheFileTemp.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    if (downloadedBytes != 0)
                    {
                        fileOutputStream.Seek(downloadedBytes, SeekOrigin.Begin);
                    }
                }
                catch (Exception e)
                {
                    //FileLog.e(e);
                }
                if (fileOutputStream == null)
                {
                    onFail(true, 0);
                    return(false);
                }
                started = true;
                //Utilities.stageQueue.postRunnable(new Runnable() {
                //@Override
                //public void run()
                //{
                Execute.BeginOnThreadPool(() =>
                {
                    if (totalBytesCount != 0 && downloadedBytes == totalBytesCount)
                    {
                        try
                        {
                            OnFinishLoadingFile(false);
                        }
                        catch (Exception e)
                        {
                            onFail(true, 0);
                        }
                    }
                    else
                    {
                        startDownloadRequest();
                    }
                });
                //    }
                //});
            }
            else
            {
                started = true;
                try
                {
                    OnFinishLoadingFile(false);
                }
                catch (Exception e)
                {
                    onFail(true, 0);
                }
            }
            return(true);
        }
Ejemplo n.º 56
0
        public void InsertNhanVien(string username, string password, string tennhanvien, int loai)
        {
            string query = "insert into Admin(userAdmin,passAdmin,tenAdmin,Loai) values('" + username + "','" + password + "','" + tennhanvien + "'," + loai + ")";

            Execute.ExcuteNonquery(query);
        }
Ejemplo n.º 57
0
    public bool Felszed(bool changeTag = false)
    { 
        lock (this)
        {
            float targetY = 0.0f;
            lifting = null;

            execute = delegate
            {
                Ray ray = new Ray(transform.position, -1 * transform.up);
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit, 100))
                {
                    //Debug.Log("Hit something", hit.rigidbody);
                    if (hit.rigidbody)
                    {
                        lifting = hit.rigidbody;
                        targetY = this.transform.position.y - 0.8f;

                        lifting.transform.parent = this.transform;

                        if (changeTag)
                        {
                            lifting.gameObject.tag = tag;
                        }
                    }
                }
            };
            isDone = delegate
            {
                if (lifting == null)
                    return true;

                if (lifting.position.y > targetY || lifting.velocity.magnitude < 0.01f)
                {
                    lifting.isKinematic = true;
                    lifting.velocity = Vector3.zero;
                    lifting.angularVelocity = Vector3.zero;
                    lifting.transform.position = transform.position + new Vector3(0, -0.8f, 0);
                    lifting.transform.rotation = Quaternion.identity;
                    return true;

                }
                else
                {
                    lifting.AddForce(0, 50, 0, ForceMode.Acceleration);
                    return false;
                }

            };
        }
        _waitHandle.WaitOne();
        return lifting != null;
    }
 public override void Up()
 {
     Execute.EmbeddedScript("20160420161139_CREATE_TABLE_EVT_CLASS.sql");
 }
Ejemplo n.º 59
0
 private void DoWriteOperateion(Execute operation)
 {
     if (m_lock.TryEnterWriteLock(m_Timeout))
     {
         try
         {
             operation();
         }
         finally
         {
             if (m_lock.IsWriteLockHeld)
                 m_lock.ExitWriteLock();
         }
     }
 }
Ejemplo n.º 60
0
 void ICommand.Execute(object parameter)
 {
     ControlExtended.SafeInvoke(() => Execute?.Invoke(parameter), LogType.Info, GlobalHelper.Get("key_133") + this.Text);
     HockeyClient.Current.TrackEvent(this.Text);
 }