private void WorkerAssignment_DropDownClosed(object sender, EventArgs e) { if (listView.SelectedItem == null || WorkerAssignment.SelectedIndex == -1) { WorkerAssignment.SelectedIndex = -1; return; } else { WorkerData worker = (WorkerData)WorkerAssignment.SelectedItem; WorkerAssignmentData assignment = assignments.Where(x => x.worker.Email == worker.Email).First(); foreach (WorkerAssignmentData existingAssingment in assignments) { existingAssingment.orders.RemoveAll(x => x.Product == ProductName.Text); } assignment.orders.Add(new ProductData() { Product = ProductName.Text, Quantity = int.Parse(ProductQty.Text) }); int index = itemsSource.IndexOf(ProductName.Text); if (index == -1) { index = itemsSource.IndexOf(actionRequiredString + ProductName.Text); } itemsSource[index] = itemsSource[index].Replace(actionRequiredString, string.Empty); listView.Items.Refresh(); } }
public void Start(string directory, string filePattern, string[] extentions, string regex, bool isRecursive, bool ignoreCase, bool fileNameOnly) { if (string.IsNullOrEmpty(directory)) { throw new ArgumentNullException("directory"); } filePattern = string.IsNullOrEmpty(filePattern) ? "*.*" : filePattern; extentions = !(extentions ?? new string[] { }).Any() ? new[] { "*.*" } : extentions; if (string.IsNullOrEmpty(regex)) { throw new ArgumentNullException("regex"); } var workerData = new WorkerData { Directory = directory, FilePattern = filePattern, Extentions = extentions, RegEx = regex, IsRecursive = isRecursive, IgnoreCase = ignoreCase, FileNameOnly = fileNameOnly }; CancelAsync().ContinueWith(x => { _bgw = new BackgroundWorker { WorkerSupportsCancellation = true }; _bgw.DoWork += BackgroundWorker_DoWork; _bgw.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; _bgw.RunWorkerAsync(workerData); }); }
private List <WorkerModel> GetWorkers() { WorkerData workerData = new WorkerData(); var gettingWorkers = workerData.SendWorkersData(); return(gettingWorkers); }
private void WorkerThreadStart() { Initialize(); while (isRunning) { //assign current work data to a tmp var, so that we use the same data through the entire itteration //even if data is changed by the main thread, nothing will break or go wrong. WorkerData tmpData = data; if (tmpData.hasNewParent) { Tools.InitRandom(tmpData.randomSeed); tmpData.hasNewParent = false; } DnaDrawing newDrawing = GetMutatedSeedSyncedDrawing(); double newErrorLevel = FitnessCalculator.GetDrawingFitness(newDrawing, info.SourceImage, partitionY, partitionHeight); var result = new DnaPartitionResult { Drawing = newDrawing, ErrorLevel = newErrorLevel, }; tmpData.workerTail.Enqueue(result); } }
public static async Task <WorkerData> FindWorkerDataByIdAsync(string code, string owner) { var output = new WorkerData(); SqlConnection Conn = new SqlConnection(GloablVars.databaseconnectionstring); SqlCommand cmd = new SqlCommand("GetWorker", Conn); try { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("code", code); cmd.Parameters.AddWithValue("owner", owner); await Conn.OpenAsync(); SqlDataReader rd = await cmd.ExecuteReaderAsync(); while (await rd.ReadAsync()) { output.name = rd.GetString(0); output.description = await rd.IsDBNullAsync(1) ? rd.GetString(1) : string.Empty; output.location = rd.GetString(2); output.position = rd.GetString(3); output.date = rd.GetDateTime(4); } Conn.Close(); } catch (Exception) { Conn.Close(); } return(output); }
async Task IPartitionObserver <DocumentServiceLease> .OnPartitionReleasedAsync(DocumentServiceLease l, ChangeFeedObserverCloseReason reason) { #if DEBUG Interlocked.Decrement(ref this.partitionCount); #endif TraceLog.Informational(string.Format("Host '{0}' releasing partition {1}...", this.HostName, l.PartitionId)); WorkerData workerData = null; if (this.partitionKeyRangeIdToWorkerMap.TryGetValue(l.PartitionId, out workerData)) { workerData.Cancellation.Cancel(); try { await workerData.Observer.CloseAsync(workerData.Context, reason); } catch (Exception ex) { // Eat all client exceptions. TraceLog.Error(string.Format("IChangeFeedObserver.CloseAsync: exception: {0}", ex)); } await workerData.Task; this.partitionKeyRangeIdToWorkerMap.TryRemove(l.PartitionId, out workerData); } TraceLog.Informational(string.Format("Host '{0}' partition {1}: released!", this.HostName, workerData.Context.PartitionKeyRangeId)); }
public DataRepository() { ApplicationUser = new ApplicationUserData(); Department = new DepartmentData(); Role = new RoleData(); Worker = new WorkerData(); Project = new ProjectData(); }
public static Inventory.IItem FromDataToInventory(WorkerData data) { return(new HiredWorker() { worker = ReadData(data), quantity = data.Quantity }); }
public static Shop.IItem FromDataToShop(WorkerData data) { return(new OfferingWorker() { worker = ReadData(data), price = data.Price }); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { if (e.Argument is WorkerData) { WorkerData wdata = (WorkerData)e.Argument; e.Result = WAD3Loader.ExtractWadFromBsp(wdata.InputFilename, wdata.OutputFilename); } }
private void Worker_download_DoWork(object sender, DoWorkEventArgs e) { WorkerData workerData = e.Argument as WorkerData; // We gather the info from our class uint offset = 0; uint total = workerData.total; int uiTransmitted; string file = workerData.filename; int progressnb; byte[] readBuffer = new byte[2048 * 8]; ErrorCode eReturn; // Create a FileStream object to write a stream to a file FileStream fileStream = System.IO.File.Create(filename, readBuffer.Length); BinaryWriter binWriter = new BinaryWriter(fileStream); while ((offset <= (total - readBuffer.Length)) && !e.Cancel) { if (Worker_download.CancellationPending) { e.Cancel = true; } eReturn = mEpReader.Read(readBuffer, 1000, out uiTransmitted); if (eReturn == ErrorCode.None) { binWriter.Write(readBuffer); offset += (uint)readBuffer.Length; progressnb = (int)((float)((float)offset / (float)total) * 100.0F); Worker_download.ReportProgress(progressnb); } else { binWriter.Close(); fileStream.Close(); mEpReader.Flush(); return; } } if ((offset >= (total - readBuffer.Length)) && !Worker_download.CancellationPending) { mEpReader.Flush(); //we create a buffer sized to the remaining bytes. This is to avoid writing a file too big. byte[] endBuffer = new byte[total - offset]; mEpReader.Read(endBuffer, 1000, out uiTransmitted); binWriter.Write(endBuffer); return; } mEpReader.Flush(); binWriter.Flush(); binWriter.Close(); fileStream.Flush(); fileStream.Unlock(0, fileStream.Length); fileStream.Close(); }
/// <summary> /// Executes business rules based on ruleSetType. Executes all business rules if ruleSetType is not passed /// </summary> /// <param name="job">The job in context</param> /// <param name="data">The worker data in context</param> /// <param name="ruleSetType">The ruleSetType (Executes all business rules if ruleSetType is not passed)</param> public void Execute(Job job, WorkerData data, RuleSetTypes ruleSetType = RuleSetTypes.Unknown) { List <BusinessRule> businessRules = ruleSetType == RuleSetTypes.Unknown ? this : this.Where(bs => bs.RuleSetType == ruleSetType).ToList(); foreach (BusinessRule businessRule in businessRules) { businessRule.Execute(job, data); } }
private void bgwInstaller_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { this.workingDialog.HideWorking(minMillisecondsDisplayed: 0); var bgwException = e.Error as BackgroundWorkerRunException; var innerException = bgwException.InnerException ?? bgwException; string installationPath = AppLogic.PathCombine(bgwException.WorkerData.GameModPath, bgwException.WorkerData.Mod.RootPath); if (bgwException.WorkerData != null && Directory.Exists(installationPath)) { try { Directory.Delete(installationPath, true); } catch { } } if (innerException is UnauthorizedAccessException) { FlexibleMessageBox.Show(innerException.FormatForMessageBox("The mod could not be installed. You may need to run as administrator."), "Access denied", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (innerException is InvalidOperationException && innerException.Message.StartsWith("Cannot determine compressed stream type.")) { FlexibleMessageBox.Show(innerException.FormatForMessageBox("The mod could not be installed because files compression type is not supported. You should try using 7zip or WinRar may be required."), "Unsupported file type", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { FlexibleMessageBox.Show(innerException.FormatForMessageBox("There was an unexpected error and the mod could not be installed."), "Mod installation error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return; } else { WorkerData workerData = e.Result as WorkerData; try { workerData.Mod.Path = Mod.FindModPath(new DirectoryInfo(AppLogic.PathCombine(workerData.GameModPath, workerData.Mod.RootPath))); if (workerData.Mod.Type == ModType.Unknown) { workerData.Mod.Type = Mod.DetectType(AppLogic.PathCombine(workerData.GameModPath, workerData.Mod.Path), out bool multiplayer); workerData.Mod.Multiplayer = multiplayer; } } catch { } this.workingDialog.HideWorking(); this.Tag = workerData.Mod; this.DialogResult = DialogResult.OK; } }
void OnFinishedWorker(WorkerData worker) { var result = worker.Process.Current; Assert.That(!worker.Process.MoveNext()); if (worker.Callback != null) { worker.Callback(result); } }
protected bool Run(string inputFileName, string outputFileName, object extraData) { backgroundWorker = new MyBackgroundWorker(); var workerData = new WorkerData() { InputFileName = inputFileName, OutputFileName = outputFileName, ExtraData = extraData, BackgroundWorker = backgroundWorker }; backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged); backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted); backgroundWorker.WorkerReportsProgress = true; backgroundWorker.WorkerSupportsCancellation = true; if (Debugger.IsAttached) { backgroundWorker_DoWork(this, new DoWorkEventArgs(workerData)); return(true); } if (progressForm != null && !progressForm.IsDisposed) { progressForm.Dispose(); } progressForm = new ProgressForm(); progressForm.Text = this.TitleBarText; progressForm.CancelButtonPressed += new EventHandler(progressForm_CancelButtonPressed); if (errorsForm != null && !errorsForm.IsDisposed) { errorsForm.Dispose(); } lastErrorCount = 0; backgroundWorker.RunWorkerAsync(workerData); DialogResult dialogResult = DialogResult.None; try { dialogResult = progressForm.ShowDialog(); } catch (System.Reflection.TargetInvocationException ex) { dialogResult = DialogResult.None; } progressForm.Dispose(); return(dialogResult == DialogResult.OK); }
public void CheckWorkersRelashions() { // Arrange ------------------------------------- DbService.LoadSample(); // Act ----------------------------------------- DbService.LoadAll(); // Assert----------------------------------------- var worker = WorkerData.GetWorker("Celivans", "irina", "vasileva"); Assert.AreEqual("202", worker.Room.Name); }
public async Task <string> CallWorkerAsync(string workerName, string delegateName, string caller, object parameters) { var streamsCacheClient = _igniteClient.GetCache <string, StreamData>("streams"); var streamObject = await streamsCacheClient.GetAsync(_streamName); var workerObject = new WorkerData(workerName, delegateName, caller, CreateDelegateParameters(parameters).Item1); streamObject.Workers[workerObject.Name] = workerObject; await streamsCacheClient.ReplaceAsync(_streamName, streamObject); return(workerObject.Name); }
public static unsafe void Write(global::Improbable.Worker.Internal.GcHandlePool _pool, WorkerData _data, global::Improbable.Worker.CInterop.SchemaObject _obj) { { _obj.AddString(1, _data.workerId); } { _obj.AddString(2, _data.workerType); } { global::Improbable.Restricted.Connection_Internal.Write(_pool, _data.connection, _obj.AddObject(3)); } }
public ClusteredWorker(int randomSeed, int partitionY, int partitionHeight, JobInfo info) { data = new WorkerData { randomSeed = randomSeed, workerTail = new Queue <DnaPartitionResult>(), workerUsedTail = new List <DnaPartitionResult>(), }; this.partitionY = partitionY; this.partitionHeight = partitionHeight; this.info = info; }
//Static Methods to create a Worker from a specific data. static Worker ReadData(WorkerData data) { return(new Worker() { id = data.Id, name = data.Name, sprite = SpritePool.LoadSprite(data.SpriteId), color = new Color(data.R, data.G, data.B, data.A), tired = data.Tired, talent = data.Talent, motivation = data.Motivation }); }
static void Main(string[] args) { CultureInfo CI = CultureInfo.InvariantCulture; Console.Write("Enter department's name: "); string deptName = Console.ReadLine(); Console.WriteLine(); Console.WriteLine("Enter worker data:"); Console.Write("Worker's Name: "); string name = Console.ReadLine(); Console.Write("Level (Junior/MidLevel/Senior): "); WorkerLevel level = Enum.Parse <WorkerLevel>(Console.ReadLine()); Console.Write("Base Salary: "); double baseSalary = double.Parse(Console.ReadLine(), CI); Department dept = new Department(deptName); WorkerData worker = new WorkerData(name, level, baseSalary, dept); Console.WriteLine(); Console.Write("How many contracts to this worker? "); int n = int.Parse(Console.ReadLine()); Console.WriteLine(); for (int i = 1; i <= n; i++) { Console.WriteLine($"Enter #{i} contract data: "); Console.Write("Date (MM/DD/YYYY):"); DateTime date = DateTime.Parse(Console.ReadLine()); Console.Write("Value per hour: "); double valuePerHour = double.Parse(Console.ReadLine(), CI); Console.Write("Duration (Hours): "); int hours = int.Parse(Console.ReadLine()); HourContract contract = new HourContract(date, valuePerHour, hours); worker.AddContract(contract); Console.WriteLine(); } Console.WriteLine(); Console.Write("Enter month and year to calculate income (MM/YYYY): "); string monthAndYear = Console.ReadLine(); int month = int.Parse(monthAndYear.Substring(0, 2)); int year = int.Parse(monthAndYear.Substring(3)); Console.WriteLine("Name : " + worker.Name); Console.WriteLine("Department: " + worker.Department.Name); Console.WriteLine("Income for " + monthAndYear + ": " + worker.Income(year, month).ToString("F2", CI)); }
/// <summary> /// Generates a random Worker item; /// </summary> /// <returns></returns> public Worker LoadSingleItem() { WorkerData workerData = new WorkerData(); Worker worker = new Worker(); worker.FirstName = Faker.Name.FirstName(); worker.LastName = Faker.Name.LastName(); worker.Address = new Address().LoadSingleItem(); worker.Job = workerData.Jobs[Faker.Number.RandomNumber(0, workerData.Jobs.Length)]; worker.Email = string.Format("{0}.{1}@tech-store.com", worker.FirstName.ToLower(), worker.LastName.ToLower()); return(worker); }
public ClusteredWorker(int randomSeed, int partitionY, int partitionHeight, JobInfo info) { data = new WorkerData { randomSeed = randomSeed, workerTail = new Queue<DnaPartitionResult>(), workerUsedTail = new List<DnaPartitionResult>(), }; this.partitionY = partitionY; this.partitionHeight = partitionHeight; this.info = info; }
public void SaveState(List <Player> players, Player activePlayer, Board board) { List <PlayerData> playerDatas = new List <PlayerData>(); List <TileData> tileDatas = new List <TileData>(); foreach (Player player in players) { PlayerData playerData = new PlayerData(); playerData.activePlayer = player == activePlayer; List <WorkerData> workerDatas = new List <WorkerData>(); foreach (Worker worker in player.GetWorkers()) { WorkerData workerData = new WorkerData(); TileData tileData = new TileData(); tileData.workerOnTile = worker.GetTile().HasWorkerOnTile(); tileData.towerPieces = worker.GetTile().GetTowerPieceCount(); tileData.domed = worker.GetTile().IsDomed(); workerData.tile = tileData; workerData.colour = (int)worker.GetColour(); workerData.gender = (int)worker.GetGender(); workerDatas.Add(workerData); if (worker == player.GetSelectedWorker()) { playerData.selectedWorker = workerData; } } playerDatas.Add(playerData); playerData.workers = workerDatas; } foreach (Tile tile in board.GetTiles()) { TileData tileData = new TileData(); tileData.workerOnTile = tile.HasWorkerOnTile(); tileData.towerPieces = tile.GetTowerPieceCount(); tileData.domed = tile.IsDomed(); tileDatas.Add(tileData); } _santoriniData.players = playerDatas; _santoriniData.tiles = tileDatas; SaveToJson(); }
public void AcceptGoodDrawing(int tailIndex, int newSeed) { DnaPartitionResult result = data.workerUsedTail[tailIndex]; parentDrawing = result.Drawing; //.Clone(); var newData = new WorkerData { randomSeed = newSeed, hasNewParent = true, workerUsedTail = new List <DnaPartitionResult>(), workerTail = new Queue <DnaPartitionResult>(), }; data = newData; // assign new data to worker, worker will get it next loop itteration }
public DnaPartitionResult GetNextResult() { WorkerData tmp = data; while (tmp.workerTail.Count == 0) { Thread.Sleep(2); //only happens at startup and on rare occasions tmp = data; } DnaPartitionResult result = tmp.workerTail.Dequeue(); tmp.workerUsedTail.Add(result); return(result); }
public Task <WorkerData[]> GetWorkers() { var worker = new WorkerData { Id = 0, Name = Environment.MachineName, State = "ready", Users = 0, Cpu = 10.1d, }; var workers = new[] { worker }; OnWorkerUpdate?.Invoke(workers.Length); return(Task.FromResult(workers)); }
private static bool NextDaysCheck(List <DayData> daysList, WorkerData worker, int currentDayIndex, int interval) { int index = currentDayIndex + interval; if (index < daysList.Count) { DayData auxDay = daysList[index]; if (auxDay.AssignedWorkers.Any(s => s == worker)) { return(false); } } return(true); }
private void bgwInstaller_DoWork(object sender, DoWorkEventArgs e) { WorkerData workerData = e.Argument as WorkerData; try { e.Result = workerData; this.DecompressArchive(workerData.ArchivePath, AppLogic.PathCombine(workerData.GameModPath, workerData.Mod.RootPath)); } catch (Exception ex) { throw new BackgroundWorkerRunException("Exception thrown in DoWork", workerData, ex); } }
public List <WorkerData> GetWorkers() { List <WorkerData> workers = new List <WorkerData>(); foreach (WorkerControl workerControl in _workers) { WorkerData workerData = workerControl.GetWorkerData(); for (int i = 0; i < workerData.DaysOfWork; i++) { workers.Add(workerData); } } return(workers); }
public void Start(IList <IList <TData> > dataBuckets, ListGenerationProgress.ListGenerationCallback progressCallback) { if (dataBuckets == null) { throw new ArgumentNullException(nameof(dataBuckets)); } if (progressCallback == null) { throw new ArgumentNullException(nameof(progressCallback)); } var totalCount = dataBuckets.Aggregate(0, (i, list) => i + list.Count); var progress = 0; void OnItemDone(string itemName) { progressCallback(new ListGenerationProgress(progress++, totalCount, itemName)); } foreach (var itemBucket in dataBuckets) { if (itemBucket.Count == 0) { continue; } var threadCount = Math.Min(MaxThreadsPerBucket, itemBucket.Count / 10 + 1); var threadWorkItemCount = itemBucket.Count / threadCount + 1; for (var i = 0; i < threadCount; i++) { var firstUnique = i * threadWorkItemCount; var workerItems = itemBucket.Skip(firstUnique).Take(threadWorkItemCount).ToList(); var worker = new Thread(WorkerThread) { Name = nameof(ThreadedWorkSpreader <TData, TState>) + "_worker", IsBackground = false }; var workerData = new WorkerData(workerItems, worker, OnItemDone, StateGenerator(itemBucket)); _workers.Add(workerData); worker.Start(workerData); } } }
private void button1_Click(object sender, EventArgs e) { if (textBox1.Text.Trim().Length > 0 && textBox2.Text.Trim().Length > 0) { WorkerData wdata = new WorkerData(); wdata.InputFilename = textBox1.Text; wdata.OutputFilename = textBox2.Text; // progressBar1.Show(); button1.Enabled = false; backgroundWorker1.RunWorkerAsync(wdata); } else { MessageBox.Show("Error, empty filename."); } }
private void b_upload_Click(object sender, EventArgs e) { if (b_upload.Text == "Cancel") { Worker_upload.CancelAsync(); if (Worker_upload.CancellationPending) t_log.AppendText("## Cancelling..." + "\r\n"); return; } if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { filename = openFileDialog1.FileName; openFileDialog1.Dispose(); t_log.AppendText("## Opening " + filename + "\r\n"); byte[] infoBuffer = new byte[8]; byte[] csumBuffer = new byte[2]; byte[] bstart = new byte[4]; byte[] bsize = new byte[4]; // Create a FileStream object to write a stream to a file FileInfo file = new FileInfo(filename); uint fileSize = (uint)file.Length; uint fullFileSize = (uint)file.Length + (uint)infoBuffer.Length + (uint)csumBuffer.Length; //uint start = 0x30000000; // Kernel ram base uint start = dlAddr; // We start where we transfered the program FileStream fileStream = file.OpenRead(); uint end = (start + fileSize); t_log.AppendText("## Calculating checksum... This might take some time on large files." + "\r\n"); UInt16 csum = csum_upload(fileStream, fileSize); t_log.AppendText("## File Information: " + "\r\n" + "## File Size : " + fileSize.ToString() + " (" + (((fileSize) / 1024) / 1024).ToString() + "MB" + " - " + ((fileSize) / 1024).ToString() + "KB)" + "\r\n" + "## Start Addr : " + "0x" + start.ToString("x") + "\r\n" + "## End Addr : " + "0x" + end.ToString("x") + "\r\n"); /* 4 bytes address, 4 bytes length, data, 2 bytes csum, * we have to spread the ints across 4 bytes (an int32 is 4 bytes - 32 bits / 8) */ bstart = BitConverter.GetBytes(start); // 1 bsize = BitConverter.GetBytes(fullFileSize); // 2 csumBuffer = BitConverter.GetBytes(csum); // 3 infoBuffer[0] = bstart[0]; infoBuffer[1] = bstart[1]; infoBuffer[2] = bstart[2]; infoBuffer[3] = bstart[3]; infoBuffer[4] = bsize[0]; infoBuffer[5] = bsize[1]; infoBuffer[6] = bsize[2]; infoBuffer[7] = bsize[3]; t_log.AppendText("## Checksum : 0x" + csum.ToString("x04") + "\r\n"); t_log.AppendText("## Got the info we need, now uploading data..." + "\r\n"); b_upload.Enabled = false; b_download.Enabled = false; // We load the data in our class. WorkerData workerData = new WorkerData { total = fullFileSize, start = start, end = end, info = infoBuffer, csum = csumBuffer, filename = filename }; // fileStream.Unlock(0, fileStream.Length); fileStream.Flush(); fileStream.Close(); b_upload.Enabled = true; b_upload.Text = "Cancel"; Worker_upload.RunWorkerAsync(workerData); // We spawn the thread. } else { openFileDialog1.Dispose(); // If no file is selected, free ressources. } }
public void AcceptGoodDrawing(int tailIndex, int newSeed) { DnaPartitionResult result = data.workerUsedTail[tailIndex]; parentDrawing = result.Drawing; //.Clone(); var newData = new WorkerData { randomSeed = newSeed, hasNewParent = true, workerUsedTail = new List<DnaPartitionResult>(), workerTail = new Queue<DnaPartitionResult>(), }; data = newData; // assign new data to worker, worker will get it next loop itteration }
//return binary script path... public static string BuildScriptThread(string input, string output, string table) { Final = new List<WorkerData>(); Console.WriteLine("Started Binary Script File Build..."); if (input == "" || table == "") { Console.WriteLine("Invalid or missing arguments. Failed."); return ""; } else if (output == "") { //generate output name based on the input output = Path.GetFileNameWithoutExtension(input);//.Split('.')[0]; } else { output = Path.GetFullPath(output); if (!File.Exists(output)) { output = output.Split('.')[0] + "_" + DateTime.Now.ToString("yyyyMMdd") + ".bin"; } } Console.WriteLine("Reading Table file..."); ROMTable rt = ROMTable.LoadTable(table); Console.WriteLine("Reading Script file..."); string script = File.ReadAllText(input).Replace("\r\n", ""); List<byte> outfile = new List<byte>(); List<byte[]> splitdata = new List<byte[]>(); List<int> handled = new List<int>(); Console.WriteLine("Evaluating data..."); int left = Console.CursorLeft; int top = Console.CursorTop; List<int> ControlPos = new List<int>(); int lastpos = 0; //find each index of a control character... for (int c = 0; c < script.Length; c = lastpos + 3) { decimal per = ((decimal)(c + 1) / (decimal)(script.Length)) * (100); Console.SetCursorPosition(left, top); Console.Write(((int)per).ToString() + "%"); lastpos = script.IndexOf("[en", c); if (!(lastpos == -1)) { ControlPos.Add(lastpos); } else { break; } } //make background workers... BackgroundWorker w1 = new BackgroundWorker(); BackgroundWorker w2 = new BackgroundWorker(); BackgroundWorker w3 = new BackgroundWorker(); BackgroundWorker w4 = new BackgroundWorker(); int piece = ControlPos.Count / 4; // make 4 worker threads if (piece < 4) {//then just do a single worker... WorkerData d1 = new WorkerData(); d1.piececount = 1; d1.indata = script; d1.total = script.Length; d1.pos = 0; d1.rt = rt; w1.DoWork += new DoWorkEventHandler(ScriptWorker_DoWork); w1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ScriptWorker_RunWorkerCompleted); w1.RunWorkerAsync(d1); Console.SetCursorPosition(left, top); Console.Write(("100").ToString() + "%"); } else { WorkerData d1 = new WorkerData(); d1.piececount = 1; d1.indata = script.Substring(0, ControlPos[piece]); d1.total = piece; d1.pos = 0; d1.rt = rt; int nextpiece = ControlPos[piece * 2] - ControlPos[piece]; WorkerData d2 = new WorkerData(); d2.piececount = 2; d2.indata = script.Substring(ControlPos[piece], nextpiece); d2.total = piece; d2.pos = 0; d2.rt = rt; nextpiece = ControlPos[piece * 3] - ControlPos[piece * 2]; WorkerData d3 = new WorkerData(); d3.piececount = 3; d3.indata = script.Substring(ControlPos[piece * 2], nextpiece); d3.total = piece; d3.pos = 0; d3.rt = rt; int lastpiece = script.Length - (ControlPos[piece * 3]); WorkerData d4 = new WorkerData(); d4.piececount = 4; d4.indata = script.Substring(ControlPos[piece * 3], lastpiece); d4.total = lastpiece; d4.pos = 0; d4.rt = rt; w1.DoWork += new DoWorkEventHandler(ScriptWorker_DoWork); w1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ScriptWorker_RunWorkerCompleted); w1.RunWorkerAsync(d1); w2.DoWork += new DoWorkEventHandler(ScriptWorker_DoWork); w2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ScriptWorker_RunWorkerCompleted); w2.RunWorkerAsync(d2); w3.DoWork += new DoWorkEventHandler(ScriptWorker_DoWork); w3.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ScriptWorker_RunWorkerCompleted); w3.RunWorkerAsync(d3); w4.DoWork += new DoWorkEventHandler(ScriptWorker_DoWork); w4.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ScriptWorker_RunWorkerCompleted); w4.RunWorkerAsync(d4); Console.SetCursorPosition(left, top); Console.Write(("100").ToString() + "%"); } Console.WriteLine("\r\nWaiting for build process to complete..."); left = Console.CursorLeft; top = Console.CursorTop; int permod = 0; while (w1.IsBusy || w2.IsBusy || w3.IsBusy || w4.IsBusy) { int percent = ((w1.IsBusy) ? 0 : 25) + ((w2.IsBusy) ? 0 : 25) + ((w3.IsBusy) ? 0 : 25) + ((w4.IsBusy) ? 0 : 25) + permod; Console.SetCursorPosition(left, top); Console.Write("~" + (percent).ToString() + "%"); permod++; if (permod > (100 - percent)) { permod = (100 - percent); } System.Threading.Thread.Sleep(100); } Console.SetCursorPosition(left, top); Console.Write(("100").ToString() + "%"); Console.WriteLine("\r\nWriting binary script file..."); outfile.Clear(); if (Final.Count > 0) { for (int c = 1; c < 5; c++) { foreach (WorkerData wd in Final) { if (wd.piececount == c) { outfile.AddRange(wd.outfile); break; } } } if (File.Exists(output)) { File.Delete(output); } using (FileStream fs = new FileStream(output, FileMode.Append)) { fs.Write(outfile.ToArray(), 0, outfile.Count); outfile.Clear(); } Console.Write("File saved: " + output + "\r\n"); } //Console.SetCursorPosition(left, top); Console.Write("Process Complete!!\r\n"); Console.WriteLine("Done!"); return output; }
private void b_download_Click(object sender, EventArgs e) { if (b_download.Text == "Cancel") { Worker_download.CancelAsync(); if (Worker_download.CancellationPending) t_log.AppendText("Cancelling..." + "\r\n"); return; } if (saveFileDialog1.ShowDialog(this) == DialogResult.OK) { filename = saveFileDialog1.FileName; saveFileDialog1.Dispose(); t_log.AppendText("## Saving to " + filename + "\r\n"); byte[] dlinfo = new byte[0x000010a0]; //this array has the size of the info that the mini2440 sends us. b_upload.Enabled = false; b_download.Enabled = false; int uiTransmitted; uint total; ErrorCode eReturn = mEpReader.Read(dlinfo, 1000, out uiTransmitted); if (eReturn == ErrorCode.None) { // We gather the informations from the info buffer and display it. total = BitConverter.ToUInt32(dlinfo, 0x30); t_log.AppendText("Nand Flash Information: " + "\r\n" + "## type : " + "0x" + BitConverter.ToInt32(dlinfo, 0x00).ToString("x08") + "\r\n" + "## flags : " + "0x" + BitConverter.ToInt32(dlinfo, 0x04).ToString("x08") + "\r\n" + "## size : " + ((BitConverter.ToInt32(dlinfo, 0x08) / 1024) / 1024).ToString() + "MB" + " - " + (BitConverter.ToInt32(dlinfo, 0x08) / 1024).ToString() + "KB" + "\r\n" + "## erasesize : " + (BitConverter.ToInt32(dlinfo, 0x0c) / 1024).ToString() + "KB" + "\r\n" + "## oobblock : " + BitConverter.ToInt32(dlinfo, 0x10).ToString() + "\r\n" + "## oobsize : " + BitConverter.ToInt32(dlinfo, 0x14).ToString() + "\r\n" + "## ecctype : " + "0x" + BitConverter.ToInt32(dlinfo, 0x18).ToString("x") + "\r\n" + "## eccsize : " + BitConverter.ToInt32(dlinfo, 0x1c).ToString() + "\r\n"); t_log.AppendText("Backup Information: " + "\r\n" + "## Start Addr : " + "0x" + BitConverter.ToInt32(dlinfo, 0x20).ToString("x08") + "\r\n" + "## End Addr : " + "0x" + BitConverter.ToInt32(dlinfo, 0x24).ToString("x08") + "\r\n" + "## bBackupOOB : " + BitConverter.ToInt32(dlinfo, 0x28).ToString() + "\r\n" + "## bCheckBad : " + BitConverter.ToInt32(dlinfo, 0x2c).ToString() + "\r\n" + "## dwBackupTotalLen : " + "0x" + total.ToString("x") + " (" + ((total / 1024) / 1024) + "MB)" + "\r\n" + "## dwReservedBlks : " + BitConverter.ToInt32(dlinfo, 0x34).ToString() + "\r\n" + "## dwEPInPktSize : " + BitConverter.ToInt32(dlinfo, 0x38).ToString() + "\r\n"); t_log.AppendText("## Got the info we need, now downloading data..." + "\r\n"); b_download.Enabled = true; b_download.Text = "Cancel"; } else { t_log.AppendText("## No info to read! " + eReturn + "\r\n"); b_upload.Enabled = true; b_download.Enabled = true; return; } // We load the data in our class. WorkerData workerData = new WorkerData { total = total, start = BitConverter.ToUInt32(dlinfo, 0x20), end = BitConverter.ToUInt32(dlinfo, 0x24) }; Worker_download.RunWorkerAsync(workerData); // We spawn the thread. } else { saveFileDialog1.Dispose(); } }