コード例 #1
0
ファイル: Request.cs プロジェクト: BenDol/RocketLauncher
 public Request(Uri url, String director, ref DownloadHandler dlHandler, Double lastVersion)
 {
     this.url = url;
     this.director = director;
     this.dlHandler = dlHandler;
     this.lastVersion = lastVersion;
 }
コード例 #2
0
ファイル: Reciever.cs プロジェクト: BenDol/RocketLauncher
        public Reciever(ref DownloadHandler dlHandler, Client client)
        {
            file = Path.Combine(Application.StartupPath, Client.UPDATE_XML_NAME);
            this.dlHandler = dlHandler;
            this.client = client;

            load();
        }
コード例 #3
0
 public UnityWebRequest(string url, string method, DownloadHandler downloadHandler, UploadHandler uploadHandler)
 {
     this.InternalCreate();
     this.InternalSetDefaults();
     this.url = url;
     this.method = method;
     this.downloadHandler = downloadHandler;
     this.uploadHandler = uploadHandler;
 }
コード例 #4
0
ファイル: Client.cs プロジェクト: BenDol/RocketLauncher
        public Client(Ui ui)
        {
            this.ui = ui;

            dlHandler = new DownloadHandler(ui.getStatusLabel(), ui.getDownloadProgressBar());
            reciever = new Reciever(ref dlHandler, this);

            Logger.log(Logger.TYPE.DEBUG, "Client successfully constructed.");
        }
コード例 #5
0
ファイル: CefView.cs プロジェクト: need-sleep/WebViewANE
        private ChromiumWebBrowser CreateNewBrowser()
        {
            var browser = new ChromiumWebBrowser(InitialUrl?.Url)
            {
                Dock = DockStyle.Fill
            };

            browser.JavascriptObjectRepository.Register("webViewANE", new BoundObject(Context), true,
                                                        BindingOptions.DefaultBinder);

            var dh = new DownloadHandler(DownloadPath);

            dh.OnDownloadUpdatedFired += OnDownloadUpdatedFired;
            dh.OnBeforeDownloadFired  += OnDownloadFired;

            KeyboardHandler = new KeyboardHandler(Context);
            KeyboardHandler.OnKeyEventFired += OnKeyEventFired;

            if (EnableDownloads)
            {
                browser.DownloadHandler = dh;
            }

            browser.KeyboardHandler = KeyboardHandler;

            var sh = new LifeSpanHandler(PopupBehaviour, PopupDimensions);

            sh.OnPermissionPopup                += OnPermissionPopup;
            sh.OnPopupBlock                     += OnPopupBlock;
            browser.LifeSpanHandler              = sh;
            browser.FrameLoadEnd                += OnFrameLoaded;
            browser.AddressChanged              += OnBrowserAddressChanged;
            browser.TitleChanged                += OnBrowserTitleChanged;
            browser.LoadingStateChanged         += OnBrowserLoadingStateChanged;
            browser.LoadError                   += OnLoadError;
            browser.IsBrowserInitializedChanged += OnBrowserInitialized;
            browser.StatusMessage               += OnStatusMessage;
            browser.DisplayHandler               = new DisplayHandler();

            if (!ContextMenuEnabled)
            {
                browser.MenuHandler = new MenuHandler();
            }

            var rh = new RequestHandler(WhiteList, BlackList);

            rh.OnUrlBlockedFired += OnUrlBlockedFired;

            browser.RequestHandler = rh;
            _tabs.Add(browser);
            TabDetails.Add(new TabDetails());

            return(browser);
        }
コード例 #6
0
 protected override void HandleResponseData(DownloadHandler downloadHandler)
 {
     if (IsError)
     {
         base.HandleResponseData(downloadHandler);
     }
     {
         ResponseData.Content = downloadHandler.data;
         ResponseData.Texture = DownloadHandlerTexture.GetContent(WebRequest);
     }
 }
コード例 #7
0
 protected override void HandleResponseData(DownloadHandler downloadHandler)
 {
     if (IsError)
     {
         base.HandleResponseData(downloadHandler);
     }
     else
     {
         ResponseData.Content = downloadHandler.data;
     }
 }
コード例 #8
0
 public WebRequestAsyncOperation Get(
     string url,
     DownloadHandler downloadHandler    = null,
     Action <UnityWebRequest> OnSuccess = null,
     Action <UnityWebRequest> OnFail    = null,
     int requestAttemps      = 3,
     int timeout             = 0,
     bool disposeOnCompleted = true)
 {
     return(SendWebRequest(genericWebRequest, url, downloadHandler, OnSuccess, OnFail, requestAttemps, timeout, disposeOnCompleted));
 }
コード例 #9
0
ファイル: GlbAsset.cs プロジェクト: manniru/glTFast
        protected override IEnumerator LoadContent(DownloadHandler dlh)
        {
            byte[] results = dlh.data;
            gLTFastInstance = new GLTFast();
            var success = gLTFastInstance.LoadGlb(results, transform);

            if (onLoadComplete != null)
            {
                onLoadComplete(success);
            }
            yield break;
        }
コード例 #10
0
 protected override void HandleResponseData(DownloadHandler downloadHandler)
 {
     if (IsError)
     {
         base.HandleResponseData(downloadHandler);
     }
     else
     {
         ResponseData.Content   = downloadHandler.data;
         ResponseData.AudioClip = DownloadHandlerAudioClip.GetContent(WebRequest);
     }
 }
コード例 #11
0
 public void UpdateDownloadHandler(DownloadHandler downloadHandler)
 {
     if (webRequest == null)
     {
         customDownloadHandler = downloadHandler;
     }
     else
     {
         webRequest.downloadHandler = downloadHandler;
         customDownloadHandler      = null;
     }
 }
        public void Token_And_Blocks_Should_Match_Default_Block_Size()
        {
            var blockSize = FileSystemConfiguration.DefaultDownloadBlockSize;

            Token = DownloadHandler.RequestDownloadToken(SourceFileInfo.FullName, false);
            Assert.AreEqual(blockSize, Token.DownloadBlockSize);

            BufferedDataBlock block = DownloadHandler.ReadBlock(Token.TransferId, 5);

            Assert.AreEqual(blockSize, block.BlockLength);
            Assert.AreEqual(blockSize, block.Data.Length);
        }
コード例 #13
0
        public void Requesting_Token_With_Block_Size_Above_Default_Should_Return_Bigger_Blocks()
        {
            var blockSize = FileSystemConfiguration.DefaultDownloadBlockSize + 50;

            Token = DownloadHandler.RequestDownloadToken(SourceFileInfo.FullName, false, blockSize);
            Assert.AreEqual(blockSize, Token.DownloadBlockSize);

            BufferedDataBlock block = DownloadHandler.ReadBlock(Token.TransferId, 0);

            Assert.AreEqual(blockSize, block.BlockLength);
            Assert.AreEqual(blockSize, block.Data.Length);
        }
コード例 #14
0
 public override void OnRequestFinished(DownloadHandler handler)
 {
     if (handler == null)
     {
         Handler?.Invoke(null);
     }
     else
     {
         DownloadHandlerTexture downloadHandler = handler as DownloadHandlerTexture;
         Handler?.Invoke(downloadHandler.texture);
     }
 }
コード例 #15
0
ファイル: Form2.cs プロジェクト: miguelpunzal/myToolbox
        public void InitBrowser()
        {
            Cef.Initialize(new CefSettings());
            browser = new ChromiumWebBrowser(urlString);
            this.Controls.Add(browser);
            DownloadHandler downer = new DownloadHandler(this);

            browser.DownloadHandler        = downer;
            downer.OnBeforeDownloadFired  += OnBeforeDownloadFired;
            downer.OnDownloadUpdatedFired += OnDownloadUpdatedFired;
            //browser.Dock = DockStyle.Fill;
        }
コード例 #16
0
        public void Requesting_Token_With_Block_Size_Below_Default_Should_Return_Small_Blocks()
        {
            var blockSize = 20480;

            Token = DownloadHandler.RequestDownloadToken(SourceFileInfo.FullName, false, blockSize);
            Assert.AreEqual(blockSize, Token.DownloadBlockSize);

            BufferedDataBlock block = DownloadHandler.ReadBlock(Token.TransferId, 0);

            Assert.AreEqual(blockSize, block.BlockLength);
            Assert.AreEqual(blockSize, block.Data.Length);
        }
コード例 #17
0
 public override void OnRequestFinished(DownloadHandler handler)
 {
     if (handler == null)
     {
         Handler?.Invoke(null);
     }
     else
     {
         DownloadHandlerAudioClip downloadHandler = handler as DownloadHandlerAudioClip;
         Handler?.Invoke(downloadHandler.audioClip);
     }
 }
コード例 #18
0
        private static IEnumerator RunRequest(string url, WWWForm wwwForm, Action <WebResponse> responseHandler, int timeout, bool isAsset)
        {
#if !LP_UNITY_LEGACY_WWW
            using (var request = CreateWebRequest(url, wwwForm, isAsset))
            {
                request.timeout = timeout;

                yield return(request.SendWebRequest());

                while (!request.isDone)
                {
                    yield return(null);
                }

                if (request.result == UnityNetworkingRequest.Result.ConnectionError ||
                    request.result == UnityNetworkingRequest.Result.ProtocolError)
                {
                    responseHandler(new LeanplumUnityWebResponse(request.responseCode, request.error, null, null));
                }
                else
                {
                    DownloadHandler            download      = request.downloadHandler;
                    DownloadHandlerAssetBundle downloadAsset = download as DownloadHandlerAssetBundle;
                    responseHandler(new LeanplumUnityWebResponse(request.responseCode,
                                                                 request.error,
                                                                 !isAsset ? download.text : null,
                                                                 isAsset ? downloadAsset?.assetBundle : null));
                }
            }
#else
            using (WWW www = CreateWww(url, wwwForm, isAsset))
            {
                float elapsed = 0.0f;
                while (!www.isDone && elapsed < timeout)
                {
                    elapsed += Time.deltaTime;
                    yield return(null);
                }

                if (www.isDone)
                {
                    responseHandler(new UnityWebResponse(200, www.error,
                                                         (String.IsNullOrEmpty(www.error) && !isAsset) ? www.text : null,
                                                         (String.IsNullOrEmpty(www.error) && isAsset) ? www.assetBundle : null));
                }
                else
                {
                    responseHandler(new UnityWebResponse(408, Constants.NETWORK_TIMEOUT_MESSAGE, String.Empty, null));
                }
            }
#endif
        }
        public void Requesting_Random_Block_Numbers_Should_Work()
        {
            for (int i = 0; i < 10; i++)
            {
                DownloadHandler.ReadBlock(Token.TransferId, i);
            }

            var block20     = DownloadHandler.ReadBlock(Token.TransferId, 20);
            var block4      = DownloadHandler.ReadBlock(Token.TransferId, 4);
            var block20Copy = DownloadHandler.ReadBlock(Token.TransferId, 20);

            Assert.AreEqual(block20.Data, block20Copy.Data);
        }
        public void Read_Blocks_Should_Be_Reflected_In_Block_Table()
        {
            BufferedDataBlock block1 = DownloadHandler.ReadBlock(Token.TransferId, 5);
            BufferedDataBlock block2 = DownloadHandler.ReadBlock(Token.TransferId, 7);

            IEnumerable <DataBlockInfo> transferTable = DownloadHandler.GetTransferredBlocks(Token.TransferId);

            Assert.AreEqual(2, transferTable.Count());
            Assert.AreEqual(block1.BlockNumber, transferTable.First().BlockNumber);
            Assert.AreEqual(block1.Offset, transferTable.First().Offset);
            Assert.AreEqual(block2.BlockNumber, transferTable.Last().BlockNumber);
            Assert.AreEqual(block2.Offset, transferTable.Last().Offset);
        }
コード例 #21
0
        public static UnityWebRequest PostRequest(string uri, WWWForm formData, DownloadHandler downloader)
        {
            byte[]          data    = UWebRequestCreator.FormDataToByte(formData);
            UnityWebRequest request = UWebRequestCreator.PostRequest(uri, data, downloader);

            //set request headers
            if (formData != null)
            {
                UWebRequestCreator.SetupRequestHeaders(request, formData.headers);
            }

            return(request);
        }
コード例 #22
0
    IEnumerator CopyKwsModelFileFromStreamingAssetsAsync()
    {
        string fromFile = Application.streamingAssetsPath + Path.DirectorySeparatorChar + kwsModelFile;
        string toFile   = Application.persistentDataPath + Path.DirectorySeparatorChar + kwsModelFile;

        UnityWebRequest downloader = UnityWebRequest.Get(fromFile);

        yield return(downloader.SendWebRequest());

        DownloadHandler handler = downloader.downloadHandler;

        File.WriteAllBytes(toFile, handler.data);
    }
コード例 #23
0
        public void Requesting_Token_With_Block_Size_Above_Max_Size_Should_Fall_Back_To_Maxium()
        {
            var blockSize    = FileSystemConfiguration.MaxDownloadBlockSize.Value + 10000;
            var expectedSize = FileSystemConfiguration.MaxDownloadBlockSize.Value;

            Token = DownloadHandler.RequestDownloadToken(SourceFileInfo.FullName, false, blockSize);
            Assert.AreEqual(expectedSize, Token.DownloadBlockSize);

            BufferedDataBlock block = DownloadHandler.ReadBlock(Token.TransferId, 0);

            Assert.AreEqual(expectedSize, block.BlockLength);
            Assert.AreEqual(expectedSize, block.Data.Length);
        }
コード例 #24
0
ファイル: DownloadManager.cs プロジェクト: wwwK/Nacollector
        public DownloadManager(CrBrowser crBrowser)
        {
            _crBrowser = crBrowser;
            browser    = _crBrowser.GetBrowser();

            var handler = new DownloadHandler();

            handler.OnBeforeDownloadFired  += (s, e) => OnBeforeDownload(e, e.downloadItem);
            handler.OnDownloadUpdatedFired += (s, e) => OnDownloadUpdated(e, e.downloadItem);

            _crBrowser.GetBrowser().DownloadHandler = handler;
            _crBrowser.GetBrowser().RegisterAsyncJsObject("CrDownloadsCallBack", new CrDownloadsCallBack(this));
        }
コード例 #25
0
        private void InitializeControl()
        {
            var contextMenuHandler = new ContextMenuHandler();
            var dialogHandler      = new DialogHandler();
            var displayHandler     = new DisplayHandler();
            var downloadLogger     = logger.CloneFor($"{nameof(DownloadHandler)} #{Id}");
            var downloadHandler    = new DownloadHandler(appConfig, downloadLogger, settings, WindowSettings);
            var keyboardHandler    = new KeyboardHandler();
            var lifeSpanHandler    = new LifeSpanHandler();
            var requestFilter      = new RequestFilter();
            var requestLogger      = logger.CloneFor($"{nameof(RequestHandler)} #{Id}");
            var resourceHandler    = new ResourceHandler(appConfig, requestFilter, logger, settings, WindowSettings, text);
            var requestHandler     = new RequestHandler(appConfig, requestFilter, requestLogger, resourceHandler, settings, WindowSettings, text);

            Icon = new BrowserIconResource();

            dialogHandler.DialogRequested  += DialogHandler_DialogRequested;
            displayHandler.FaviconChanged  += DisplayHandler_FaviconChanged;
            displayHandler.ProgressChanged += DisplayHandler_ProgressChanged;
            downloadHandler.ConfigurationDownloadRequested += DownloadHandler_ConfigurationDownloadRequested;
            downloadHandler.DownloadUpdated           += DownloadHandler_DownloadUpdated;
            keyboardHandler.FindRequested             += KeyboardHandler_FindRequested;
            keyboardHandler.HomeNavigationRequested   += HomeNavigationRequested;
            keyboardHandler.ReloadRequested           += ReloadRequested;
            keyboardHandler.ZoomInRequested           += ZoomInRequested;
            keyboardHandler.ZoomOutRequested          += ZoomOutRequested;
            keyboardHandler.ZoomResetRequested        += ZoomResetRequested;
            lifeSpanHandler.PopupRequested            += LifeSpanHandler_PopupRequested;
            resourceHandler.SessionIdentifierDetected += (id) => SessionIdentifierDetected?.Invoke(id);
            requestHandler.QuitUrlVisited             += RequestHandler_QuitUrlVisited;
            requestHandler.RequestBlocked             += RequestHandler_RequestBlocked;

            InitializeRequestFilter(requestFilter);

            control = new BrowserControl(
                contextMenuHandler,
                dialogHandler,
                displayHandler,
                downloadHandler,
                keyboardHandler,
                lifeSpanHandler,
                requestHandler,
                startUrl);
            control.AddressChanged      += Control_AddressChanged;
            control.LoadFailed          += Control_LoadFailed;
            control.LoadingStateChanged += Control_LoadingStateChanged;
            control.TitleChanged        += Control_TitleChanged;

            control.Initialize();
            logger.Debug("Initialized browser control.");
        }
コード例 #26
0
        private IEnumerator RequestAsync(string action,
                                         string method,
                                         Action <UnityWebRequest> requestAction,
                                         Action <ErrorLevel, string> errorAction,
                                         DownloadHandler downloadHandler,
                                         UploadHandler uploadHandler,
                                         string contentType,
                                         bool needAuthorize,
                                         bool saveCookie)
        {
            var url = string.Format("http://{0}:{1}/", NetworkConfiguration.Current.ip, NetworkConfiguration.Current.port);

            yield return(RequestAsyncFromUrl(url, method, requestAction, errorAction, downloadHandler, uploadHandler, contentType, needAuthorize, saveCookie));
        }
コード例 #27
0
 public AssetBundle GetAssetBundle()
 {
     if (m_AssetBundle == null && m_downloadHandler != null)
     {
         //m_AssetBundle = m_downloadHandler.assetBundle;
         byte[] newBuffer = new byte[m_downloadHandler.data.Length - m_bundleOffset];
         System.Buffer.BlockCopy(m_downloadHandler.data, m_bundleOffset, newBuffer, 0, m_downloadHandler.data.Length - m_bundleOffset);
         m_AssetBundle = AssetBundle.LoadFromMemory(newBuffer);
         //newBuffer = null;
         m_downloadHandler.Dispose();
         m_downloadHandler = null;
     }
     return(m_AssetBundle);
 }
        public void Getting_The_Stream_Should_Lock_File()
        {
            string resourceId = SourceFile.FullName.ToLowerInvariant();

            var state = LockRepository.GetLockState(resourceId);

            Assert.AreEqual(ResourceLockState.Unlocked, state);

            using (Stream stream = DownloadHandler.ReadFile(resourceId))
            {
                state = LockRepository.GetLockState(resourceId);
                Assert.AreEqual(ResourceLockState.ReadOnly, state);
            }
        }
コード例 #29
0
        /// <summary>
        /// Tests FTP access to all test servers in the database.
        /// </summary>
        /// <returns></returns>
        public async Task <Dictionary <Server, bool> > TestFtpAccess()
        {
            var servers = DatabaseUtil.GetAllTestServers();
            var results = new Dictionary <Server, bool>();

            foreach (var server in servers)
            {
                var result = await DownloadHandler.TestFtpAccess(server);

                results.Add(server, result);
            }

            return(results);
        }
コード例 #30
0
 /// <summary>
 /// Unloads all resources associated with this asset bundle.
 /// </summary>
 public void Unload()
 {
     if (m_AssetBundle != null)
     {
         m_AssetBundle.Unload(true);
         m_AssetBundle = null;
     }
     if (m_downloadHandler != null)
     {
         m_downloadHandler.Dispose();
         m_downloadHandler = null;
     }
     m_RequestOperation = null;
 }
コード例 #31
0
ファイル: Form1.cs プロジェクト: miguelpunzal/myToolbox
        private async void button5_ClickAsync(object sender, EventArgs e)
        {
            try
            {
                origvalue_1 = txt_csvurl.Text;
                origvalue_2 = queryUrl.Text;

                DownloadHandler downer = new DownloadHandler(this);
                browser.DownloadHandler        = downer;
                downer.OnBeforeDownloadFired  += OnBeforeDownloadFired;
                downer.OnDownloadUpdatedFired += OnDownloadUpdatedFired;


                //timer1.Enabled = false;
                //timer2.Enabled = false;
                //timer3.Enabled = false;

                string x = await browser.GetSourceAsync();

                string   date         = getBetween(x, textBox5.Text, textBox6.Text);
                string   replacedDate = date.Replace(" - ", ";");
                string   sprint       = getBetween(x, textBox7.Text, textBox8.Text);
                string[] twoDates     = replacedDate.Split(';');

                DateTime date1 = DateTime.Parse(twoDates[0]);
                DateTime date2 = DateTime.Parse(twoDates[1]).AddDays(1);

                String formattedDate1 = date1.ToString("yyyy-MM-dd");
                String formattedDate2 = date2.ToString("yyyy-MM-dd");

                queryUrl.Text = queryUrl.Text.Replace("^^^^^^", formattedDate1);
                queryUrl.Text = queryUrl.Text.Replace("######", formattedDate2);
                queryUrl.Text = queryUrl.Text.Replace("!!!!!!", sprint);

                txt_csvurl.Text += queryUrl.Text;
                //  MessageBox.Show(txt_csvurl.Text);
                oldurl = browser.Address;
                //  browser.Load(txt_csvurl.Text);
                //browser.Reload();

                // dlUrl = txt_csvurl.Text;
                browser.Load(txt_csvurl.Text);

                txt_csvurl.Text = origvalue_1;
                queryUrl.Text   = origvalue_2;
                FillDataGrids();
            }
            catch (Exception ex) {
            }
        }
コード例 #32
0
        public static UnityWebRequest PostRequest(string uri, string postData, DownloadHandler downloader)
        {
            //string to byte[]
            byte[] data = null;
            if (!string.IsNullOrEmpty(postData))
            {
                //
                data = System.Text.Encoding.UTF8.GetBytes(postData);
            }

            UnityWebRequest request = UWebRequestCreator.PostRequest(uri, data, downloader);

            return(request);
        }
コード例 #33
0
        protected override void CleanupInternal()
        {
            if (Token != null)
            {
                if (DownloadHandler.GetTransferStatus(Token.TransferId) != TransferStatus.UnknownTransfer)
                {
                    DownloadHandler.CancelTransfer(Token.TransferId, AbortReason.Undefined);
                }
            }

            SystemTime.Reset();
            ParentDirectory.Delete(true);

            base.CleanupInternal();
        }
        public void Number_Of_Available_Blocks_Should_Match_Token()
        {
            long blockNumber = 0;

            for (int i = 0; i < Token.TotalBlockCount; i++)
            {
                BufferedDataBlock block = DownloadHandler.ReadBlock(Token.TransferId, blockNumber++);

                //the receive method checks offsets and block numbers
                base.ReceiveBlock(block);
            }

            //make sure we got all the data
            CollectionAssert.AreEqual(SourceFileContents, ReceivingBuffer);
        }
コード例 #35
0
 /// <summary>
 /// Download
 /// </summary>
 /// <param name="downloadHandler">download handler delegate</param>
 /// <param name="taskName">task name</param>
 /// <param name="progress">progress</param>
 /// <returns>true, if successful</returns>
 private bool Download(DownloadHandler downloadHandler, string taskName, int progress)
 {
     return Download(downloadHandler, taskName, progress, true);
 }
コード例 #36
0
 /// <summary>
 /// Download
 /// </summary>
 /// <param name="downloadHandler">download handler delegate</param>
 /// <param name="taskName">task name</param>
 /// <param name="progress">progress</param>
 /// <param name="shouldDownload">should download?</param>
 /// <returns>true, if successful</returns>
 private bool Download(DownloadHandler downloadHandler, string taskName, int progress, bool shouldDownload)
 {
     if (shouldDownload)
     {
         Invoke(new UpdateProgressHandler(UpdateProgress), Status.Downloading, taskName, progress);
         if (downloadHandler.Invoke())
         {
             Log.Info("SyncView.Download", "Task {0} Successful", taskName);
             return true;
         }
         Log.Info("SyncView.Download", "Task {0} Failed", taskName);
         return false;
     }
     return true;
 }
コード例 #37
0
ファイル: Request.cs プロジェクト: BenDol/RocketLauncher
 public void kill()
 {
     dead = true;
     serverXML = null;
     callback = null;
     url = null;
     director = null;
     directorUrl = null;
     dlHandler = null;
     lastVersion = 0;
 }
コード例 #38
0
ファイル: Launcher.cs プロジェクト: 123marvin123/PawnPlus
        private void DownloadPawnFiles()
        {
            try
            {
                this.backgroundWorker.ReportProgress(10, Localization.Text_CheckingFiles);
                Thread.Sleep(100);

                string JSONString = string.Empty;

                using (WebClient webClient = new WebClient())
                {
                    JSONString = webClient.DownloadString("https://raw.githubusercontent.com/WopsS/PawnPlus/master/Information.json");
                }

                InformationJSON applicationJSON = JsonConvert.DeserializeObject<InformationJSON>(JSONString);

                FileInfo fileInfo = null;

                string TemporaryFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                string SAMPZIPPath = Path.Combine(TemporaryFolder, applicationJSON.SAMPZIPName), CompilerZIPPath = Path.Combine(TemporaryFolder, applicationJSON.CompilerZIPName);

                Directory.CreateDirectory(TemporaryFolder);

                DownloadHandler downloadHandler = new DownloadHandler(new Tuple<Uri, string>[]
                {
                    Tuple.Create(new Uri(applicationJSON.SAMPFilesLink + "/" + applicationJSON.SAMPZIPName), SAMPZIPPath),
                    Tuple.Create(new Uri(applicationJSON.CompilerLink + "/" + applicationJSON.CompilerZIPName), CompilerZIPPath),
                });

                downloadHandler.ProgressChanged += this.DownloadHandler_DownloadProgressChanged;
                downloadHandler.FileCompleted += this.DownloadHandler_DownloadProgressComplete;

                this.backgroundWorker.ReportProgress(15, Localization.Text_ServerFilesDownloading);
                Thread.Sleep(500);

                this.Invoke(new MethodInvoker(delegate
                {
                    this.downloadControl = new DownloadControl();

                    this.Height = 190;
                    this.controlsPanel.Controls.Clear();
                    this.controlsPanel.Controls.Add(this.downloadControl);
                }));

                downloadHandler.Start(); // Download SA-MP files.
                fileInfo = new FileInfo(SAMPZIPPath);

                if (File.Exists(SAMPZIPPath) == true && fileInfo.Length > 0)
                {
                    this.backgroundWorker.ReportProgress(15, Localization.Text_ServerFilesUnpacking);
                    Thread.Sleep(1000);

                    ZipArchive Archive = ZipArchive.Open(SAMPZIPPath);

                    foreach (ZipArchiveEntry archiveEntry in Archive.Entries)
                    {
                        if (archiveEntry.IsDirectory == false)
                        {
                            archiveEntry.WriteToDirectory(TemporaryFolder, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                        }
                    }

                    Archive.Dispose();

                    this.backgroundWorker.ReportProgress(15, Localization.Text_ServerFilesCopying);
                    Thread.Sleep(1000);

                    // Let's copy server includes.
                    string[] Files = Directory.GetFiles(Path.Combine(TemporaryFolder, "pawno", "include"));

                    foreach (string CurrentFile in Files)
                    {
                        File.Copy(CurrentFile, Path.Combine(ApplicationData.IncludesDirectory, Path.GetFileName(CurrentFile)), true);
                    }

                    this.backgroundWorker.ReportProgress(15, Localization.Text_ServerFilesCopied);
                    Thread.Sleep(1000);
                }
                else
                {
                    this.backgroundWorker.ReportProgress(15, Localization.Text_ServerFilesError);
                    Thread.Sleep(2000);
                }

                this.backgroundWorker.ReportProgress(15, Localization.Text_CompilerFilesDownloading);
                Thread.Sleep(500);

                this.Invoke(new MethodInvoker(delegate
                {
                    this.downloadControl = new DownloadControl();

                    this.Height = 190;
                    this.controlsPanel.Controls.Clear();
                    this.controlsPanel.Controls.Add(this.downloadControl);
                }));

                downloadHandler.Start(); // Download ZEEX compiler files.
                fileInfo = new FileInfo(CompilerZIPPath);

                if (File.Exists(CompilerZIPPath) == true && fileInfo.Length > 0)
                {
                    this.backgroundWorker.ReportProgress(15, Localization.Text_CompilerFilesUnpacking);
                    Thread.Sleep(1000);

                    ZipArchive Archive = ZipArchive.Open(CompilerZIPPath);

                    foreach (ZipArchiveEntry archiveEntry in Archive.Entries)
                    {
                        if (archiveEntry.IsDirectory == false)
                        {
                            archiveEntry.WriteToDirectory(TemporaryFolder, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                        }
                    }

                    Archive.Dispose();

                    this.backgroundWorker.ReportProgress(15, Localization.Text_CompilerFilesCopying);
                    Thread.Sleep(1000);

                    // Let's copy PAWN files.
                    File.Copy(Path.Combine(TemporaryFolder, CompilerZIPPath.Remove(CompilerZIPPath.Length - 4), "bin", "pawnc.dll"), Path.Combine(ApplicationData.PawnDirectory, Path.GetFileName("pawnc.dll")), true);
                    File.Copy(Path.Combine(TemporaryFolder, CompilerZIPPath.Remove(CompilerZIPPath.Length - 4), "bin", "pawncc.exe"), Path.Combine(ApplicationData.PawnDirectory, Path.GetFileName("pawncc.exe")), true);

                    this.backgroundWorker.ReportProgress(15, Localization.Text_CompilerFilesCopied);
                    Thread.Sleep(1000);
                }
                else
                {
                    this.backgroundWorker.ReportProgress(15, Localization.Text_CompilerFilesError);
                    Thread.Sleep(2000);
                }

                // Let's delete the temporary folder, we don't need it from now.
                Directory.Delete(TemporaryFolder, true);

                downloadHandler.Dispose();

                Thread.Sleep(50);
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandledException(ex);
            }
        }
コード例 #39
0
 /// <summary>
 /// 开始下载。
 /// </summary>
 /// <param name="resp"></param>
 /// <param name="fileName"></param>
 /// <param name="handler"></param>
 protected void StartDownload(HttpResponse resp, string fileName, DownloadHandler handler)
 {
     if (resp != null && handler != null)
     {
         resp.Clear();
         resp.Buffer = true;
         resp.Charset = "gb2312";
         resp.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
         resp.ContentEncoding = Encoding.GetEncoding("gb2312");//设置输出流为简体中文
         resp.ContentType = this.contentType;
         // output.Save(resp.OutputStream);
         handler(resp.OutputStream);
         resp.Flush();
         resp.End();
     }
 }