Ejemplo n.º 1
0
        public DAL(IsolatedStorageOfflineContext context
            , String appName
            , String language
            , String userName
            , String userPassword
            , String configName
            , String configVersion
            , IDictionary<string, string> deviceInfo
            , ProgressDelegate p
            , Func<Uri, CacheControllerBehavior, AsyncWorkerManager, CacheRequestHandler> chacheRequestFactory)
        {
            this.appName = appName;
            this.language = language;
            this.configName = configName;
            this.configVersion = configVersion;
            this.onProgress = p;

            this.context = context;
            this.context.LoadCompleted += context_LoadCompleted;
            this.context.CacheController.SetCacheRequestFactory(chacheRequestFactory);
            this.context.CacheController.RefreshCompleted += CacheController_RefreshCompleted;
            this.context.CacheController.ControllerBehavior.Credentials = new System.Net.NetworkCredential(userName, userPassword);
            this.context.CacheController.ControllerBehavior.ConfigName = this.configName;
            this.context.CacheController.ControllerBehavior.ConfigVersion = this.configVersion;
            this.context.CacheController.ControllerBehavior.CoreVersion = CoreInformation.CoreVersion;
            this.context.CacheController.ControllerBehavior.ReadProgressCallback = ReadProgressCallback;
            this.context.CacheController.ControllerBehavior.DeviceInfo = deviceInfo;

            //this.context.CacheController.ControllerBehavior.AddScopeParameters("Outlet","{A507956F-D135-4E8A-BD7F-14B54AC1E95C}");
        }
Ejemplo n.º 2
0
 public static RSSFile Download(string url, ProgressDelegate listener, ICancellable cancelObject)
 {
     try
     {
         Logger.Log("Downloading RSS file from {0}", url);
         var request = HttpWebRequest.Create(url);
         request.Timeout = 15000;
         using (var response = request.GetResponse())
         {
             using (var stream = new ProgressStream(response.GetResponseStream(), response.ContentLength, listener, cancelObject))
             {
                 try
                 {
                     return(new RSSFile(stream));
                 }
                 finally
                 {
                     stream.Close();
                 }
             }
         }
     }
     catch (Exception e)
     {
         Logger.Log("Caught exception: {0}", e.ToString());
         return(null);
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Build tile system and apply stripping rules.
        /// </summary>
        /// <param name="system">Tile system.</param>
        /// <param name="progressHandler">Progress handler delegate.</param>
        /// <returns>Tile system builder that was used to build tile system.</returns>
        private static TileSystemBuilder BuildTileSystemHelper(TileSystem system, ProgressDelegate progressHandler = null)
        {
            var builder = new TileSystemBuilder(progressHandler);

            BuildTileSystemHelper(builder, system);
            return(builder);
        }
Ejemplo n.º 4
0
        ProgressDelegate getAndRemoveCallbackFromRegister(HttpRequestMessage request)
        {
            ProgressDelegate emptyDelegate = delegate { };

            lock (registeredProgressCallbacks) {
                if (!registeredProgressCallbacks.ContainsKey(request))
                {
                    return(emptyDelegate);
                }

                var weakRef = registeredProgressCallbacks[request];
                if (weakRef == null)
                {
                    return(emptyDelegate);
                }

                var callback = weakRef.Target as ProgressDelegate;
                if (callback == null)
                {
                    return(emptyDelegate);
                }

                registeredProgressCallbacks.Remove(request);
                return(callback);
            }
        }
 private void init(ProgressStream stream)
 {
     stream.ReadCallback = readBytes;
     Progress            = delegate
     {
     };
 }
Ejemplo n.º 6
0
 /// <summary>
 /// This will simulate the mod installation and decide installation choices and files final paths.
 /// </summary>
 /// <param name="modArchiveFileList">The list of files inside the mod archive.</param>
 /// <param name="stopPatterns">patterns matching files or directories that should be at the top of the directory structure.</param>
 /// <param name="pluginPath">skip as the first path component in installer destinations</param>
 /// <param name="destinationPath">The file install destination folder.</param>
 /// <param name="progressDelegate">A delegate to provide progress feedback.</param>
 /// <param name="coreDelegate">A delegate for all the interactions with the js core.</param>
 public abstract Task <Dictionary <string, object> > Install(List <string> modArchiveFileList,
                                                             List <string> stopPatterns,
                                                             string pluginPath,
                                                             string destinationPath,
                                                             dynamic preset,
                                                             ProgressDelegate progressDelegate,
                                                             CoreDelegates coreDelegate);
Ejemplo n.º 7
0
        private void Initialize(DirectoryInfo directory, uint level, ProgressDelegate Progress)
        {
            FileSystemInfo[] children = directory.GetFileSystemInfos();

            if (children != null)
            {
                Progress?.Invoke(this, new ProgressEventArgs(0, children.Length));
                int childNumberLength = children.Length.ToString().Length;
                for (int i = 0; i < children.Length; i++)
                {
                    IsoFolderElement child;
                    string           childNumber = string.Format("{0:D" + childNumberLength.ToString() + "}", i);
                    if (children[i].GetType() == typeof(DirectoryInfo))
                    {
                        child = new IsoDirectory(this, (DirectoryInfo)children[i], level + 1, childNumber);
                    }
                    else
                    {
                        child = new IsoFile((FileInfo)children[i], childNumber);
                    }

                    Children.Add(child);

                    Progress?.Invoke(this, new ProgressEventArgs(i));
                }
            }
            Children.Sort();

            CalculateSize();
        }
Ejemplo n.º 8
0
        /**
         * 上传文件
         */
        protected string uploadFiles(Object upauth, ArrayList filelist, ProgressDelegate progress = null)
        {
            string upresults = "[";

            Dictionary <Object, Object> dt = (Dictionary <Object, Object>)upauth;

            object nsp_host, nsp_tstr, secret, nsp_tapp;

            if (dt.TryGetValue((object)"nsp_host", out nsp_host) == false ||
                dt.TryGetValue((object)"nsp_tstr", out nsp_tstr) == false ||
                dt.TryGetValue((object)"secret", out secret) == false ||
                dt.TryGetValue((object)"nsp_tapp", out nsp_tapp) == false)
            {
                throw new Exception("上传鉴权出错");
            }

            foreach (Object filename in filelist)
            {
                string uploadresult = null;
                string mksinglefile = null;
                try
                {
                    uploadresult = uploadFile(nsp_tapp.ToString(), secret.ToString(), nsp_host.ToString(), nsp_tstr.ToString(), filename.ToString(), progress);
                    mksinglefile = mkfilestr(uploadresult);
                }
                catch (Exception err) {
                    NSPLog.log(LogMsgType.NSP_LOG_ERR, err.Message);
                    throw err;
                }
                upresults += mksinglefile + ",";
            }
            upresults = upresults.Substring(0, upresults.Length - 1) + "]";

            return(upresults);
        }
 public static void UpdateProgresssBar(double progress, ProgressDelegate progressDelegate)
 {
     if (progressDelegate != null)
     {
         progressDelegate.Invoke(progress);
     }
 }
        public virtual async Task <IRestApiResult <TResult> > PostAsync <TContent, TResult>(
            Priority priority,
            string path,
            TContent content = default(TContent),
            ProgressDelegate progressDelegate = null,
            IList <KeyValuePair <string, string> > headers = null,
            IHttpContentResolver httpContentResolver       = null,
            IHttpResponseResolver httpResponseResolver     = null,
            CancellationToken cancellationToken            = default(CancellationToken))
        {
            var httpContent = ResolveHttpContent(content);
            var stream      = await httpContent.ReadAsStreamAsync();

            var progressContent = new ProgressStreamContent(httpContent.Headers, stream, cancellationToken)
            {
                Progress = progressDelegate
            };

            var httpRequestMessage = new HttpRequestMessage(new HttpMethod("POST"), path)
            {
                Content = progressContent
            };

            return(await SendAsync <TResult>(priority, httpRequestMessage, headers, httpResponseResolver, cancellationToken));
        }
Ejemplo n.º 11
0
        public DAL(IsolatedStorageOfflineContext context
                   , String appName
                   , String language
                   , String userName
                   , String userPassword
                   , String configName
                   , String configVersion
                   , IDictionary <string, string> deviceInfo
                   , ProgressDelegate p
                   , Func <Uri, CacheControllerBehavior, AsyncWorkerManager, CacheRequestHandler> chacheRequestFactory)
        {
            this.appName       = appName;
            this.language      = language;
            this.configName    = configName;
            this.configVersion = configVersion;
            this.onProgress    = p;

            this.context = context;
            this.context.LoadCompleted += context_LoadCompleted;
            this.context.CacheController.SetCacheRequestFactory(chacheRequestFactory);
            this.context.CacheController.RefreshCompleted += CacheController_RefreshCompleted;
            this.context.CacheController.ControllerBehavior.Credentials          = new System.Net.NetworkCredential(userName, userPassword);
            this.context.CacheController.ControllerBehavior.ConfigName           = this.configName;
            this.context.CacheController.ControllerBehavior.ConfigVersion        = this.configVersion;
            this.context.CacheController.ControllerBehavior.CoreVersion          = CoreInformation.CoreVersion;
            this.context.CacheController.ControllerBehavior.ReadProgressCallback = ReadProgressCallback;
            this.context.CacheController.ControllerBehavior.DeviceInfo           = deviceInfo;

            //this.context.CacheController.ControllerBehavior.AddScopeParameters("Outlet","{A507956F-D135-4E8A-BD7F-14B54AC1E95C}");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// For ROOT Only !!
        /// </summary>
        public IsoDirectory(TreeNode directory, UInt32 level, string childNumber, ProgressDelegate Progress)
            : base(directory, true, childNumber)
        {
            Parent = this;

            Initialize(directory, level, Progress);
        }
Ejemplo n.º 13
0
        private void Initialize(DirectoryInfo directory, UInt32 level, ProgressDelegate Progress)
        {
            Level = level;

            FileSystemInfo[] children = directory.GetFileSystemInfos();

            if (children != null)
            {
                Progress?.Invoke(this, new ProgressEventArgs(0, children.Length));

                int childNumberLength = children.Length.ToString().Length;
                for (int i = 0; i < children.Length; i++)
                {
                    string childNumber = String.Format("{0:D" + childNumberLength.ToString() + "}", i);

                    Children.Add(children[i] is DirectoryInfo ? (IsoFolderElement)
                                 new IsoDirectory(this, (DirectoryInfo)children[i], level + 1, childNumber) :
                                 new IsoFile((FileInfo)children[i], childNumber));

                    Progress?.Invoke(this, new ProgressEventArgs(i));
                }
            }

            Children.Sort();

            CalculateSize();
        }
Ejemplo n.º 14
0
 public static void UpdateProgresssBar(double progress, ProgressDelegate progressDelegate)
 {
     if (progressDelegate != null)
     {
         progressDelegate.Invoke(progress);
     }
 }
Ejemplo n.º 15
0
        public async Task <Dictionary <string, object> > ApplyPatch(JObject data,
                                                                    ProgressDelegate progress,
                                                                    CoreDelegates core)
        {
            Dictionary <string, object> res = await IsPatchApplicable(data, core);

            if (res ["Result"].ToString() == "False")
            {
                return(res);
            }

            res = await ReflectionPatch.Instance.ApplyPatch(data, progress, core);

            if (res ["Result"].ToString() == "False")
            {
                return(res);
            }

            if (await core.context.IsDeploymentRequired())
            {
                res = await DeployFiles(core);

                if (res ["Result"].ToString() == "False")
                {
                    return(res);
                }
            }

            return(await Injector.Instance.ApplyPatch(data, progress, core));
        }
Ejemplo n.º 16
0
        public static void CompressDirectory(string _inputDirectory, string _zippedFileName, ProgressDelegate _progress)
        {
            DirectoryInfo	_inputDirectoryInfo		= new DirectoryInfo(_inputDirectory);
            Uri 			_inputDirectoryURI		= new Uri(_inputDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);

            using (FileStream _zippedFileStream 	= new FileStream(_zippedFileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (GZipStream _zipStream 		= new GZipStream(_zippedFileStream, CompressionMode.Compress))
                {
                    // Iterate through each file to get relative path to the file and compress that file
                    foreach (FileInfo _file in _inputDirectoryInfo.GetFiles("*.*", SearchOption.AllDirectories))
                    {
                        string	_curFilePath			= _file.FullName;

                        if (Path.GetExtension(_curFilePath) == ".meta")
                            continue;

                        string 	_curFileRelativePath 	= _inputDirectoryURI.MakeRelativePath(_curFilePath);

                        if (_progress != null)
                            _progress("[Zip] Compressing file: " + _curFileRelativePath);

                        CompressFile(_inputDirectory, _curFileRelativePath, _zipStream);
                    }
                }
            }
        }
        /// <summary>
        /// Выполняет операцию в фоновом потоке, не блокируя UI элементы формы. Может быть вызван сколько угодно раз подряд
        /// </summary>
        /// <param name="args">Начальные аргументы для потока</param>
        /// <param name="action">Метод, выполняемый в фоновом потоке</param>
        /// <param name="progress">Метод, выполняемый в фоновом потоке, позволяющий откликаться в основной поток</param>
        /// <param name="completed">Метод, выполняемый после окончания фонового потока</param>
        /// <param name="cancellationToken">Токен для воркеров с возможностью остановки</param>
        public static void RunAsync(object args, DoWorkDelegate action, ProgressDelegate progress, CompletedDelegate completed, CancellationTokenSource cancellationToken = null)
        {
            Worker w = new Worker(args, action, completed, progress, progress != null, cancellationToken);

            w.Complited += new EventHandler(w_Complited);
            Count++;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// This will assign all files to the proper destination.
        /// </summary>
        /// <param name="fileList">The list of files inside the mod archive.</param>
        /// <param name="stopPatterns">patterns matching files or directories that should be at the top of the directory structure.</param>
        /// <param name="progressDelegate">A delegate to provide progress feedback.</param>
        /// <param name="coreDelegate">A delegate for all the interactions with the js core.</param>
        protected async Task <List <Instruction> > BasicModInstall(List <string> fileList,
                                                                   List <string> stopPatterns,
                                                                   ProgressDelegate progressDelegate,
                                                                   CoreDelegates coreDelegate)
        {
            List <Instruction> FilesToInstall = new List <Instruction>();
            string             prefix         = ArchiveStructure.FindPathPrefix(fileList, stopPatterns);

            await Task.Run(() =>
            {
                foreach (string ArchiveFile in fileList)
                {
                    if (ArchiveFile.EndsWith("" + Path.DirectorySeparatorChar))
                    {
                        // don't include directories, only files
                        continue;
                    }
                    string destination;
                    if (ArchiveFile.StartsWith(prefix))
                    {
                        destination = ArchiveFile.Substring(prefix.Length);
                    }
                    else
                    {
                        destination = ArchiveFile;
                    }
                    FilesToInstall.Add(Instruction.CreateCopy(ArchiveFile, destination));
                    // Progress should increase.
                }
            });

            return(FilesToInstall);
        }
Ejemplo n.º 19
0
        // For ROOT !!
        public IsoDirectory(DirectoryInfo directory, uint level, string childNumber, ProgressDelegate Progress)
            : base(directory, true, childNumber)
        {
            Parent = this;

            Initialize(directory, level, Progress);
        }
Ejemplo n.º 20
0
 public static RSSFile Download(string url, ProgressDelegate listener, ICancellable cancelObject)
 {
     try
     {
         var request = HttpWebRequest.Create(url);
         request.Timeout = 15000;
         using (var response = request.GetResponse())
         {
             using (var stream = new ProgressStream(response.GetResponseStream(), response.ContentLength, listener, cancelObject))
             {
                 try
                 {
                     return(new RSSFile(stream));
                 }
                 finally
                 {
                     stream.Close();
                 }
             }
         }
     }
     catch (IOException)
     {
         return(null);
     }
     catch (WebException)
     {
         return(null);
     }
 }
Ejemplo n.º 21
0
        public static async Task <TResult> PostAsync <TContent, TResult>(this WebApiClient webApiClient,
                                                                         Priority priority, string path, TContent content = default(TContent),
                                                                         ProgressDelegate progressDelegate = null, IHttpContentResolver contentResolver = null)
        {
            var httpClient = webApiClient.GetWebApiClient(priority);

            webApiClient.SetHttpRequestHeaders(httpClient);

            var httpContent = webApiClient.ResolveHttpContent(content);

            var stream = await httpContent.ReadAsStreamAsync();

            var progressContent = new ProgressStreamContent(httpContent.Headers, stream, CancellationToken.None);

            progressContent.Progress = progressDelegate;

            var response = await httpClient
                           .PostAsync(path, progressContent)
                           .ConfigureAwait(false);

            if (!await response.EnsureSuccessStatusCodeAsync())
            {
                return(default(TResult));
            }

            return(await webApiClient.HttpResponseResolver.ResolveHttpResponseAsync <TResult>(response));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Perfroms a two dimensional isotropic wavelet transformation for an array. The result is copied back to the declared array.
        /// </summary>
        /// <exception cref="ArgumentException"></exception>
        virtual public void BacktransformIsotropic2D(float[,] src, ProgressDelegate progressDelegate = null)
        {
            lock (threadSync) {
                checkArrayArgument(src, "src");
                //Calculate the integral digits of log to the base two of the maximum of "width" and "height"
                //The resulting number of "width | height" cannot have a greater log to the base 2 (integral digits)
                //than the greater of both values.
                int log2 = 1;
                int test = 1;
                while (test < (width | height))
                {
                    test <<= 1;
                    log2++;
                }
                float[,] tmp = getTempArray();
                int i = 1;
                initProgress(progressDelegate);
                while ((i <= log2) && (!updateProgress(0)))
                {
                    //Shift always rounds down (towards negative infinity)
                    //However, for odd lengths we have one more low-pass value than
                    //high-pass values. By shifting the negative value and negating the result
                    //we get the desired result.
                    int w = -(-width >> (log2 - i));
                    int h = -(-height >> (log2 - i));

                    if ((w >= minSize) && (h >= minSize))
                    {
                        InvTransformCols(src, tmp, w, h);
                        InvTransformRows(tmp, src, w, h);
                    }
                    i++;
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Updates the progress value of the current task by the declared increment and
        /// calls a callback to notify the caller about the progress and give
        /// the possiblily to abort the current task.
        /// </summary>
        /// <param name="progressDelegate">a delegate to notify the caller about the progress and to give
        /// the possiblity to abort the current task. Can be set to null if notification is not required</param>
        /// <param name="maxValue">The maximal progress value (to calculate progress percentage). Can be set to 0 if used with TransformIsotropic2D() or BacktransformIsotropic2D() </param>
        private void initProgress(ProgressDelegate progressDelegate, long maxValue = 0)
        {
            if (progressDelegate != null)
            {
                this.progressSync = new object();
            }
            else
            {
                this.progressSync = null;
            }
            int w = width, h = height;

            this.progressMax = maxValue;
            //Calculate the exact maximal value for the progress value if not declared (used by TransformIsotropic2D() and BacktransformIsotropic2D())
            if (this.progressMax == 0)
            {
                while ((w >= minSize) && (h >= minSize))
                {
                    this.progressMax += 2 * w * h;
                    w = -(-w >> 1);
                    h = -(-h >> 1);
                }
            }
            this.progressDelegate = progressDelegate;
            this.progressValue    = 0;
            this.progressAbort    = false;
        }
Ejemplo n.º 24
0
		public void Write( BinaryWriter writer, ProgressDelegate Progress ) {
			if ( m_extent > 0 && m_size > 0 ) {
				
				FileStream source = new FileStream( m_fullPath, FileMode.Open, FileAccess.Read );
				BinaryReader reader = new BinaryReader( source );

				// The write buffer is 1MB long. I haven't given too much study into this particular field, so 
				// feel free to change according two whatever writing speed is optimal.
				int bucket = (int)IsoAlgorithm.SectorSize*512; // 1 MB
				byte[] buffer = new byte[bucket];
				while ( true ) {
					int bytesRead = reader.Read( buffer, 0, bucket );

					if ( bytesRead == 0 ) {
						break;
					}

					if ( bytesRead == bucket ) {
						writer.Write( buffer );
					} else {
						writer.Write( buffer, 0, bytesRead );
						if ( bytesRead%IsoAlgorithm.SectorSize != 0 ) {
							writer.Write( new byte[IsoAlgorithm.SectorSize-( bytesRead%IsoAlgorithm.SectorSize )] );
						}
						break;
					}

					Progress( this, new ProgressEventArgs( (int)( writer.BaseStream.Length/IsoAlgorithm.SectorSize ) ) );
				}

				reader.Close();
				source.Close();
			}
		}
Ejemplo n.º 25
0
        public ConcurrentBag <List <Candle> > GetHistoryFromFile(ProgressDelegate progress, int period, DateTime fromDate, DateTime toDate)
        {
            IHistory h;
            int      num;
            Dictionary <string, string>    source           = ZerodhaOperations.LoadInstruments();
            ConcurrentBag <List <Candle> > resultCollection = new ConcurrentBag <List <Candle> >();
            int num2 = period;

            if (num2 > 10)
            {
                if (num2 == 15)
                {
                    h = new TradeHistory15();
                    goto TR_0000;
                }
                else if (num2 == 30)
                {
                    h = new TradeHistory30();
                    goto TR_0000;
                }
                else if (num2 == 60)
                {
                    h = new TradeHistory60();
                    goto TR_0000;
                }
            }
            else if (num2 == 5)
            {
                h = new TradeHistory5();
                goto TR_0000;
            }
            else if (num2 == 10)
            {
                h = new TradeHistory10();
                goto TR_0000;
            }
            else if (num2 == 100)
            {
                h = new TradeHistoryDaily();
                goto TR_0000;
            }
            {
                h = new TradeHistoryDaily();
            }
TR_0000:
            num = Environment.ProcessorCount;
            ParallelOptions parallelOptions = new ParallelOptions();

            parallelOptions.MaxDegreeOfParallelism = num;
            Parallel.ForEach <KeyValuePair <string, string> >(source, parallelOptions, delegate(KeyValuePair <string, string> i)
            {
                resultCollection.Add(h.GetHistoryFromFile(h.folderName, i.Value, fromDate.AddDays(-30), toDate));
                if (progress != null)
                {
                    progress($"Loading Data ... {i.Value}");
                }
            });
            return(resultCollection);
        }
Ejemplo n.º 26
0
        public MainForm()
        {
            InitializeComponent();
            FormClosing += OnFormClosing;

            ProgressCallback   = progressCallback;
            UpdateNodeCallback = updateNodeCallback;
        }
Ejemplo n.º 27
0
    public SplashForm()
    {
        InitializeComponent();

        update_version_function = this.UpdateVersionInternal;
        update_information_function = this.UpdateInformationInternal;
        update_progress_function = this.UpdateProgressInternal;
    }
Ejemplo n.º 28
0
 public void SlowMethod(ProgressDelegate progressDelegate)
 {
     for (int i = 0; i < 10; i++)
     {
         Thread.Sleep(500);
         progressDelegate();
     }
 }
Ejemplo n.º 29
0
 public SplashScreen()
 {
     InitializeComponent();
     this.StartPosition = FormStartPosition.CenterScreen;
     this.progressBar1.Maximum = 100;
     del = this.UpdateProgressInternal;
     this.label4.Text = ProductVersion;
 }
Ejemplo n.º 30
0
        public static bool DecompressFile(string sDir, GZipStream zipStream, ProgressDelegate progress)
        {
            //Decompress file name
            byte[] bytes  = new byte[sizeof(int)];
            int    Readed = zipStream.Read(bytes, 0, sizeof(int));

            if (Readed < sizeof(int))
            {
                return(false);
            }

            int iNameLen = BitConverter.ToInt32(bytes, 0);

            bytes = new byte[sizeof(char)];
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < iNameLen; i++)
            {
                zipStream.Read(bytes, 0, sizeof(char));
                char c = BitConverter.ToChar(bytes, 0);
                sb.Append(c);
            }
            string sFileName = sb.ToString();

            if (progress != null)
            {
                progress(sFileName);
            }

            //Decompress file content
            bytes = new byte[sizeof(int)];
            zipStream.Read(bytes, 0, sizeof(int));
            int iFileLen = BitConverter.ToInt32(bytes, 0);

            bytes = new byte[iFileLen];
            zipStream.Read(bytes, 0, bytes.Length);

            string sFilePath = Path.Combine(sDir, sFileName);
            string sFinalDir = Path.GetDirectoryName(sFilePath);

            if (!Directory.Exists(sFinalDir))
            {
                Directory.CreateDirectory(sFinalDir);
            }
TryAgain:

            try
            {
                using (FileStream outFile = new FileStream(sFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    outFile.Write(bytes, 0, iFileLen);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                goto TryAgain;
            }
            return(true);
        }
 public Form1()
 {
     rand = new Random();
     cookieContainer = new CookieContainer();
     progressDelegate = new ProgressDelegate(updateProgress);
     listViewDelegate = new ListViewDelegate(updateListView);
     statusDelegate = new StatusDelegate(updateStatus);
     InitializeComponent();
 }
Ejemplo n.º 32
0
 public DataImportWizardP2(string file)
 {
     _excelFile = file;
     _dbManager = DBAccessManager.GetInstance();
     InitializeComponent();
     _dlgLbl = new DataDelegate(Update);
     _dlgPrg = new ProgressDelegate(UpdateProgress);
     new Thread(() => LoadData()).Start();
 }
Ejemplo n.º 33
0
        public void TestProgress()
        {
            ProgressDelegate p = null;

            p += WriteProgressToConsole;
            p += WriteProgressToFile;

            ProgressEmulator(p);
        }
        public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback)
        {
            if (callback == null && registeredProgressCallbacks.ContainsKey(request)) {
                registeredProgressCallbacks.Remove(request);
                return;
            }

            registeredProgressCallbacks[request] = new WeakReference(callback);
        }
Ejemplo n.º 35
0
 public static void UnPackFolder(string inpath, string outpath, ProgressDelegate progress)
 {
     UPKFolder.UnPackFolder(new FileChangeInfo
     {
         inpath           = inpath,
         outpath          = outpath,
         progressDelegate = progress
     });
 }
Ejemplo n.º 36
0
 public static void Compress(string inpath, string outpath, ProgressDelegate progress)
 {
     Compress(new FileChangeInfo
     {
         inpath           = inpath,
         outpath          = outpath,
         progressDelegate = progress
     });
 }
Ejemplo n.º 37
0
        public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback)
        {
            if (callback == null && registeredProgressCallbacks.ContainsKey(request)) {
                registeredProgressCallbacks.Remove(request);
                return;
            }

            registeredProgressCallbacks[request] = callback;
        }
Ejemplo n.º 38
0
        public static void DeCompress(string inpath, string outpath, ProgressDelegate progress)
        {
            FileChangeInfo info = new FileChangeInfo();

            info.inpath           = inpath;
            info.outpath          = outpath;
            info.progressDelegate = progress;
            DeCompress(info);
        }
 public static void DecompressToDirectory(string sCompressedFile, string sDir, ProgressDelegate progress)
 {
     using (FileStream inFile = new FileStream(sCompressedFile, FileMode.Open, FileAccess.Read, FileShare.None))
         using (GZipStream zipStream = new GZipStream(inFile, CompressionMode.Decompress, true))
             while (DecompressFile(sDir, zipStream, progress))
             {
                 ;
             }
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Adds the specified integers while reporting progress.
 /// </summary>
 /// <returns>The result of adding a and b.</returns>
 /// <param name="a">The integer a.</param>
 /// <param name="b">The integer b.</param>
 /// <param name="progress">The progress callback.</param>
 public static int AddWithProgress(int a, int b, ProgressDelegate progress)
 {
     progress(0.25f, "25%");
     Thread.Sleep(1000);
     progress(0.5f, "50%");
     Thread.Sleep(1000);
     progress(0.75f, "75%");
     Thread.Sleep(1000);
     return a + b;
 }
	public void PlaceTrees(ProgressDelegate progressDelegate)
	{
		if (!Validate())
			return;
		instances = new ArrayList();
		TreesPosition = new List<TreePosition>();
		//get alpha map width and height of terrain
		int alphamapWidth = terrainData.alphamapWidth;
		int alphamapHeight = terrainData.alphamapHeight;
		
		//get splat map of terrain
		splatmap = terrainData.GetAlphamaps(0,0,alphamapWidth,alphamapHeight);
		
		//dimension of splatmaps
		int xDim = splatmap.GetUpperBound(0);
		int yDim = splatmap.GetUpperBound(1);
		
		//how big is one unit in real world
		xUnit = (float)terrainData.size.x / (float)(xDim + 1);
		yUnit = (float)terrainData.size.z / (float)(yDim + 1);
		
		float percentPosition = 0.1f;
		progressDelegate("Placing trees", "Determining basic position", percentPosition);
		float calculation = 0.4f / xDim;
		for(int x = 0; x <= xDim; x ++)
		{
			for(int y = 0; y <= yDim; y ++)
			{
				foreach(TreeTextureSettings treeTexture in TreeTextures)
				{
					//this texture is not used for planting trees
					if (treeTexture.IsUsed == false)
						continue;
					
					float alphaMap = splatmap[x,y,treeTexture.Index];
					//this texture is not where we are currently in
					if (alphaMap < treeTexture.AlphamapValue)
						continue;
					
					//check distance from the nearest tree
					if (IsTreePositionClose(x, y, treeTexture.TreeDistance, treeTexture.Index))
					    continue;
					TreePosition position = new TreePosition();
					position.PosX = x;
					position.PosY = y;
					position.TreeIndex = treeTexture.DetermineTreePrototype;
					position.TextureIndex = treeTexture.Index;
					TreesPosition.Add(position);
				}
			}
			percentPosition += calculation;
			progressDelegate("Placing trees", "Determining basic position", percentPosition);
		}
		Place(progressDelegate);
	}
Ejemplo n.º 42
0
        public DownloadState Download(string url, Control ctrl, ProgressDelegate pd)
        {
            RequestState myRequestState = new RequestState();
             try
             {
            // Create a HttpWebrequest object to the desired URL.
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            // Create an instance of the RequestState and assign the previous myHttpWebRequest
            // object to its request field.
            myRequestState.downloadManager = this;
            myRequestState.request = myHttpWebRequest;
            myRequestState.ctrl = ctrl;
            myRequestState.progFormCB = new ProgressFormDelegate(Progress);
            myRequestState.progCB = new ProgressDelegate( pd );

            // Start the asynchronous request.
            IAsyncResult result = (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);

            // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);

            // Release the HttpWebResponse resource.
            //myRequestState.response.Close();
            lock (activeDownloads)
            {
               activeDownloads.Add(myRequestState);
            }

            return (DownloadState)myRequestState;
             }
             catch (WebException e)
             {
            myRequestState.error = e;
            myRequestState.progFormCB(myRequestState.progCB, myRequestState);

            /*
            Console.WriteLine("\nMain Exception raised!");
            Console.WriteLine("\nMessage:{0}", e.Message);
            Console.WriteLine("\nStatus:{0}", e.Status);
            Console.WriteLine("Press any key to continue..........");
            */
             }
             catch (Exception e)
             {
            Console.WriteLine("\nMain Exception raised!");
            Console.WriteLine("Source :{0} ", e.Source);
            Console.WriteLine("Message :{0} ", e.Message);
            Console.WriteLine("Press any key to continue..........");
            //Console.Read();
             }

             return null;
        }
        public ProgressStream( Stream innerStream, long lengthHint, ProgressDelegate listener, ICancellable cancelObject )
        {
            m_innerStream = innerStream;
            m_listener = listener;
            m_cancelObject = cancelObject;

            m_length = lengthHint;
            m_position = 0;
            m_lastProgress = -1;
            EmitProgress();
        }
Ejemplo n.º 44
0
        public static void DecompressToDirectory(string _compressedFilePath, string _targetFolder, ProgressDelegate _progress = null)
        {
            string 		_curZippedFileName		= Path.GetFileNameWithoutExtension(_compressedFilePath);
            string		_decompressToDirectory	= Path.Combine(_targetFolder, _curZippedFileName);

            using (FileStream _compressedFileStream = new FileStream(_compressedFilePath, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                using (GZipStream _zipStream = new GZipStream(_compressedFileStream, CompressionMode.Decompress, true))
                {
                    while (DecompressFile(_decompressToDirectory, _zipStream, _progress));
                }
            }
        }
Ejemplo n.º 45
0
        public SplashScreen()
        {
            InitializeComponent();
            //Application.EnableVisualStyles();
            this.textBox1.Text = "";
            this.textBox2.Text = "";
            this.textBox3.Text = "";
            this.textBox4.Text = "";
            //this.textBox5.Text = "";
            //this.progressBar1.Maximum = 100;

            deleg = this.UpdateProgressInternal;
            // this.Opacity = 0.70D;
        }
Ejemplo n.º 46
0
        static void CompressDirectory(string sInDir, string sOutFile, ProgressDelegate progress)
        {
            string[] sFiles = Directory.GetFiles(sInDir, "*.*", SearchOption.AllDirectories);
            int iDirLen = sInDir[sInDir.Length - 1] == Path.DirectorySeparatorChar ? sInDir.Length : sInDir.Length + 1;

            using (FileStream outFile = new FileStream(sOutFile, FileMode.Create, FileAccess.Write, FileShare.None))
            using (GZipStream str = new GZipStream(outFile, CompressionMode.Compress))
                foreach (string sFilePath in sFiles)
                {
                    string sRelativePath = sFilePath.Substring(iDirLen);
                    if (progress != null)
                        progress(sRelativePath);
                    CompressFile(sInDir, sRelativePath, str);
                }
        }
Ejemplo n.º 47
0
        /// <summary>
        /// writes messages about calculation status and progress
        /// </summary>
        /// <param name="KeyOfSender"></param>
        /// <param name="Percent"></param>
        /// <param name="Message"></param>
        public void Progress(string KeyOfSender, int Percent, string StatusMsg)
        {
            if (this.InvokeRequired == false)
            {
                string msg = StatusMsg;
                int perc = Percent;

                this.Text = msg + perc.ToString() + " % done!";
                calcProgressBar.Value = perc;
            }
            else
            {
                ProgressDelegate progDeleg = new ProgressDelegate(Progress);
                this.BeginInvoke(progDeleg, new object[] { KeyOfSender, Percent, StatusMsg });
            }
        }
Ejemplo n.º 48
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            // Reset all progress trackers to 0
            Reset();

            ProgressDelegate progressDelegate = null;

            if (rdoSpinBox.Checked)
                progressDelegate = new ProgressDelegate(IncrementSpinBox);
            else if (rdoProgressBar.Checked)
                progressDelegate = new ProgressDelegate(IncrementProgressBar);
            else
                progressDelegate = new ProgressDelegate(IncrementTrackBar);

            // Run the simulation!
            SlowMethod(progressDelegate);
        }
Ejemplo n.º 49
0
		public void delegateTest(){
			ProgressDelegate progress;
			Console.WriteLine("Enter 2 numbers separated with a comma:");
			string input = Console.ReadLine();
			int commaPos = input.IndexOf(',');

			double param1 = Convert.ToDouble(input.Substring(0,commaPos));
			double param2 = Convert.ToDouble(input.Substring(commaPos+1,input.Length - commaPos-1));

			Console.Write("Enter M to multiply or D to divide:");
			input = Console.ReadLine();
			if( input == "M"){
				progress = new ProgressDelegate(Multiply);
			}else{
				progress = new ProgressDelegate(Divide);
			}
			Console.WriteLine("Result: {0}",progress(param1,param2));
			Console.ReadKey();
		}
Ejemplo n.º 50
0
			public List< Tuple< File, File > >	Compare( ExtensionFilesGroup _other, ProgressDelegate _progress ) {
				int	maxFilesCount = Math.Max( m_files.Count, _other.m_files.Count );

				// First, compare file sizes
				Dictionary< long, Tuple< List< File >, List< File > > >	size2Files = new Dictionary< long, Tuple< List< File >, List< File > > >( maxFilesCount );
				foreach ( File file in m_files ) {
					if ( !size2Files.ContainsKey( file.m_size ) )
						size2Files.Add( file.m_size, new Tuple< List< File >, List< File > >( new List< File >(), new List< File >() ) );
					size2Files[file.m_size].Item1.Add( file );
				}
				foreach ( File file in _other.m_files ) {
					if ( !size2Files.ContainsKey( file.m_size ) )
						size2Files.Add( file.m_size, new Tuple< List< File >, List< File > >( new List< File >(), new List< File >() ) );
					size2Files[file.m_size].Item2.Add( file );
				}

				// Compare among files of the same size
				List< Tuple< File, File > >	result = new List< Tuple< File, File > >( maxFilesCount );

				int	sameSizeFilesProgressCount = Math.Max( 1, size2Files.Values.Count / 100 );
				int	sameSizeFilesIndex = 0;
				foreach ( Tuple< List< File >, List< File > > sameSizeFiles in size2Files.Values ) {
					if ( (++sameSizeFilesIndex % sameSizeFilesProgressCount) == 0 ) {
						// Notify of progress
						_progress( (float) sameSizeFilesIndex / size2Files.Values.Count, result.Count );
					}

					for ( int fileIndex0=0; fileIndex0 < sameSizeFiles.Item1.Count; fileIndex0++ ) {
						File	file0 = sameSizeFiles.Item1[fileIndex0];
						for ( int fileIndex1=0; fileIndex1 < sameSizeFiles.Item2.Count; fileIndex1++ ) {
							File	file1 = sameSizeFiles.Item2[fileIndex1];
							if ( file0.m_fullName == file1.m_fullName )
								continue;	// Ignore same files...

							if ( file0.CompareBinary( file1 ) ) {
								result.Add( new Tuple<File,File>( file0, file1 ) );	// Same!
							}
						}
					}
				}
				return result;
			}
Ejemplo n.º 51
0
        public static bool DecompressFile(string sDir, GZipStream zipStream, ProgressDelegate progress)
        {
            //Decompress file name
            byte[] bytes = new byte[sizeof(int)];
            int Readed = zipStream.Read(bytes, 0, sizeof(int));
            if (Readed < sizeof(int))
                return false;

            int iNameLen = BitConverter.ToInt32(bytes, 0);
            bytes = new byte[sizeof(char)];
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < iNameLen; i++)
            {
                zipStream.Read(bytes, 0, sizeof(char));
                char c = BitConverter.ToChar(bytes, 0);
                sb.Append(c);
            }
            string sFileName = sb.ToString();
            if (progress != null)
                progress(sFileName);

            //Decompress file content
            bytes = new byte[sizeof(int)];
            zipStream.Read(bytes, 0, sizeof(int));
            int iFileLen = BitConverter.ToInt32(bytes, 0);

            bytes = new byte[iFileLen];
            zipStream.Read(bytes, 0, bytes.Length);

            string sFilePath = Path.Combine(sDir, sFileName);
            string sFinalDir = Path.GetDirectoryName(sFilePath);
            if (!Directory.Exists(sFinalDir))
                Directory.CreateDirectory(sFinalDir);

            using (FileStream outFile = new FileStream(sFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
                outFile.Write(bytes, 0, iFileLen);

            return true;
        }
        public static bool InstallGame( string gameTitle, string gameVersion, ProgressDelegate listener, ICancellable cancelObject )
        {
            var downloadPath = GetDownloadPath( gameTitle, gameVersion );
            var installPath = GetInstallPath( gameTitle, gameVersion );
            if( File.Exists( downloadPath ) )
            {
                try
                {
                    using( var zipFile = new ZipFile( downloadPath ) )
                    {
                        // Delete old install
                        if( Directory.Exists( installPath ) )
                        {
                            Directory.Delete( installPath, true );
                        }
                        Directory.CreateDirectory( installPath );

                        // Extract new install
                        int totalFiles = zipFile.Entries.Count;
                        int filesInstalled = 0;
                        int lastProgress = 0;
                        listener.Invoke( 0 );
                        foreach( var entry in zipFile.Entries )
                        {
                            // Extract the file
                            var entryInstallPath = Path.Combine( installPath, entry.FileName );
                            if( entry.IsDirectory )
                            {
                                Directory.CreateDirectory( entryInstallPath );
                            }
                            else
                            {
                                Directory.CreateDirectory( Path.GetDirectoryName( entryInstallPath ) );
                                using( var file = File.OpenWrite( entryInstallPath ) )
                                {
                                    try
                                    {
                                        using( var reader = new ProgressStream( entry.OpenReader(), -1, delegate {
                                            // TODO: Emit progress during installation of large individual files?
                                        }, cancelObject ) )
                                        {
                                            try
                                            {
                                                reader.CopyTo( file );
                                                if( Program.Platform == Platform.Linux ||
                                                    Program.Platform == Platform.OSX )
                                                {
                                                    Mono.Unix.Native.Syscall.chmod(
                                                        entryInstallPath,
                                                        Mono.Unix.Native.FilePermissions.ACCESSPERMS
                                                    );
                                                }
                                            }
                                            finally
                                            {
                                                reader.Close();
                                            }
                                        }
                                    }
                                    finally
                                    {
                                        file.Close();
                                    }
                                }
                            }

                            // Check for cancellation
                            if( cancelObject.Cancelled )
                            {
                                throw new IOCancelledException();
                            }

                            // Notify the progress listener
                            filesInstalled++;
                            int progress = (filesInstalled * 100) / totalFiles;
                            if( progress != lastProgress )
                            {
                                listener.Invoke( progress );
                                lastProgress = progress;
                            }
                        }
                    }
                    return true;
                }
                catch( IOException )
                {
                    if( Directory.Exists( installPath ) )
                    {
                        Directory.Delete( installPath, true );
                    }
                    return false;
                }
                catch( ZipException )
                {
                    if( Directory.Exists( installPath ) )
                    {
                        Directory.Delete( installPath, true );
                    }
                    return false;
                }
            }
            return false;
        }
Ejemplo n.º 53
0
		private static string BuildHTMLPage(
			IServiceProvider provider,
			IList<IMsg> msgs,
			ProgressDelegate pd,
			bool processSmiles,
			Encoding encoding)
		{
			var formatter = new TextFormatter();
			var sb = new StringBuilder();
			var forum = new Forum(provider);
			forum.LoadData(msgs[0].ForumID);
			sb.AppendFormat(
				@"<tr><td class='s' colspan='2' align='center'>{0}&nbsp;<font size='1'>[{1}]</font></td></tr>",
				forum.Description, forum.Name);

			string messageFormat;
			using (var rd = new StreamReader(Assembly.GetExecutingAssembly().GetRequiredResourceStream(_messageFormatResource)))
				messageFormat = rd.ReadToEnd();

			var i = 0;
			foreach (var msg in msgs)
			{
				var formattedRating = msg.GetFormattedRating();

				sb.AppendFormat(
					messageFormat,
					msg.ID,
					msg.Subject,
					msg.ParentID,
					SR.Forum.ExportMessages.Export2ParentLink,
					msg.UserNick,
					FormatUserClass((UserClass)msg.UserClass, true),
					msg.Date,
					string.IsNullOrEmpty(formattedRating)
						? string.Empty
						: SR.TGColumnRate + " " + formattedRating,
					formatter.Format(msg.Body, processSmiles));

				i++;
				pd(i, msgs.Count);
			}

			string exportPageFormat;
			using (var rd = new StreamReader(Assembly.GetExecutingAssembly().GetRequiredResourceStream(_exportPageResource)))
				exportPageFormat = rd.ReadToEnd();

			string exportForumStyle;
			using (var rd = new StreamReader(Assembly.GetExecutingAssembly().GetRequiredResourceStream(_exportForumResource)))
				exportForumStyle = rd.ReadToEnd();

			return
				string.Format(
					exportPageFormat,
					forum.Description + " [" + forum.Name + "]",
					encoding.HeaderName,
					exportForumStyle,
					sb);
		}
Ejemplo n.º 54
0
		private static void Export2Mht(
			IServiceProvider provider,
			IList<IMsg> msgs,
			Stream fs,
			ProgressDelegate pd)
		{
			var encoding = Encoding.UTF8;
			using (var sw = new StreamWriter(fs, Encoding.Default))
			{
				sw.Write(
					_mhtHeader,
					DateTime.Now.ToString("ddd, d MMM yyyy h:m:s zz00", CultureInfo.InvariantCulture),
					encoding.HeaderName);
				sw.Flush();

				var htmlText = BuildHTMLPage(provider, msgs, pd, true, Encoding.UTF8);
				var page = encoding.GetBytes(htmlText);
				fs.Write(page, 0, page.Length);

				var usedSmileFiles =
					msgs
						.SelectMany(msg => TextFormatter.GetSmileFiles(msg.Body))
						.Distinct();

				const string prefix = @"ForumImages\";

				foreach (var smileName in usedSmileFiles)
				{
					var smileImage =
						provider
							.GetRequiredService<IStyleImageManager>()
							.GetImage(prefix + smileName, StyleImageType.ConstSize);
					var ifi = ImageFormatInfo.FromImageFormat(smileImage.RawFormat);

					sw.Write(_mhtContentImageHeader, ifi.MimeType, smileName, ifi.Extension);

					using (var ms = new MemoryStream())
					{
						smileImage.Save(ms, smileImage.RawFormat);
						sw.Write(Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.InsertLineBreaks));
					}
				}

				sw.Write(_mhtFooter);
			}
		}
Ejemplo n.º 55
0
		private static void Export2HTML(IServiceProvider provider, IList<IMsg> msgs, Stream fs, ProgressDelegate pd)
		{
			using (var sw = new StreamWriter(fs, Encoding.Default))
				sw.Write(BuildHTMLPage(provider, msgs, pd, false, Encoding.UTF8));
		}
Ejemplo n.º 56
0
		private static void Export2Text(ICollection<IMsg> msgs, Stream fs, ProgressDelegate pd)
		{
			var sb = new StringBuilder();
			var maxCharacters = Config.Instance.ForumExportConfig.CharsPerLine;

			var i = 0;
			foreach (var msg in msgs)
			{
				sb.Append(BuildTxtString("_", ' ', ' ', maxCharacters));
				sb.Append(BuildTxtString(SR.TGColumnDate
					+ ": " + msg.Date, '|', '|', maxCharacters));
				sb.Append(BuildTxtString(SR.TGColumnAuthor
					+ ": " + msg.UserNick + " " + FormatUserClass((UserClass)msg.UserClass, false), '|', '|',
					maxCharacters));
				sb.Append(BuildTxtString(SR.TGColumnSubject
					+ ": " + msg.Subject, '|', '|', maxCharacters));
				if (msg.GetFormattedRating().Length > 0)
					sb.Append(BuildTxtString(SR.TGColumnRate
						+ ": " + msg.GetFormattedRating(), '|', '|', maxCharacters));
				sb.Append(BuildTxtString("~", '|', '|', maxCharacters));
				sb.Append(
					BuildTxtString(
						(Config.Instance.ForumExportConfig.ExportRemoveTags ? RemoveTags(msg.Body) : msg.Body), '|',
						'|', maxCharacters));
				sb.Append(BuildTxtString("_", '|', '|', maxCharacters));
				sb.Append(BuildTxtString(" ", ' ', ' ', maxCharacters));

				i++;
				pd(i, msgs.Count);
			}

			var encoding = Encoding.Default;
			switch (Config.Instance.ForumExportConfig.ExportPlainTextEncoding)
			{
				case ExportPlainTextEncoding.Default:
					encoding = Encoding.Default;
					break;
				case ExportPlainTextEncoding.DOSCP866:
					encoding = Encoding.GetEncoding(866);
					break;
				case ExportPlainTextEncoding.Unicode:
					encoding = Encoding.Unicode;
					break;
				case ExportPlainTextEncoding.UTF8:
					encoding = Encoding.UTF8;
					break;
				case ExportPlainTextEncoding.WinCP1251:
					encoding = Encoding.GetEncoding(1251);
					break;
			}

			using (var sw = new StreamWriter(fs, encoding))
			{
				sw.Write(sb);
				sw.Flush();
			}
		}
        public static bool ExtractEmbeddedGame( ProgressDelegate listener, ICancellable cancelObject )
        {
            string gameTitle, gameVersion, gameURL, username, password;
            if( GetEmbeddedGameInfo( out gameTitle, out gameVersion, out gameURL, out username, out password ) && gameVersion != null )
            {
                var downloadPath = GetDownloadPath( gameTitle, gameVersion );
                try
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    var stream = assembly.GetManifestResourceStream( "EmbeddedGame." + Program.Platform + ".zip" );
                    if( stream == null )
                    {
                        stream =  assembly.GetManifestResourceStream( "EmbeddedGame.zip" );
                    }
                    if( stream != null )
                    {
                        using( stream )
                        {
                            try
                            {
                                using( var progressStream = new ProgressStream( stream, -1, listener, cancelObject ) )
                                {
                                    // Delete old download
                                    if( File.Exists( downloadPath ) )
                                    {
                                        File.Delete( downloadPath );
                                    }

                                    // Create new download
                                    try
                                    {
                                        Directory.CreateDirectory( Path.GetDirectoryName( downloadPath ) );
                                        using( var output = File.OpenWrite( downloadPath ) )
                                        {
                                            try
                                            {
                                                progressStream.CopyTo( output );
                                            }
                                            finally
                                            {
                                                output.Close();
                                            }
                                        }
                                    }
                                    finally
                                    {
                                        progressStream.Close();
                                    }
                                }
                            }
                            finally
                            {
                                stream.Close();
                            }
                        }
                        return true;
                    }
                    return false;
                }
                catch( IOException )
                {
                    if( File.Exists( downloadPath ) )
                    {
                        File.Delete( downloadPath );
                    }
                    return false;
                }
            }
            return false;
        }
Ejemplo n.º 58
0
 public void Progress(double pctComplete)
 {
     if (this.InvokeRequired)
     {
         ProgressDelegate del = new ProgressDelegate(Progress);
         this.Invoke(del, new object[] { pctComplete });
     }
     else
     {
         progressbar.Value = (int)pctComplete;
     }
 }
Ejemplo n.º 59
0
 public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback)
 {
     throw new Exception(wrongVersion);
 }
        public static bool DownloadGame( string gameTitle, string gameVersion, string url, string username, string password, ProgressDelegate listener, ICancellable cancelObject, out bool o_authFailure, out string o_customMessage )
        {
            if( url == null )
            {
                o_authFailure = false;
                o_customMessage = null;
                return false;
            }

            var downloadPath = GetDownloadPath( gameTitle, gameVersion );
            try
            {
                var request = HttpWebRequest.Create( url );
                request.Timeout = 15000;
                if( username != null && password != null )
                {
                    request.Credentials = new NetworkCredential( username, password );
                }
                using( var response = request.GetResponse() )
                {
                    // Read the message
                    o_customMessage = response.Headers.Get( "X-IndieLauncher-Message" );

                    // Read the content
                    using( var stream = new ProgressStream( response.GetResponseStream(), response.ContentLength, listener, cancelObject ) )
                    {
                        try
                        {
                            // Delete old download
                            if( File.Exists( downloadPath ) )
                            {
                                File.Delete( downloadPath );
                            }

                            // Create new download
                            Directory.CreateDirectory( Path.GetDirectoryName( downloadPath ) );
                            using( var output = File.OpenWrite( downloadPath ) )
                            {
                                try
                                {
                                    stream.CopyTo( output );
                                }
                                finally
                                {
                                    output.Close();
                                }
                            }
                        }
                        finally
                        {
                            stream.Close();
                        }
                    }
                }
                o_authFailure = false;
                return true;
            }
            catch( IOException )
            {
                if( File.Exists( downloadPath ) )
                {
                    File.Delete( downloadPath );
                }
                o_customMessage = null;
                o_authFailure = false;
                return false;
            }
            catch( WebException e )
            {
                if( File.Exists( downloadPath ) )
                {
                    File.Delete( downloadPath );
                }
                if( e.Response != null )
                {
                    o_customMessage = e.Response.Headers.Get( "X-IndieLauncher-Message" );
                    if( ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized )
                    {
                        o_authFailure = true;
                    }
                    else
                    {
                        o_authFailure = false;
                    }
                }
                else
                {
                    o_customMessage = null;
                    o_authFailure = false;
                }
                return false;
            }
        }