/// <summary> /// Return true if success /// </summary> /// <param name="s"></param> /// <param name="url"></param> /// <param name="destPath"></param> /// <returns></returns> private static bool DownloadFile(EngineState s, string url, string destPath) { Uri uri = new Uri(url); bool result = true; Stopwatch watch = Stopwatch.StartNew(); using (WebClient client = new WebClient()) { client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { s.MainViewModel.BuildCommandProgressValue = e.ProgressPercentage; TimeSpan t = watch.Elapsed; double totalSec = t.TotalSeconds; string downloaded = NumberHelper.ByteSizeToHumanReadableString(e.BytesReceived, 1); string total = NumberHelper.ByteSizeToHumanReadableString(e.TotalBytesToReceive, 1); if (totalSec == 0) { s.MainViewModel.BuildCommandProgressText = $"{url}\r\nTotal : {total}\r\nReceived : {downloaded}"; } else { long bytePerSec = (long)(e.BytesReceived / totalSec); // Byte per sec string speedStr = NumberHelper.ByteSizeToHumanReadableString((long)(e.BytesReceived / totalSec), 1) + "/s"; // KB/s, MB/s, ... TimeSpan r = TimeSpan.FromSeconds((e.TotalBytesToReceive - e.BytesReceived) / bytePerSec); int hour = (int)r.TotalHours; int min = r.Minutes; int sec = r.Seconds; s.MainViewModel.BuildCommandProgressText = $"{url}\r\nTotal : {total}\r\nReceived : {downloaded}\r\nSpeed : {speedStr}\r\nRemaining Time : {hour}h {min}m {sec}s"; } }; AutoResetEvent resetEvent = new AutoResetEvent(false); client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { s.RunningWebClient = null; // Check if error occured if (e.Cancelled || e.Error != null) { result = false; if (File.Exists(destPath)) { File.Delete(destPath); } } resetEvent.Set(); }; s.RunningWebClient = client; client.DownloadFileAsync(uri, destPath); resetEvent.WaitOne(); } watch.Stop(); return(result); }
private void gridControl_CurrentCellKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (this._jual == null || txtNotaJual.Text.Length == 0) { MsgHelper.MsgWarning("Maaf isian data belum lengkap !"); txtNotaJual.Focus(); return; } var grid = (GridControl)sender; var rowIndex = grid.CurrentCell.RowIndex; var colIndex = grid.CurrentCell.ColIndex; GridCurrentCell cc; ItemJualProduk itemJual; switch (colIndex) { case 2: // kode produk _isValidKodeProduk = false; cc = grid.CurrentCell; var kodeProduk = cc.Renderer.ControlValue.ToString(); if (kodeProduk.Length == 0) { GridListControlHelper.SetCurrentCell(grid, rowIndex, colIndex + 1); } else { itemJual = this._jual.item_jual.Where(f => f.Produk.kode_produk.ToLower() == kodeProduk.ToLower() && f.jumlah > f.jumlah_retur) .SingleOrDefault(); if (itemJual == null) { MsgHelper.MsgWarning("Data produk tidak ditemukan"); GridListControlHelper.SelectCellText(grid, rowIndex, colIndex); return; } _isValidKodeProduk = true; if (!IsExist(itemJual.produk_id)) { SetItemProduk(grid, rowIndex, itemJual, itemJual.jumlah - itemJual.jumlah_retur, itemJual.harga_jual); grid.Refresh(); RefreshTotal(); GridListControlHelper.SetCurrentCell(grid, rowIndex, colIndex + 2); } else { GridListControlHelper.SetCurrentCell(grid, rowIndex, colIndex + 2); } } break; case 3: // nama produk cc = grid.CurrentCell; var namaProduk = cc.Renderer.ControlValue.ToString(); if (!_isValidKodeProduk) { var listOfItemJual = this._jual.item_jual.Where(f => f.Produk.nama_produk.ToLower().Contains(namaProduk.ToLower()) && f.jumlah > f.jumlah_retur) .ToList(); if (listOfItemJual.Count == 0) { MsgHelper.MsgWarning("Data produk tidak ditemukan"); GridListControlHelper.SelectCellText(grid, rowIndex, colIndex); } else if (listOfItemJual.Count == 1) { itemJual = listOfItemJual[0]; if (!IsExist(itemJual.produk_id)) { SetItemProduk(grid, rowIndex, itemJual, itemJual.jumlah - itemJual.jumlah_retur, itemJual.harga_jual); grid.Refresh(); GridListControlHelper.SetCurrentCell(grid, rowIndex, colIndex + 1); } else { MsgHelper.MsgWarning("Data produk sudah diinputkan"); GridListControlHelper.SelectCellText(grid, rowIndex, colIndex); } } else // data lebih dari satu { _rowIndex = rowIndex; _colIndex = colIndex; var frmLookup = new FrmLookupItemNota("Item Penjualan", listOfItemJual); frmLookup.Listener = this; frmLookup.ShowDialog(); } } break; case 4: _isValidJumlahRetur = false; try { cc = grid.CurrentCell; double jumlahRetur = NumberHelper.StringToDouble(cc.Renderer.ControlValue.ToString(), true); var jumlahJual = _listOfItemRetur[rowIndex - 1].jumlah; if (jumlahRetur <= jumlahJual) { _isValidJumlahRetur = true; GridListControlHelper.SetCurrentCell(grid, rowIndex, colIndex + 1); } else { MsgHelper.MsgWarning("Maaf, jumlah retur tidak boleh melebihi jumlah jual"); } } catch { } break; case 5: if (grid.RowCount == rowIndex) { _listOfItemRetur.Add(new ItemReturJualProduk()); grid.RowCount = _listOfItemRetur.Count; } GridListControlHelper.SetCurrentCell(grid, rowIndex + 1, 2); // fokus ke kolom nama produk break; default: break; } } }
private void InitGridControl(GridControl grid) { var gridListProperties = new List <GridListControlProperties>(); gridListProperties.Add(new GridListControlProperties { Header = "No", Width = 30 }); gridListProperties.Add(new GridListControlProperties { Header = "Kode Produk", Width = 120 }); gridListProperties.Add(new GridListControlProperties { Header = "Nama Produk", Width = 320 }); gridListProperties.Add(new GridListControlProperties { Header = "Jumlah", Width = 50 }); gridListProperties.Add(new GridListControlProperties { Header = "Diskon", Width = 50 }); gridListProperties.Add(new GridListControlProperties { Header = "Harga", Width = 90 }); gridListProperties.Add(new GridListControlProperties { Header = "Sub Total", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Aksi" }); GridListControlHelper.InitializeGridListControl <ItemBeliProduk>(grid, _listOfItemBeli, gridListProperties); grid.PushButtonClick += delegate(object sender, GridCellPushButtonClickEventArgs e) { if (e.ColIndex == 8) { if (grid.RowCount == 1) { MsgHelper.MsgWarning("Minimal 1 item produk harus diinputkan !"); return; } if (MsgHelper.MsgDelete()) { var itemBeli = _listOfItemBeli[e.RowIndex - 1]; itemBeli.entity_state = EntityState.Deleted; _listOfItemBeliDeleted.Add(itemBeli); _listOfItemBeli.Remove(itemBeli); grid.RowCount = _listOfItemBeli.Count(); grid.Refresh(); RefreshTotal(); } } }; grid.QueryCellInfo += delegate(object sender, GridQueryCellInfoEventArgs e) { // Make sure the cell falls inside the grid if (e.RowIndex > 0) { if (!(_listOfItemBeli.Count > 0)) { return; } var itemBeli = _listOfItemBeli[e.RowIndex - 1]; var produk = itemBeli.Produk; if (e.RowIndex % 2 == 0) { e.Style.BackColor = ColorCollection.BACK_COLOR_ALTERNATE; } double harga = 0; double jumlah = 0; var isRetur = itemBeli.jumlah_retur > 0; if (isRetur) { e.Style.BackColor = Color.Red; e.Style.Enabled = false; } switch (e.ColIndex) { case 1: // no urut e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.Enabled = false; e.Style.CellValue = e.RowIndex.ToString(); break; case 2: if (produk != null) { e.Style.CellValue = produk.kode_produk; } break; case 3: // nama produk if (produk != null) { e.Style.CellValue = produk.nama_produk; } break; case 4: // jumlah e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellValue = itemBeli.jumlah - itemBeli.jumlah_retur; break; case 5: // diskon e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellValue = itemBeli.diskon; break; case 6: // harga e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; harga = itemBeli.harga; if (!(harga > 0)) { if (produk != null) { harga = produk.harga_beli; } } e.Style.CellValue = NumberHelper.NumberToString(harga); break; case 7: // subtotal e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.Enabled = false; jumlah = itemBeli.jumlah - itemBeli.jumlah_retur; harga = itemBeli.harga_setelah_diskon; if (!(harga > 0)) { if (produk != null) { harga = produk.harga_beli; } } e.Style.CellValue = NumberHelper.NumberToString(jumlah * harga); break; case 8: // button hapus e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellType = GridCellTypeName.PushButton; e.Style.Description = "Hapus"; break; default: break; } e.Handled = true; // we handled it, let the grid know } }; var colIndex = 2; // kolom nama produk grid.CurrentCell.MoveTo(1, colIndex, GridSetCurrentCellOptions.BeginEndUpdate); }
protected override void Simpan() { if (_isNewData) { _produk = new Produk(); } if (_produk.list_of_harga_grosir.Count == 0) { var index = 0; foreach (var item in _listOfTxtHargaGrosir) { var txtHargaGrosir = _listOfTxtHargaGrosir[index]; var txtJumlahMinGrosir = _listOfTxtJumlahGrosir[index]; var txtDiskonGrosir = _listOfTxtDiskonGrosir[index]; var hargaGrosir = new HargaGrosir { harga_ke = index + 1, harga_grosir = NumberHelper.StringToDouble(txtHargaGrosir.Text), jumlah_minimal = NumberHelper.StringToDouble(txtJumlahMinGrosir.Text, true), diskon = NumberHelper.StringToDouble(txtDiskonGrosir.Text, true) }; _produk.list_of_harga_grosir.Add(hargaGrosir); index++; } } else { var index = 0; foreach (var item in _produk.list_of_harga_grosir) { var txtHargaGrosir = _listOfTxtHargaGrosir[index]; var txtJumlahMinGrosir = _listOfTxtJumlahGrosir[index]; var txtDiskonGrosir = _listOfTxtDiskonGrosir[index]; item.harga_grosir = NumberHelper.StringToDouble(txtHargaGrosir.Text); item.jumlah_minimal = NumberHelper.StringToDouble(txtJumlahMinGrosir.Text, true); item.diskon = NumberHelper.StringToDouble(txtDiskonGrosir.Text, true); index++; } } var golongan = _listOfGolongan[cmbGolongan.SelectedIndex]; _produk.golongan_id = golongan.golongan_id; _produk.Golongan = golongan; _produk.kode_produk = txtKodeProduk.Text; _produk.nama_produk = txtNamaProduk.Text; _produk.satuan = txtSatuan.Text; _produk.harga_beli = NumberHelper.StringToDouble(txtHargaBeli.Text); _produk.harga_jual = NumberHelper.StringToDouble(txtHargaJual.Text); _produk.diskon = NumberHelper.StringToDouble(txtDiskon.Text, true); _produk.persentase_keuntungan = NumberHelper.StringToDouble(txtKeuntungan.Text, true); _produk.stok = NumberHelper.StringToDouble(txtStok.Text, true); _produk.stok_gudang = NumberHelper.StringToDouble(txtStokGudang.Text, true); _produk.minimal_stok_gudang = NumberHelper.StringToDouble(txtMinStokGudang.Text, true); var result = 0; var validationError = new ValidationError(); using (new StCursor(Cursors.WaitCursor, new TimeSpan(0, 0, 0, 0))) { if (_isNewData) { result = _bll.Save(_produk, ref validationError); } else { result = _bll.Update(_produk, ref validationError); } if (result > 0) { Listener.Ok(this, _isNewData, _produk); if (_isNewData) { base.ResetForm(this); txtKodeProduk.Text = this._bll.GetLastKodeProduk(); txtKodeProduk.Focus(); } else { this.Close(); } } else { if (validationError.Message.NullToString().Length > 0) { MsgHelper.MsgWarning(validationError.Message); base.SetFocusObject(validationError.PropertyName, this); } else { MsgHelper.MsgDuplicate("kode produk"); txtKodeProduk.Focus(); txtKodeProduk.SelectAll(); } } } }
private void InitGridControl(GridControl grid) { var gridListProperties = new List <GridListControlProperties>(); gridListProperties.Add(new GridListControlProperties { Header = "No", Width = 30 }); gridListProperties.Add(new GridListControlProperties { Header = "Nota Jual", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Total", Width = 100, IsEditable = false, HorizontalAlignment = GridHorizontalAlignment.Right }); gridListProperties.Add(new GridListControlProperties { Header = "Kekurangan", Width = 100, IsEditable = false, HorizontalAlignment = GridHorizontalAlignment.Right }); gridListProperties.Add(new GridListControlProperties { Header = "Pembayaran", Width = 100, HorizontalAlignment = GridHorizontalAlignment.Right }); gridListProperties.Add(new GridListControlProperties { Header = "Keterangan", Width = 200 }); gridListProperties.Add(new GridListControlProperties { Header = "Aksi" }); GridListControlHelper.InitializeGridListControl <ItemPembayaranPiutangProduk>(grid, _listOfItemPembayaranPiutang, gridListProperties); grid.PushButtonClick += delegate(object sender, GridCellPushButtonClickEventArgs e) { if (e.ColIndex == 7) { if (grid.RowCount == 1) { MsgHelper.MsgWarning("Minimal 1 nota harus diinputkan !"); return; } if (MsgHelper.MsgDelete()) { var pembayaranPiutang = _listOfItemPembayaranPiutang[e.RowIndex - 1]; pembayaranPiutang.entity_state = EntityState.Deleted; _listOfItemPembayaranPiutangDeleted.Add(pembayaranPiutang); _listOfItemPembayaranPiutang.Remove(pembayaranPiutang); grid.RowCount = _listOfItemPembayaranPiutang.Count(); grid.Refresh(); RefreshTotal(); } } }; grid.QueryCellInfo += delegate(object sender, GridQueryCellInfoEventArgs e) { // Make sure the cell falls inside the grid if (e.RowIndex > 0) { if (!(_listOfItemPembayaranPiutang.Count > 0)) { return; } double grand_total = 0; double sisaNota = 0; var itemPembayaran = _listOfItemPembayaranPiutang[e.RowIndex - 1]; var jual = itemPembayaran.JualProduk; if (jual != null) { grand_total = jual.grand_total;; sisaNota = jual.sisa_nota; } switch (e.ColIndex) { case 1: // no urut e.Style.CellValue = e.RowIndex.ToString(); break; case 2: // nota jual if (jual != null) { e.Style.CellValue = jual.nota; } if (jual != null) { if (jual.tanggal_tempo.IsNull()) // nota tunai nominalnya tidak bisa diedit { e.Style.Enabled = false; e.Style.BackColor = ColorCollection.DEFAULT_FORM_COLOR; base.SetButtonSimpanToFalse(true); } } break; case 3: // total e.Style.CellValue = NumberHelper.NumberToString(grand_total); break; case 4: // kekurangan e.Style.CellValue = NumberHelper.NumberToString(sisaNota); break; case 5: // pembayaran if (jual != null) { if (jual.tanggal_tempo.IsNull()) // nota tunai nominalnya tidak bisa diedit { e.Style.Enabled = false; e.Style.BackColor = ColorCollection.DEFAULT_FORM_COLOR; } } e.Style.CellValue = NumberHelper.NumberToString(itemPembayaran.nominal); break; case 6: // keterangan e.Style.CellValue = itemPembayaran.keterangan; break; case 7: // button hapus e.Style.CellType = GridCellTypeName.PushButton; e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.Description = "Hapus"; if (jual != null) { e.Style.Enabled = !jual.tanggal_tempo.IsNull(); } break; default: break; } e.Handled = true; // we handled it, let the grid know } }; var colIndex = 2; // kolom nama produk grid.CurrentCell.MoveTo(1, colIndex, GridSetCurrentCellOptions.BeginEndUpdate); }
public AnalysisKit(Pullenti.Ner.SourceOfAnalysis sofa = null, bool onlyTokenizing = false, Pullenti.Morph.MorphLang lang = null, ProgressChangedEventHandler progress = null) { if (sofa == null) { return; } m_Sofa = sofa; StartDate = DateTime.Now; List <Pullenti.Morph.MorphToken> tokens = Pullenti.Morph.MorphologyService.Process(sofa.Text, lang, progress); Pullenti.Ner.Token t0 = null; if (tokens != null) { for (int ii = 0; ii < tokens.Count; ii++) { Pullenti.Morph.MorphToken mt = tokens[ii]; if (mt.BeginChar == 733860) { } Pullenti.Ner.TextToken tt = new Pullenti.Ner.TextToken(mt, this); if (sofa.CorrectionDict != null) { string corw; if (sofa.CorrectionDict.TryGetValue(mt.Term, out corw)) { List <Pullenti.Morph.MorphToken> ccc = Pullenti.Morph.MorphologyService.Process(corw, lang, null); if (ccc != null && ccc.Count == 1) { Pullenti.Ner.TextToken tt1 = new Pullenti.Ner.TextToken(ccc[0], this, tt.BeginChar, tt.EndChar) { Term0 = tt.Term }; tt1.Chars = tt.Chars; tt = tt1; if (CorrectedTokens == null) { CorrectedTokens = new Dictionary <Pullenti.Ner.Token, string>(); } CorrectedTokens.Add(tt, tt.GetSourceText()); } } } if (t0 == null) { FirstToken = tt; } else { t0.Next = tt; } t0 = tt; } } if (sofa.ClearDust) { this.ClearDust(); } if (sofa.DoWordsMergingByMorph) { this.CorrectWordsByMerging(lang); } if (sofa.DoWordCorrectionByMorph) { this.CorrectWordsByMorph(lang); } this.MergeLetters(); this.DefineBaseLanguage(); if (sofa.CreateNumberTokens) { for (Pullenti.Ner.Token t = FirstToken; t != null; t = t.Next) { Pullenti.Ner.NumberToken nt = NumberHelper.TryParseNumber(t); if (nt == null) { continue; } this.EmbedToken(nt); t = nt; } } if (onlyTokenizing) { return; } for (Pullenti.Ner.Token t = FirstToken; t != null; t = t.Next) { if (t.Morph.Class.IsPreposition) { continue; } Pullenti.Morph.MorphClass mc = t.GetMorphClassInDictionary(); if (mc.IsUndefined && t.Chars.IsCyrillicLetter && t.LengthChar > 4) { string tail = sofa.Text.Substring(t.EndChar - 1, 2); Pullenti.Ner.Token tte = null; Pullenti.Ner.Token tt = t.Previous; if (tt != null && ((tt.IsCommaAnd || tt.Morph.Class.IsPreposition || tt.Morph.Class.IsConjunction))) { tt = tt.Previous; } if ((tt != null && !tt.GetMorphClassInDictionary().IsUndefined&& ((tt.Morph.Class.Value & t.Morph.Class.Value)) != 0) && tt.LengthChar > 4) { string tail2 = sofa.Text.Substring(tt.EndChar - 1, 2); if (tail2 == tail) { tte = tt; } } if (tte == null) { tt = t.Next; if (tt != null && ((tt.IsCommaAnd || tt.Morph.Class.IsPreposition || tt.Morph.Class.IsConjunction))) { tt = tt.Next; } if ((tt != null && !tt.GetMorphClassInDictionary().IsUndefined&& ((tt.Morph.Class.Value & t.Morph.Class.Value)) != 0) && tt.LengthChar > 4) { string tail2 = sofa.Text.Substring(tt.EndChar - 1, 2); if (tail2 == tail) { tte = tt; } } } if (tte != null) { t.Morph.RemoveItemsEx(tte.Morph, tte.GetMorphClassInDictionary()); } } continue; } this.CreateStatistics(); }
public void MinMaxValuesAreCorrect() { NumberHelper.AssertLong("-9223372036854775808", long.MinValue); NumberHelper.AssertLong("9223372036854775807", long.MaxValue); }
public static void N410() { // Decimal consts var DecimalZero = decimal.Zero; var DecimalOne = decimal.One; var DecimalMinusOne = decimal.MinusOne; var DecimalMaxValue = decimal.MaxValue; var DecimalMinValue = decimal.MinValue; NumberHelper.AssertDecimal("0", DecimalZero, "DecimalZero"); NumberHelper.AssertDecimal("1", DecimalOne, "DecimalOne"); NumberHelper.AssertDecimal("-1", DecimalMinusOne, "DecimalMinusOne"); NumberHelper.AssertDecimal("79228162514264337593543950335", DecimalMaxValue, "DecimalMaxValue"); NumberHelper.AssertDecimal("-79228162514264337593543950335", DecimalMinValue, "DecimalMinValue"); // Decimal consts in expressions decimal dz = 0m; DecimalZero = decimal.Zero + dz; DecimalOne = decimal.One + dz; DecimalMinusOne = decimal.MinusOne + dz; DecimalMaxValue = decimal.MaxValue + dz; DecimalMinValue = decimal.MinValue + dz; NumberHelper.AssertDecimal("0", DecimalZero, "DecimalZeroin expression"); NumberHelper.AssertDecimal("1", DecimalOne, "DecimalOnein expression"); NumberHelper.AssertDecimal("-1", DecimalMinusOne, "DecimalMinusOnein expression"); NumberHelper.AssertDecimal("79228162514264337593543950335", DecimalMaxValue, "DecimalMaxValuein expression"); NumberHelper.AssertDecimal("-79228162514264337593543950335", DecimalMinValue, "DecimalMinValuein expression"); var numberPositiveInfinity = Script.Get <object>("Number.POSITIVE_INFINITY"); var numberNegativeInfinity = Script.Get <object>("Number.NEGATIVE_INFINITY"); var numberNaN = Script.NaN; // Double consts var DoubleMaxValue = double.MaxValue; var DoubleMinValue = double.MinValue; var DoubleEpsilon = double.Epsilon; var DoubleNegativeInfinity = double.NegativeInfinity; var DoublePositiveInfinity = double.PositiveInfinity; var DoubleNaN = double.NaN; NumberHelper.AssertDouble("1.79769313486232E+308", DoubleMaxValue, "DoubleMaxValue"); NumberHelper.AssertDouble("-1.79769313486232E+308", DoubleMinValue, "DoubleMinValue"); NumberHelper.AssertDouble("4.94065645841247E-324", DoubleEpsilon, "DoubleEpsilon"); Assert.AreEqual(numberNegativeInfinity, DoubleNegativeInfinity, "DoubleNegativeInfinity"); Assert.AreEqual(numberPositiveInfinity, DoublePositiveInfinity, "DoublePositiveInfinity"); Assert.AreEqual(numberNaN, DoubleNaN, "DoubleNaN"); // Double consts in expressions double dblz = 0d; DoubleMaxValue = double.MaxValue + dblz; DoubleMinValue = double.MinValue + dblz; DoubleEpsilon = double.Epsilon + dblz; DoubleNegativeInfinity = double.NegativeInfinity + dblz; DoublePositiveInfinity = double.PositiveInfinity + dblz; DoubleNaN = double.NaN + dblz; NumberHelper.AssertDouble("1.79769313486232E+308", DoubleMaxValue, "DoubleMaxValuein expression"); NumberHelper.AssertDouble("-1.79769313486232E+308", DoubleMinValue, "DoubleMinValuein expression"); NumberHelper.AssertDouble("4.94065645841247E-324", DoubleEpsilon, "DoubleEpsilonin expression"); Assert.AreEqual(numberNegativeInfinity, DoubleNegativeInfinity, "DoubleNegativeInfinityin expression"); Assert.AreEqual(numberPositiveInfinity, DoublePositiveInfinity, "DoublePositiveInfinityin expression"); Assert.AreEqual(numberNaN, DoubleNaN, "DoubleNaNin expression"); // Math consts var MathE = Math.E; var MathPI = Math.PI; NumberHelper.AssertDouble("2.71828182845905", MathE, "MathE"); //IE has Math.LOG2E defined as 1.4426950408889633 instead of standard 1.4426950408889634 NumberHelper.AssertDouble("3.14159265358979", MathPI, "MathPI"); // Math consts in expression MathE = Math.E + 0; MathPI = Math.PI + 0; NumberHelper.AssertDouble("2.71828182845905", MathE, "MathEin expression"); //IE has Math.LOG2E defined as 1.4426950408889633 instead of standard 1.4426950408889634 NumberHelper.AssertDouble("3.14159265358979", MathPI, "MathPIin expression"); // Single consts var SingleMaxValue = float.MaxValue; var SingleMinValue = float.MinValue; var SingleEpsilon = float.Epsilon; var SingleNaN = float.NaN; var SingleNegativeInfinity = float.NegativeInfinity; var SinglePositiveInfinity = float.PositiveInfinity; NumberHelper.AssertFloat("3.402823E+38", SingleMaxValue, "SingleMaxValue"); NumberHelper.AssertFloat("-3.402823E+38", SingleMinValue, "SingleMinValue"); NumberHelper.AssertFloat("1.401298E-45", SingleEpsilon, "SingleEpsilon"); Assert.AreEqual(numberNaN, SingleNaN, "SingleNaN"); Assert.AreEqual(numberNegativeInfinity, SingleNegativeInfinity, "SingleNegativeInfinity"); Assert.AreEqual(numberPositiveInfinity, SinglePositiveInfinity, "SinglePositiveInfinity"); // Single consts in expression float fz = 0; SingleMaxValue = float.MaxValue + fz; SingleMinValue = float.MinValue + fz; SingleEpsilon = float.Epsilon + fz; SingleNaN = float.NaN + fz; SingleNegativeInfinity = float.NegativeInfinity + fz; SinglePositiveInfinity = float.PositiveInfinity + fz; NumberHelper.AssertFloat("3.402823E+38", SingleMaxValue, "SingleMaxValuein expression"); NumberHelper.AssertFloat("-3.402823E+38", SingleMinValue, "SingleMinValuein expression"); NumberHelper.AssertFloat("1.401298E-45", SingleEpsilon, "SingleEpsilonin expression"); Assert.AreEqual(numberNaN, SingleNaN, "SingleNaNin expression"); Assert.AreEqual(numberNegativeInfinity, SingleNegativeInfinity, "SingleNegativeInfinityin expression"); Assert.AreEqual(numberPositiveInfinity, SinglePositiveInfinity, "SinglePositiveInfinityin expression"); }
private void InitGridListHistoriPembayaran() { var gridListProperties = new List <GridListControlProperties>(); gridListProperties.Add(new GridListControlProperties { Header = "No", Width = 30 }); gridListProperties.Add(new GridListControlProperties { Header = "Tanggal", Width = 70 }); gridListProperties.Add(new GridListControlProperties { Header = "Nota", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Jumlah", Width = 90 }); gridListProperties.Add(new GridListControlProperties { Header = "Keterangan" }); GridListControlHelper.InitializeGridListControl <PembayaranKasbon>(this.gridListHistoriPembayaran, _listOfHistoriPembayaranKasbon, gridListProperties); if (_listOfHistoriPembayaranKasbon.Count > 0) { this.gridListHistoriPembayaran.SetSelected(0, true); } this.gridListHistoriPembayaran.Grid.QueryCellInfo += delegate(object sender, GridQueryCellInfoEventArgs e) { if (_listOfHistoriPembayaranKasbon.Count > 0) { if (e.RowIndex > 0) { var rowIndex = e.RowIndex - 1; if (rowIndex < _listOfHistoriPembayaranKasbon.Count) { var pembayaranKasbon = _listOfHistoriPembayaranKasbon[rowIndex]; switch (e.ColIndex) { case 2: e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellValue = DateTimeHelper.DateToString(pembayaranKasbon.tanggal); break; case 3: e.Style.CellValue = pembayaranKasbon.nota; break; case 4: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(pembayaranKasbon.nominal); break; case 5: e.Style.CellValue = pembayaranKasbon.keterangan; break; default: break; } // we handled it, let the grid know e.Handled = true; } } } }; this.gridListHistoriPembayaran.SelectedValueChanged += delegate(object sender, EventArgs e) { GridListHistoriPembayaranHandleSelectionChanged((GridListControl)sender); }; this.gridListHistoriPembayaran.DoubleClick += delegate(object sender, EventArgs e) { if (btnPerbaikiPembayaran.Enabled) { btnPerbaikiPembayaran_Click(sender, e); } }; }
public void TestMethod1() { int actual = NumberHelper.NumberOf1Between1AndN(1); Assert.AreEqual(actual, 1); }
public void Cetak(JualProduk jual, IList <HeaderNota> listOfHeaderNota, int jumlahBaris = 29, int jumlahKarakter = 80, bool isCetakKeteranganNota = true, string infoCopyright = "") { var garisPemisah = StringHelper.PrintChar('=', jumlahKarakter); var textToPrint = new StringBuilder(); var rowCount = 0; // jumlah baris yang tercetak if (!Utils.IsRunningUnderIDE()) { textToPrint.Append(ESCCommandHelper.InitializePrinter()); textToPrint.Append(ESCCommandHelper.CenterText()); } // cetak header foreach (var header in listOfHeaderNota) { if (header.keterangan.Length > 0) { if (header.keterangan.Length > garisPemisah.Length) { header.keterangan = StringHelper.FixedLength(header.keterangan, garisPemisah.Length); } textToPrint.Append(header.keterangan).Append(ESCCommandHelper.LineFeed(1)); rowCount++; } } textToPrint.Append(ESCCommandHelper.LineFeed(1)); rowCount++; if (!Utils.IsRunningUnderIDE()) { textToPrint.Append(ESCCommandHelper.LeftText()); } // cetak informasi nota textToPrint.Append("Nota : ").Append(jual.nota).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append("Tanggal: ").Append(DateTimeHelper.DateToString(jual.tanggal)); if (jual.tanggal_tempo != null) { textToPrint.Append(StringHelper.PrintChar(' ', 4)); textToPrint.Append("Tempo: ").Append(DateTimeHelper.DateToString(jual.tanggal_tempo)).Append(ESCCommandHelper.LineFeed(2)); } else { textToPrint.Append(ESCCommandHelper.LineFeed(2)); } rowCount += 4; // cetak informasi customer var namaCustomer = string.Empty; if (jual.is_sdac) { if (jual.Customer != null) { namaCustomer = StringHelper.FixedLength(jual.Customer.nama_customer.NullToString(), jumlahKarakter - 10); } } else { namaCustomer = StringHelper.FixedLength(jual.kirim_kepada.NullToString(), jumlahKarakter - 10); } if (namaCustomer.Length > 0) { var alamat1 = jual.is_sdac ? jual.Customer.alamat.NullToString() : jual.kirim_alamat.NullToString(); var alamat2 = string.Empty; var sb = new StringBuilder(); if (jual.is_sdac) { var customer = jual.Customer; alamat2 = customer == null ? string.Empty : customer.get_wilayah_lengkap; } else { alamat2 = jual.kirim_kecamatan; } textToPrint.Append("Kepada : ").Append(namaCustomer).Append(ESCCommandHelper.LineFeed(1)); rowCount++; textToPrint.Append("Alamat : "); var isAddLineFeed = true; if (alamat1.Length > 0) { textToPrint.Append(StringHelper.FixedLength(alamat1, jumlahKarakter - 10)).Append(ESCCommandHelper.LineFeed(1)); rowCount++; isAddLineFeed = false; } if (alamat2.Length > 0) { textToPrint.Append(StringHelper.PrintChar(' ', 9)).Append(StringHelper.FixedLength(alamat2, jumlahKarakter - 10)).Append(ESCCommandHelper.LineFeed(1)); rowCount++; isAddLineFeed = false; } if (isAddLineFeed) { textToPrint.Append(ESCCommandHelper.LineFeed(1)); } } textToPrint.Append(garisPemisah).Append(ESCCommandHelper.LineFeed(1)); // header tabel textToPrint.Append("NO"); textToPrint.Append(StringHelper.PrintChar(' ', 2)); textToPrint.Append("PRODUK"); textToPrint.Append(StringHelper.PrintChar(' ', 34)); textToPrint.Append("JUMLAH"); textToPrint.Append(StringHelper.PrintChar(' ', 2)); textToPrint.Append("HARGA"); textToPrint.Append(StringHelper.PrintChar(' ', 4)); textToPrint.Append("DISC (%)"); textToPrint.Append(StringHelper.PrintChar(' ', 2)); textToPrint.Append("SUB TOTAL").Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(garisPemisah).Append(ESCCommandHelper.LineFeed(1)); rowCount += 3; var lengthProduk = 37; var lengthJumlah = 5; var lengthHarga = 9; var lengthDisc = 5; var lengthSubTotal = 11; // cetak item var noUrut = 1; foreach (var item in jual.item_jual) { var strNoUrut = StringHelper.RightAlignment(noUrut.ToString(), 2); textToPrint.Append(strNoUrut).Append(StringHelper.PrintChar(' ', 2)); var produk = StringHelper.FixedLength(item.Produk.nama_produk, lengthProduk); textToPrint.Append(produk).Append(StringHelper.PrintChar(' ', 2)); var strJumlah = StringHelper.RightAlignment((item.jumlah - item.jumlah_retur).ToString(), lengthJumlah); textToPrint.Append(strJumlah).Append(StringHelper.PrintChar(' ', 2)); var strHarga = StringHelper.RightAlignment(NumberHelper.NumberToString(item.harga_setelah_diskon), lengthHarga); textToPrint.Append(strHarga).Append(StringHelper.PrintChar(' ', 2)); var strDisc = StringHelper.RightAlignment((item.diskon).ToString(), lengthDisc); textToPrint.Append(strDisc).Append(StringHelper.PrintChar(' ', 3)); var subTotal = (item.jumlah - item.jumlah_retur) * item.harga_setelah_diskon; var strSubTotal = StringHelper.RightAlignment(NumberHelper.NumberToString(subTotal), lengthSubTotal); textToPrint.Append(strSubTotal).Append(ESCCommandHelper.LineFeed(1)); if (item.keterangan.Length > 0) { textToPrint.Append(StringHelper.PrintChar(' ', 4)).Append(item.keterangan).Append(ESCCommandHelper.LineFeed(1)); } noUrut++; rowCount++; } // cetak footer textToPrint.Append(garisPemisah).Append(ESCCommandHelper.LineFeed(1)); var lengthOngkosKirim = 11; if (jual.ongkos_kirim > 0) { textToPrint.Append(StringHelper.PrintChar(' ', 56)); var strOngkosKirim = StringHelper.RightAlignment(NumberHelper.NumberToString(jual.ongkos_kirim), lengthOngkosKirim); textToPrint.Append("Ongkos Kirim:").Append(strOngkosKirim).Append(ESCCommandHelper.LineFeed(1)); rowCount++; } if (jual.diskon > 0) { var strDiscNota = StringHelper.RightAlignment(NumberHelper.NumberToString(jual.diskon), lengthOngkosKirim); textToPrint.Append(StringHelper.PrintChar(' ', 56)); textToPrint.Append("Diskon :").Append(strDiscNota).Append(ESCCommandHelper.LineFeed(1)); rowCount++; } if (jual.ppn > 0) { var strPPN = StringHelper.RightAlignment(NumberHelper.NumberToString(jual.ppn), lengthOngkosKirim); textToPrint.Append(StringHelper.PrintChar(' ', 56)); textToPrint.Append("PPN :").Append(strPPN).Append(ESCCommandHelper.LineFeed(1)); rowCount++; } var strGrandTotal = StringHelper.RightAlignment(NumberHelper.NumberToString(jual.grand_total), lengthOngkosKirim); textToPrint.Append(StringHelper.PrintChar(' ', 56)); textToPrint.Append("Total :").Append(strGrandTotal).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(garisPemisah).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(StringHelper.PrintChar(' ', 8)).Append("Penerima"); textToPrint.Append(StringHelper.PrintChar(' ', 40)).Append("Hormat Kami"); textToPrint.Append(ESCCommandHelper.LineFeed(3)); textToPrint.Append(StringHelper.PrintChar(' ', 6)).Append("------------"); textToPrint.Append(StringHelper.PrintChar(' ', 37)).Append("-------------"); if (isCetakKeteranganNota && jual.keterangan.NullToString().Length > 0) { textToPrint.Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(ESCCommandHelper.LineFeed(1)).Append("Keterangan: ").Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append("* "); var splitKeterangan = StringHelper.SplitByLength(jual.keterangan, 78); foreach (var ket in splitKeterangan) { textToPrint.Append(ket).Append(ESCCommandHelper.LineFeed(1)); } } if (infoCopyright.Length > 0) { textToPrint.Append(ESCCommandHelper.LineFeed(1)); if (!Utils.IsRunningUnderIDE()) { textToPrint.Append(ESCCommandHelper.CenterText()); } textToPrint.Append(infoCopyright).Append(ESCCommandHelper.LineFeed(1)); } rowCount += 6; // perhitungan sisa kertas untuk keperluan line feed var listOfMaxRow = new Dictionary <int, int>(); for (int i = 1; i < 11; i++) { var key = jumlahBaris * i; var value = key + 4; listOfMaxRow.Add(key, value); } var maxJumlahBaris = 0; // maksimal jumlah baris tercetak dalam satu halaman foreach (var item in listOfMaxRow) { maxJumlahBaris = item.Value; if (rowCount <= item.Key) { break; } } var lineFeed = maxJumlahBaris - rowCount; textToPrint.Append(ESCCommandHelper.LineFeed(lineFeed)); if (!Utils.IsRunningUnderIDE()) { RawPrintHelper.SendStringToPrinter(_printerName, textToPrint.ToString()); } else { RawPrintHelper.SendStringToFile(textToPrint.ToString()); } }
public void TestMethod7() { int actual = NumberHelper.NumberOf1Between1AndN(21345); Assert.AreEqual(actual, 18821); }
private void InitGridList() { var gridListProperties = new List <GridListControlProperties>(); gridListProperties.Add(new GridListControlProperties { Header = "No", Width = 30 }); gridListProperties.Add(new GridListControlProperties { Header = "Tanggal", Width = 80 }); gridListProperties.Add(new GridListControlProperties { Header = "Nama", Width = 200 }); gridListProperties.Add(new GridListControlProperties { Header = "Jabatan", Width = 200 }); gridListProperties.Add(new GridListControlProperties { Header = "Kehadiran", Width = 70 }); gridListProperties.Add(new GridListControlProperties { Header = "Absen", Width = 70 }); gridListProperties.Add(new GridListControlProperties { Header = "Gaji", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Tunjangan", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Bonus", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Lembur", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Potongan", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Total" }); GridListControlHelper.InitializeGridListControl <GajiKaryawan>(this.gridList, _listOfGaji, gridListProperties); if (_listOfGaji.Count > 0) { this.gridList.SetSelected(0, true); } this.gridList.Grid.QueryCellInfo += delegate(object sender, GridQueryCellInfoEventArgs e) { if (_listOfGaji.Count > 0) { if (e.RowIndex > 0) { var rowIndex = e.RowIndex - 1; if (rowIndex < _listOfGaji.Count) { var gaji = _listOfGaji[rowIndex]; switch (e.ColIndex) { case 2: e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellValue = DateTimeHelper.DateToString(gaji.tanggal); break; case 3: var karyawan = gaji.Karyawan; if (karyawan != null) { e.Style.CellValue = karyawan.nama_karyawan; } break; case 4: var jabatan = gaji.Karyawan.Jabatan; if (jabatan != null) { e.Style.CellValue = jabatan.nama_jabatan; } break; case 5: e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellValue = gaji.kehadiran; break; case 6: e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellValue = gaji.absen; break; case 7: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(gaji.gaji_akhir); break; case 8: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(gaji.tunjangan); break; case 9: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(gaji.bonus); break; case 10: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(gaji.lembur_akhir); break; case 11: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(gaji.potongan); break; case 12: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(gaji.total_gaji); break; default: break; } // we handled it, let the grid know e.Handled = true; } } } }; }
public static List <LogInfo> StrFormat(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_StrFormat info = cmd.Info.Cast <CodeInfo_StrFormat>(); StrFormatType type = info.Type; switch (type) { case StrFormatType.IntToBytes: case StrFormatType.Bytes: { StrFormatInfo_IntToBytes subInfo = info.SubInfo.Cast <StrFormatInfo_IntToBytes>(); string byteSizeStr = StringEscaper.Preprocess(s, subInfo.ByteSize); if (!NumberHelper.ParseInt64(byteSizeStr, out long byteSize)) { return(LogInfo.LogErrorMessage(logs, $"[{byteSizeStr}] is not a valid integer")); } if (byteSize < 0) { return(LogInfo.LogErrorMessage(logs, $"[{byteSize}] must be a positive integer")); } string destStr = NumberHelper.ByteSizeToSIUnit(byteSize); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.BytesToInt: { Debug.Assert(info.SubInfo.GetType() == typeof(StrFormatInfo_BytesToInt), "Invalid StrFormatInfo"); StrFormatInfo_BytesToInt subInfo = info.SubInfo as StrFormatInfo_BytesToInt; Debug.Assert(subInfo != null, "Invalid StrFormatInfo"); string humanReadableByteSizeStr = StringEscaper.Preprocess(s, subInfo.HumanReadableByteSize); decimal dest = NumberHelper.HumanReadableStringToByteSize(humanReadableByteSizeStr); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, decimal.Ceiling(dest).ToString(CultureInfo.InvariantCulture)); logs.AddRange(varLogs); } break; case StrFormatType.Hex: { StrFormatInfo_Hex subInfo = info.SubInfo.Cast <StrFormatInfo_Hex>(); string intStr = StringEscaper.Preprocess(s, subInfo.Integer); if (!NumberHelper.ParseInt32(intStr, out int intVal)) { return(LogInfo.LogErrorMessage(logs, $"[{intStr}] is not a valid integer")); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, intVal.ToString("X8")); logs.AddRange(varLogs); } break; case StrFormatType.Ceil: case StrFormatType.Floor: case StrFormatType.Round: { StrFormatInfo_CeilFloorRound subInfo = info.SubInfo.Cast <StrFormatInfo_CeilFloorRound>(); string roundToStr = StringEscaper.Preprocess(s, subInfo.RoundTo); // Is roundToStr number? if (!NumberHelper.ParseInt64(roundToStr, out long roundTo)) { // Is roundToStr is one of K, M, G, T, P? if (roundToStr.Equals("K", StringComparison.OrdinalIgnoreCase)) { roundTo = KB; } else if (roundToStr.Equals("M", StringComparison.OrdinalIgnoreCase)) { roundTo = MB; } else if (roundToStr.Equals("G", StringComparison.OrdinalIgnoreCase)) { roundTo = GB; } else if (roundToStr.Equals("T", StringComparison.OrdinalIgnoreCase)) { roundTo = TB; } else if (roundToStr.Equals("P", StringComparison.OrdinalIgnoreCase)) { roundTo = PB; } else { return(LogInfo.LogErrorMessage(logs, $"[{roundToStr}] is not a valid integer")); } } if (roundTo < 0) { return(LogInfo.LogErrorMessage(logs, $"[{roundTo}] must be a positive integer")); } string srcIntStr = StringEscaper.Preprocess(s, subInfo.SizeVar); if (!NumberHelper.ParseInt64(srcIntStr, out long srcInt)) { return(LogInfo.LogErrorMessage(logs, $"[{srcIntStr}] is not a valid integer")); } long destInt; switch (type) { case StrFormatType.Ceil: { long remainder = srcInt % roundTo; destInt = srcInt - remainder + roundTo; break; } case StrFormatType.Floor: { long remainder = srcInt % roundTo; destInt = srcInt - remainder; break; } case StrFormatType.Round: { long remainder = srcInt % roundTo; if ((roundTo - 1) / 2 < remainder) { destInt = srcInt - remainder + roundTo; } else { destInt = srcInt - remainder; } break; } default: throw new InternalException($"Internal Logic Error at StrFormat,{type}"); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.SizeVar, destInt.ToString()); logs.AddRange(varLogs); } break; case StrFormatType.Date: { // <yyyy-mmm-dd hh:nn am/pm> StrFormatInfo_Date subInfo = info.SubInfo.Cast <StrFormatInfo_Date>(); string formatStr = StringEscaper.Preprocess(s, subInfo.FormatString); string destStr = DateTime.Now.ToString(formatStr, CultureInfo.InvariantCulture); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.FileName: case StrFormatType.DirPath: case StrFormatType.Path: case StrFormatType.Ext: { StrFormatInfo_Path subInfo = info.SubInfo.Cast <StrFormatInfo_Path>(); string srcStr = StringEscaper.Preprocess(s, subInfo.FilePath); string destStr = string.Empty; if (srcStr.Trim().Equals(string.Empty, StringComparison.Ordinal)) // Empty or Whitespace string { logs.Add(new LogInfo(LogState.Info, $"Source string [{srcStr}] is empty")); } else { switch (type) { case StrFormatType.FileName: destStr = Path.GetFileName(srcStr); logs.Add(new LogInfo(LogState.Success, $"Path [{srcStr}]'s file name is [{destStr}]")); break; case StrFormatType.DirPath: case StrFormatType.Path: // Includes Last Seperator - Default WB082 Behavior int bsIdx = srcStr.LastIndexOf('\\'); int sIdx = srcStr.LastIndexOf('/'); if (bsIdx != -1 && sIdx != -1) { // Slash and BackSlash cannot exist at same time logs.Add(new LogInfo(LogState.Error, $"Path [{srcStr}] is invalid")); return(logs); } if (bsIdx != -1) { // Normal file path // destStr = Path.GetDirectoryName(srcStr) + '\\'; destStr = srcStr.Substring(0, bsIdx + 1); } else { // URL if (sIdx == -1) { destStr = string.Empty; } else { destStr = srcStr.Substring(0, sIdx + 1); } } logs.Add(new LogInfo(LogState.Success, $"Path [{srcStr}]'s directory path is [{destStr}]")); break; case StrFormatType.Ext: destStr = Path.GetExtension(srcStr); logs.Add(new LogInfo(LogState.Success, $"Path [{srcStr}]'s extension is [{destStr}]")); break; default: throw new InternalException($"Internal Logic Error at StrFormat,{type}"); } } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.PathCombine: { // StrFormat,PathCombine,<DirPath>,<FileName>,<DestVar> StrFormatInfo_PathCombine subInfo = info.SubInfo.Cast <StrFormatInfo_PathCombine>(); string dirPath = StringEscaper.Preprocess(s, subInfo.DirPath).Trim(); string fileName = StringEscaper.Preprocess(s, subInfo.FileName).Trim(); if (Regex.IsMatch(dirPath, @"^([a-zA-Z]:)$", RegexOptions.Compiled | RegexOptions.CultureInvariant)) { dirPath = dirPath + @"\"; } string destStr = Path.Combine(dirPath, fileName); logs.Add(new LogInfo(LogState.Success, $"Path [{dirPath}] and [{fileName}] combined into [{destStr}]")); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.Inc: case StrFormatType.Dec: case StrFormatType.Mult: case StrFormatType.Div: { StrFormatInfo_Arithmetic subInfo = info.SubInfo.Cast <StrFormatInfo_Arithmetic>(); string operandStr = StringEscaper.Preprocess(s, subInfo.Integer); if (!NumberHelper.ParseInt64(operandStr, out long operand)) { return(LogInfo.LogErrorMessage(logs, $"[{operandStr}] is not a valid integer")); } string destStr; string srcStr = StringEscaper.Preprocess(s, subInfo.DestVar); if (NumberHelper.ParseInt64(srcStr, out long src)) { // Integer (Discouraged - Use Math,Add/Sub/Mul/Div/IntDiv instead) long dest = src; if (type == StrFormatType.Inc) { dest += operand; } else if (type == StrFormatType.Dec) { dest -= operand; } else if (type == StrFormatType.Mult) { dest *= operand; } else if (type == StrFormatType.Div) { dest /= operand; } destStr = dest.ToString(); } else if (srcStr.Length == 1 && (type == StrFormatType.Inc || type == StrFormatType.Dec)) { // Letter bool upper = StringHelper.IsUpperAlphabet(srcStr[0]); bool lower = StringHelper.IsLowerAlphabet(srcStr[0]); if (upper == false && lower == false) { logs.Add(new LogInfo(LogState.Error, $"[{srcStr}] is not a valid integer nor drive letter")); return(logs); } char dest = srcStr[0]; if (type == StrFormatType.Inc) { dest = (char)(dest + operand); } else if (type == StrFormatType.Dec) { dest = (char)(dest - operand); } if (upper && !StringHelper.IsUpperAlphabet(dest) || lower && !StringHelper.IsLowerAlphabet(dest)) { return(LogInfo.LogErrorMessage(logs, "Result is not a valid drive letter")); } destStr = dest.ToString(); } else { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.Left: case StrFormatType.Right: { StrFormatInfo_LeftRight subInfo = info.SubInfo.Cast <StrFormatInfo_LeftRight>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string cutLenStr = StringEscaper.Preprocess(s, subInfo.Count); if (!NumberHelper.ParseInt32(cutLenStr, out int cutLen)) { return(LogInfo.LogErrorMessage(logs, $"[{cutLenStr}] is not a valid integer")); } if (cutLen < 0) { return(LogInfo.LogErrorMessage(logs, $"[{cutLen}] must be a positive integer")); } string destStr = string.Empty; try { if (type == StrFormatType.Left) { if (cutLen <= srcStr.Length) { destStr = srcStr.Substring(0, cutLen); } else { destStr = srcStr; } } else if (type == StrFormatType.Right) { if (cutLen <= srcStr.Length) { destStr = srcStr.Substring(srcStr.Length - cutLen, cutLen); } else { destStr = srcStr; } } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } catch (ArgumentOutOfRangeException) { // Correct WB082 behavior : Not error, but just empty string logs.Add(new LogInfo(LogState.Ignore, $"[{cutLen}] is not a valid index")); logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, string.Empty)); } } break; case StrFormatType.Mid: { // Index start from 1, not 0! StrFormatInfo_Mid subInfo = info.SubInfo.Cast <StrFormatInfo_Mid>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string startPosStr = StringEscaper.Preprocess(s, subInfo.StartPos); if (!NumberHelper.ParseInt32(startPosStr, out int startPos)) { return(LogInfo.LogErrorMessage(logs, $"[{startPosStr}] is not a valid integer")); } if (startPos <= 0) { return(LogInfo.LogErrorMessage(logs, $"[{startPos}] must be a positive integer")); } string lenStr = StringEscaper.Preprocess(s, subInfo.Length); if (!NumberHelper.ParseInt32(lenStr, out int len)) { return(LogInfo.LogErrorMessage(logs, $"[{lenStr}] is not a valid integer")); } if (len <= 0) { return(LogInfo.LogErrorMessage(logs, $"[{len}] must be a positive integer")); } // Error handling if (srcStr.Length <= startPos - 1) { return(LogInfo.LogErrorMessage(logs, $"Start position [{startPos}] cannot be bigger than source string's length [{srcStr.Length}]")); } if (srcStr.Length - (startPos - 1) < len) { return(LogInfo.LogErrorMessage(logs, $"Length [{len}] cannot be bigger than [{srcStr.Length - startPos}]")); } string destStr = srcStr.Substring(startPos - 1, len); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.Len: { StrFormatInfo_Len subInfo = info.SubInfo.Cast <StrFormatInfo_Len>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, srcStr.Length.ToString()); logs.AddRange(varLogs); } break; case StrFormatType.LTrim: case StrFormatType.RTrim: case StrFormatType.CTrim: { StrFormatInfo_Trim subInfo = info.SubInfo.Cast <StrFormatInfo_Trim>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string toTrim = StringEscaper.Preprocess(s, subInfo.ToTrim); try { string destStr; if (type == StrFormatType.LTrim) // string.Substring { if (!NumberHelper.ParseInt32(toTrim, out int cutLen)) { logs.Add(new LogInfo(LogState.Error, $"[{toTrim}] is not a valid integer")); } // Error handling if (srcStr.Length < cutLen) { cutLen = srcStr.Length; } else if (cutLen < 0) { cutLen = 0; } destStr = srcStr.Substring(cutLen); } else if (type == StrFormatType.RTrim) // string.Substring { if (!NumberHelper.ParseInt32(toTrim, out int cutLen)) { logs.Add(new LogInfo(LogState.Error, $"[{toTrim}] is not a valid integer")); } // Error handling if (srcStr.Length < cutLen) { cutLen = srcStr.Length; } else if (cutLen < 0) { cutLen = 0; } destStr = srcStr.Substring(0, srcStr.Length - cutLen); } else if (type == StrFormatType.CTrim) // string.Trim { if (toTrim.Length == 0) { return(LogInfo.LogErrorMessage(logs, "No characters to trim")); } char[] chArr = toTrim.ToCharArray(); destStr = srcStr.Trim(chArr); } else { throw new InternalException("Internal Logic Error at StrFormat,Trim"); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVarName, destStr); logs.AddRange(varLogs); } catch (ArgumentOutOfRangeException) { logs.Add(new LogInfo(LogState.Error, $"[{toTrim}] is not a valid index")); } } break; case StrFormatType.NTrim: { StrFormatInfo_NTrim subInfo = info.SubInfo.Cast <StrFormatInfo_NTrim>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); Match m = Regex.Match(srcStr, @"([0-9]+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant); var destStr = m.Success ? srcStr.Substring(0, m.Index) : srcStr; List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.UCase: case StrFormatType.LCase: { StrFormatInfo_ULCase subInfo = info.SubInfo.Cast <StrFormatInfo_ULCase>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string destStr; if (type == StrFormatType.UCase) { destStr = srcStr.ToUpper(CultureInfo.InvariantCulture); } else if (type == StrFormatType.LCase) { destStr = srcStr.ToLower(CultureInfo.InvariantCulture); } else { throw new InternalException("Internal Logic Error at StrFormat,ULCase"); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.Pos: case StrFormatType.PosX: { StrFormatInfo_Pos subInfo = info.SubInfo.Cast <StrFormatInfo_Pos>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string subStr = StringEscaper.Preprocess(s, subInfo.SubStr); StringComparison comp = StringComparison.OrdinalIgnoreCase; if (type == StrFormatType.PosX) { comp = StringComparison.Ordinal; } // 0 if not found int idx = 0; if (!subStr.Equals(string.Empty, StringComparison.Ordinal)) { idx = srcStr.IndexOf(subStr, comp) + 1; } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, idx.ToString()); logs.AddRange(varLogs); } break; case StrFormatType.Replace: case StrFormatType.ReplaceX: { StrFormatInfo_Replace subInfo = info.SubInfo.Cast <StrFormatInfo_Replace>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string subStr = StringEscaper.Preprocess(s, subInfo.SearchStr); string newStr = StringEscaper.Preprocess(s, subInfo.ReplaceStr); StringComparison comp = StringComparison.OrdinalIgnoreCase; if (type == StrFormatType.ReplaceX) { comp = StringComparison.Ordinal; } string destStr = StringHelper.ReplaceEx(srcStr, subStr, newStr, comp); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.ShortPath: case StrFormatType.LongPath: { // Will be deprecated StrFormatInfo_ShortLongPath subInfo = info.SubInfo.Cast <StrFormatInfo_ShortLongPath>(); logs.Add(new LogInfo(LogState.Warning, $"Command [StrFormatType,{info.Type}] is deprecated")); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string destStr; if (type == StrFormatType.ShortPath) { destStr = FileHelper.GetShortPath(srcStr); } else { destStr = FileHelper.GetLongPath(srcStr); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case StrFormatType.Split: { StrFormatInfo_Split subInfo = info.SubInfo.Cast <StrFormatInfo_Split>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string delimStr = StringEscaper.Preprocess(s, subInfo.Delimiter); string idxStr = StringEscaper.Preprocess(s, subInfo.Index); if (!NumberHelper.ParseInt32(idxStr, out int idx)) { return(LogInfo.LogErrorMessage(logs, $"[{idxStr}] is not a valid integer")); } char[] delim = delimStr.ToCharArray(); List <LogInfo> varLogs; if (idx == 0) { int delimCount = srcStr.Split(delim).Length; logs.Add(new LogInfo(LogState.Success, $"String [{srcStr}] is split to [{delimCount}] strings.")); varLogs = Variables.SetVariable(s, subInfo.DestVar, delimCount.ToString()); logs.AddRange(varLogs); } else { string[] slices = srcStr.Split(delim); if (idx - 1 < slices.Length) { string destStr = slices[idx - 1]; logs.Add(new LogInfo(LogState.Success, $"String [{srcStr}]'s split index [{idx}] is [{destStr}]")); varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } else { logs.Add(new LogInfo(LogState.Info, $"Index [{idx}] out of bounds [{slices.Length}]")); } } } break; case StrFormatType.PadLeft: case StrFormatType.PadRight: { StrFormatInfo_Pad subInfo = info.SubInfo.Cast <StrFormatInfo_Pad>(); string srcStr = StringEscaper.Preprocess(s, subInfo.SrcStr); string totalWidthStr = StringEscaper.Preprocess(s, subInfo.TotalWidth); string padCharStr = StringEscaper.Preprocess(s, subInfo.PadChar); if (!NumberHelper.ParseInt32(totalWidthStr, out int totalWidth)) { return(LogInfo.LogErrorMessage(logs, $"[{totalWidthStr}] is not a valid integer")); } if (totalWidth < 0) { return(LogInfo.LogErrorMessage(logs, $"[{totalWidth}] must be a positive integer")); } if (padCharStr.Length != 1) { return(LogInfo.LogErrorMessage(logs, $"Padding character [{padCharStr}] should be one character")); } char padChar = padCharStr[0]; string destStr = type == StrFormatType.PadLeft ? srcStr.PadLeft(totalWidth, padChar) : srcStr.PadRight(totalWidth, padChar); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; // Error default: throw new InternalException("Internal Logic Error at CommandString.StrFormat"); } return(logs); }
/// <summary> /// Called every frame to perform processing. We only use /// this function if it's not called by another component. /// </summary> protected void Update() { if (mAnimator == null) { return; } if (mCameraRig == null) { return; } if (Time.deltaTime == 0f) { return; } // Store the state we're in mStateInfo = mAnimator.GetCurrentAnimatorStateInfo(0); mTransitionInfo = mAnimator.GetAnimatorTransitionInfo(0); if (mCameraRig.Mode == 2) { if (mStance != 2) { mPrevStance = mStance; mStance = 2; } } else { if (mStance == 2) { mStance = mPrevStance; } } // Determine the stance we're in if (mInputSource != null && mInputSource.IsPressed(KeyCode.LeftControl)) { //if (mStance != 2) //{ // mPrevStance = mStance; // mStance = 2; // mPrevRigMode = CameraRigMode; // // Start the transition process // //_CameraRig.TransitionToMode(EnumCameraMode.FIRST_PERSON); // CameraRigMode = EnumCameraMode.FIRST_PERSON; //} } else if (mStance == 2) { //mStance = mPrevStance; ////_CameraRig.TransitionToMode(mPrevRigMode); //CameraRigMode = mPrevRigMode; } else if (mInputSource != null && mInputSource.IsJustPressed(KeyCode.T)) { mPrevStance = mStance; if (mStance == 0) { mStance = 1; ((AdventureRig)mCameraRig).AnchorOrbitsCamera = false; } else if (mStance == 1) { mStance = 0; ((AdventureRig)mCameraRig).AnchorOrbitsCamera = true; } mCameraRig.Mode = 0; } // Grab the direction and speed of the input relative to our current heading StickToWorldspace(this.transform, _CameraRig.transform, ref mTempState); // Ensure some of the other values are set correctly mTempState.Acceleration = mState.Acceleration; mTempState.InitialHeading = mState.InitialHeading; // Ranged movement allows for slow forward, backwards, and strafing if (mStance == 2) { //CameraRigMode = EnumCameraMode.FIRST_PERSON; mTempState.Speed *= _TargetingStanceMovementSpeedMultiplier; // Change our heading if needed if (mTempState.Speed == 0) { if (IsInBackwardsState) { mTempState.InitialHeading = 2; } else { mTempState.InitialHeading = 0; } } else if (mTempState.Speed != 0 && mState.Speed == 0) { float lInitialAngle = Mathf.Abs(mTempState.FromCameraAngle); if (lInitialAngle < mForwardHeadingLimit) { mTempState.InitialHeading = 0; } else if (lInitialAngle > 180f - mBackwardsHeadingLimit) { mTempState.InitialHeading = 2; } else { mTempState.InitialHeading = 1; } } // Ensure we're always facing forward //mYAxisRotationAngle = NumberHelper.GetHorizontalAngle(transform.forward, _CameraRig.transform.forward); //mTempState.FromAvatarAngle = 0f; } // Combat movement allows for forward, backwards, strafing, and pivoting else if (mStance == 1) { // Determine our initial heading if (mTempState.Speed == 0) { if (IsInBackwardsState) { mTempState.InitialHeading = 2; } else { mTempState.InitialHeading = 0; } } else if (mTempState.Speed != 0 && mState.Speed == 0) { float lInitialAngle = Mathf.Abs(mTempState.FromCameraAngle); if (lInitialAngle < mForwardHeadingLimit) { mTempState.InitialHeading = 0; } else if (lInitialAngle > 180f - mBackwardsHeadingLimit) { mTempState.InitialHeading = 2; } else { mTempState.InitialHeading = 1; } } // Ensure if we've been heading forward that we don't allow the // avatar to rotate back facing the player if (mTempState.InitialHeading == 0) { //CameraRigMode = EnumCameraMode.THIRD_PERSON_FOLLOW; // Force the input to make us go forwards if (mTempState.Speed > 0.1f && (mTempState.FromCameraAngle < -90 || mTempState.FromCameraAngle > 90)) { mTempState.InputY = 1; } // If no forward rotation is allowed, this is easy if (mForwardHeadingLimit == 0f) { mTempState.FromAvatarAngle = 0f; } // Respect the foward rotation limits else { // Test if our rotation reaches the max from the camera. We use the camera since // the avatar itself rotates and this limit is relative. if (mTempState.FromCameraAngle < -mForwardHeadingLimit) { mTempState.FromCameraAngle = -mForwardHeadingLimit; } else if (mTempState.FromCameraAngle > mForwardHeadingLimit) { mTempState.FromCameraAngle = mForwardHeadingLimit; } // If we have reached a limit, we need to adjust the avatar angle if (Mathf.Abs(mTempState.FromCameraAngle) == mForwardHeadingLimit) { // Flip the angle if we're crossing over the axis if (Mathf.Sign(mTempState.FromCameraAngle) != Mathf.Sign(mState.FromCameraAngle)) { mTempState.FromCameraAngle = -mTempState.FromCameraAngle; } // Only allow the avatar to rotate the heading limit, taking into account the angular // difference between the camera and the avatar mTempState.FromAvatarAngle = mTempState.FromCameraAngle + NumberHelper.GetHorizontalAngle(transform.forward, _CameraRig.transform.forward); } } } else if (mTempState.InitialHeading == 2) { //CameraRigMode = EnumCameraMode.THIRD_PERSON_FIXED; // Force the input to make us go backwards if (mTempState.Speed > 0.1f && (mTempState.FromCameraAngle > -90 && mTempState.FromCameraAngle < 90)) { mTempState.InputY = -1; } // Ensure we don't go beyond our boundry if (mBackwardsHeadingLimit != 0f) { float lBackwardsHeadingLimit = 180f - mBackwardsHeadingLimit; // Test if our rotation reaches the max from the camera. We use the camera since // the avatar itself rotates and this limit is relative. if (mTempState.FromCameraAngle <= 0 && mTempState.FromCameraAngle > -lBackwardsHeadingLimit) { mTempState.FromCameraAngle = -lBackwardsHeadingLimit; } else if (mTempState.FromCameraAngle >= 0 && mTempState.FromCameraAngle < lBackwardsHeadingLimit) { mTempState.FromCameraAngle = lBackwardsHeadingLimit; } // If we have reached a limit, we need to adjust the avatar angle if (Mathf.Abs(mTempState.FromCameraAngle) == lBackwardsHeadingLimit) { // Only allow the avatar to rotate the heading limit, taking into account the angular // difference between the camera and the avatar mTempState.FromAvatarAngle = mTempState.FromCameraAngle + NumberHelper.GetHorizontalAngle(transform.forward, _CameraRig.transform.forward); } // Since we're moving backwards, we need to flip the movement angle. // If we're not moving and simply finishing an animation, we don't // want to rotate at all. if (mTempState.Speed == 0) { mTempState.FromAvatarAngle = 0f; } else if (mTempState.FromAvatarAngle <= 0) { mTempState.FromAvatarAngle += 180f; } else if (mTempState.FromAvatarAngle > 0) { mTempState.FromAvatarAngle -= 180f; } } } else if (mTempState.InitialHeading == 1) { //CameraRigMode = EnumCameraMode.THIRD_PERSON_FIXED; // Move out of the sidestep if needed if (mTempState.InputY > 0.1) { mTempState.InitialHeading = 0; } else if (mTempState.InputY < -0.1) { mTempState.InitialHeading = 2; } // We need to be able to rotate our avatar so it's facing // in the direction of the camera if (mTempState.InitialHeading == 1) { mTempState.FromCameraAngle = 0f; mTempState.FromAvatarAngle = mTempState.FromCameraAngle + NumberHelper.GetHorizontalAngle(transform.forward, _CameraRig.transform.forward); } } } // Determine the acceleration. We test this agains the 'last-last' speed so // that we are averaging out one frame. //mLastAcceleration = mAcceleration; mPrevState.Acceleration = mState.Acceleration; // Determine the trend so we can figure out acceleration if (mTempState.Speed == mState.Speed) { if (mSpeedTrendDirection != 0) { mSpeedTrendDirection = 0; } } else if (mTempState.Speed < mState.Speed) { if (mSpeedTrendDirection != 1) { mSpeedTrendDirection = 1; if (mMecanimUpdateDelay <= 0f) { mMecanimUpdateDelay = 0.2f; } } // Acceleration needs to stay consistant for mecanim mTempState.Acceleration = mTempState.Speed - mSpeedTrendStart; } else if (mTempState.Speed > mState.Speed) { if (mSpeedTrendDirection != 2) { mSpeedTrendDirection = 2; if (mMecanimUpdateDelay <= 0f) { mMecanimUpdateDelay = 0.2f; } } // Acceleration needs to stay consistant for mecanim mTempState.Acceleration = mTempState.Speed - mSpeedTrendStart; } // Shuffle the states to keep us from having to reallocated AdventureControllerState lTempState = mPrevState; mPrevState = mState; mState = mTempState; mTempState = lTempState; // Apply the movement and rotation ApplyMovement(); ApplyRotation(); // Delay a bit before we update the speed if we're accelerating // or decelerating. mMecanimUpdateDelay -= Time.deltaTime; if (mMecanimUpdateDelay <= 0f) { mAnimator.SetFloat("Speed", mState.Speed); //, 0.05f, Time.deltaTime); mSpeedTrendStart = mState.Speed; } // Update the direction relative to the avatar mAnimator.SetFloat("Avatar Direction", mState.FromAvatarAngle); // At this point, we never use angular speed. Rotation is done // in the ApplyRotation() function. Angular speed currently only effects // locomotion. mAnimator.SetFloat("Angular Speed", 0f); // The stance determins if we're in exploration or combat mode. mAnimator.SetInteger("Stance", mStance); // The direction from the camera mAnimator.SetFloat("Camera Direction", mState.FromCameraAngle); //, 0.05f, Time.deltaTime); // The raw input from the UI mAnimator.SetFloat("Input X", mState.InputX); //, 0.25f, Time.deltaTime); mAnimator.SetFloat("Input Y", mState.InputY); //, 0.25f, Time.deltaTime); }
private void InitGridList() { var gridListProperties = new List <GridListControlProperties>(); gridListProperties.Add(new GridListControlProperties { Header = "No", Width = 30 }); gridListProperties.Add(new GridListControlProperties { Header = "Tanggal", Width = 90 }); gridListProperties.Add(new GridListControlProperties { Header = "Nota", Width = 90 }); gridListProperties.Add(new GridListControlProperties { Header = "Karyawan", Width = 230 }); gridListProperties.Add(new GridListControlProperties { Header = "Jumlah", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Sisa", Width = 100 }); gridListProperties.Add(new GridListControlProperties { Header = "Keterangan" }); GridListControlHelper.InitializeGridListControl <Kasbon>(this.gridList, _listOfKasbon, gridListProperties); if (_listOfKasbon.Count > 0) { this.gridList.SetSelected(0, true); GridListHandleSelectionChanged(this.gridList); } this.gridList.Grid.QueryCellInfo += delegate(object sender, GridQueryCellInfoEventArgs e) { if (_listOfKasbon.Count > 0) { if (e.RowIndex > 0) { var rowIndex = e.RowIndex - 1; if (rowIndex < _listOfKasbon.Count) { var kasbon = _listOfKasbon[rowIndex]; switch (e.ColIndex) { case 2: e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellValue = DateTimeHelper.DateToString(kasbon.tanggal); break; case 3: e.Style.CellValue = kasbon.nota; break; case 4: var karyawan = kasbon.Karyawan; if (karyawan != null) { e.Style.CellValue = kasbon.Karyawan.nama_karyawan; } break; case 5: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(kasbon.nominal); break; case 6: e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(kasbon.sisa); break; case 7: e.Style.CellValue = kasbon.keterangan; break; default: break; } // we handled it, let the grid know e.Handled = true; } } } }; this.gridList.SelectedValueChanged += delegate(object sender, EventArgs e) { GridListHandleSelectionChanged((GridListControl)sender); }; }
protected override void Simpan() { if (_isNewData) { _karyawan = new Karyawan(); } _karyawan.nama_karyawan = txtNama.Text; _karyawan.alamat = txtAlamat.Text; _karyawan.telepon = txtTelepon.Text; _karyawan.is_active = rdoAktif.Checked ? true : false; var jabatan = _listOfJabatan[cmbJabatan.SelectedIndex]; _karyawan.jabatan_id = jabatan.jabatan_id; _karyawan.Jabatan = jabatan; _karyawan.jenis_gajian = (JenisGajian)cmbJenisGaji.SelectedIndex; _karyawan.gaji_pokok = NumberHelper.StringToDouble(txtGajiPokok.Text); _karyawan.gaji_lembur = NumberHelper.StringToDouble(txtLembur.Text); var result = 0; var validationError = new ValidationError(); using (new StCursor(Cursors.WaitCursor, new TimeSpan(0, 0, 0, 0))) { if (_isNewData) { result = _bll.Save(_karyawan, ref validationError); } else { result = _bll.Update(_karyawan, ref validationError); } if (result > 0) { Listener.Ok(this, _isNewData, _karyawan); if (_isNewData) { base.ResetForm(this); txtNama.Focus(); } else { this.Close(); } } else { if (validationError.Message.NullToString().Length > 0) { MsgHelper.MsgWarning(validationError.Message); base.SetFocusObject(validationError.PropertyName, this); } else { MsgHelper.MsgUpdateError(); } } } }
protected override void Simpan() { if (this._customer == null || txtCustomer.Text.Length == 0) { MsgHelper.MsgWarning("'Customer' tidak boleh kosong !"); txtCustomer.Focus(); return; } var total = SumGrid(this._listOfItemJual); if (!(total > 0)) { MsgHelper.MsgWarning("Anda belum melengkapi inputan data produk !"); return; } if (rdoKredit.Checked) { if (!DateTimeHelper.IsValidRangeTanggal(dtpTanggal.Value, dtpTanggalTempo.Value)) { MsgHelper.MsgNotValidRangeTanggal(); return; } total = NumberHelper.StringToDouble(lblTotal.Text); if (this._customer != null) { if (this._customer.plafon_piutang > 0) { if (!(this._customer.plafon_piutang >= (total + this._customer.sisa_piutang))) { var msg = string.Empty; if (this._customer.sisa_piutang > 0) { msg = "Maaf, maksimal plafon piutang customer '{0}' adalah : {1}" + "\nSaat ini customer '{0}' masih mempunyai piutang sebesar : {2}"; msg = string.Format(msg, this._customer.nama_customer, NumberHelper.NumberToString(this._customer.plafon_piutang), NumberHelper.NumberToString(this._customer.sisa_piutang)); } else { msg = "Maaf, maksimal plafon piutang customer '{0}' adalah : {1}"; msg = string.Format(msg, this._customer.nama_customer, NumberHelper.NumberToString(this._customer.plafon_piutang)); } MsgHelper.MsgWarning(msg); return; } } } } if (!MsgHelper.MsgKonfirmasi("Apakah proses ingin dilanjutkan ?")) { return; } if (_isNewData) { _jual = new JualProduk(); } _jual.pengguna_id = this._pengguna.pengguna_id; _jual.Pengguna = this._pengguna; _jual.customer_id = this._customer.customer_id; _jual.Customer = this._customer; _jual.nota = txtNota.Text; _jual.tanggal = dtpTanggal.Value; _jual.tanggal_tempo = DateTimeHelper.GetNullDateTime(); _jual.is_tunai = rdoTunai.Checked; if (rdoKredit.Checked) // penjualan kredit { _jual.tanggal_tempo = dtpTanggalTempo.Value; } _jual.ppn = NumberHelper.StringToDouble(txtPPN.Text); _jual.diskon = NumberHelper.StringToDouble(txtDiskon.Text); _jual.keterangan = txtKeterangan.Text; _jual.item_jual = this._listOfItemJual.Where(f => f.Produk != null).ToList(); foreach (var item in _jual.item_jual) { if (!(item.harga_beli > 0)) { item.harga_beli = item.Produk.harga_beli; } if (!(item.harga_jual > 0)) { item.harga_jual = item.Produk.harga_jual; } } if (!_isNewData) // update { _jual.item_jual_deleted = _listOfItemJualDeleted; } var result = 0; var validationError = new ValidationError(); using (new StCursor(Cursors.WaitCursor, new TimeSpan(0, 0, 0, 0))) { if (_isNewData) { result = _bll.Save(_jual, ref validationError); } else { result = _bll.Update(_jual, ref validationError); } if (result > 0) { if (chkCetakNotaJual.Checked) { CetakNota(_jual.jual_id); } Listener.Ok(this, _isNewData, _jual); _customer = null; _listOfItemJual.Clear(); _listOfItemJualDeleted.Clear(); this.Close(); } else { if (validationError.Message.Length > 0) { MsgHelper.MsgWarning(validationError.Message); base.SetFocusObject(validationError.PropertyName, this); } else { MsgHelper.MsgUpdateError(); } } } }
private void InitGridList() { var gridListProperties = new List <GridListControlProperties>(); gridListProperties.Add(new GridListControlProperties { Header = "No", Width = 30 }); gridListProperties.Add(new GridListControlProperties { Header = "Nama", Width = 250 }); gridListProperties.Add(new GridListControlProperties { Header = "Alamat", Width = 300 }); gridListProperties.Add(new GridListControlProperties { Header = "Kontak", Width = 250 }); gridListProperties.Add(new GridListControlProperties { Header = "Telepon", Width = 130 }); gridListProperties.Add(new GridListControlProperties { Header = "Sisa Hutang", Width = 100 }); GridListControlHelper.InitializeGridListControl <Supplier>(this.gridList, _listOfSupplier, gridListProperties); if (_listOfSupplier.Count > 0) { this.gridList.SetSelected(0, true); } this.gridList.Grid.QueryCellInfo += delegate(object sender, GridQueryCellInfoEventArgs e) { if (_listOfSupplier.Count > 0) { if (e.RowIndex > 0) { var rowIndex = e.RowIndex - 1; if (rowIndex < _listOfSupplier.Count) { var supplier = _listOfSupplier[rowIndex]; switch (e.ColIndex) { case 2: e.Style.CellValue = supplier.nama_supplier; break; case 3: e.Style.CellValue = supplier.alamat; break; case 4: e.Style.CellValue = supplier.kontak; break; case 5: e.Style.CellValue = supplier.telepon; break; case 6: e.Style.CellValue = NumberHelper.NumberToString(supplier.total_hutang - supplier.total_pembayaran_hutang); e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; break; default: break; } // we handled it, let the grid know e.Handled = true; } } } }; }
public void Cetak(JualProduk jual, IList <HeaderNotaMiniPos> listOfHeaderNota, IList <FooterNotaMiniPos> listOfFooterNota, int jumlahKarakter, int lineFeed, bool isCetakCustomer = true) { var garisPemisah = StringHelper.PrintChar('=', jumlahKarakter); var textToPrint = new StringBuilder(); if (!Utils.IsRunningUnderIDE()) { textToPrint.Append(ESCCommandHelper.InitializePrinter()); textToPrint.Append(ESCCommandHelper.LineSpacing()); textToPrint.Append(ESCCommandHelper.CenterText()); } // cetak header foreach (var header in listOfHeaderNota) { if (header.keterangan.Length > 0) { header.keterangan = StringHelper.FixedLength(header.keterangan, garisPemisah.Length); textToPrint.Append(header.keterangan).Append(ESCCommandHelper.LineFeed(1)); } } // cetak garis textToPrint.Append(garisPemisah).Append(ESCCommandHelper.LineFeed(1)); if (!Utils.IsRunningUnderIDE()) { textToPrint.Append(ESCCommandHelper.LeftText()); } // set tanggal, jam, user var tanggal = StringHelper.FixedLength(DateTimeHelper.DateToString(DateTime.Now), 10); var jam = DateTimeHelper.TimeToString(DateTime.Now); var kasir = StringHelper.PrintChar(' ', (garisPemisah.Length - 18 - jual.Pengguna.nama_pengguna.Length) / 2) + jual.Pengguna.nama_pengguna; kasir = StringHelper.FixedLength(kasir, garisPemisah.Length - 18); // cetak tanggal, kasir, jam textToPrint.Append(tanggal); textToPrint.Append(kasir); // pengguna textToPrint.Append(jam).Append(ESCCommandHelper.LineFeed(2)); // jam // cetak info nota textToPrint.Append("Nota : ").Append(jual.nota).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append("Tanggal: ").Append(DateTimeHelper.DateToString(jual.tanggal)).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append("Tempo : ").Append(jual.tanggal_tempo == null ? "-" : DateTimeHelper.DateToString(jual.tanggal_tempo)).Append(ESCCommandHelper.LineFeed(1)); if (isCetakCustomer) { textToPrint.Append(ESCCommandHelper.LineFeed(1)); // cetak info customer textToPrint.Append("Kepada: ").Append(ESCCommandHelper.LineFeed(1)); var namaCustomer = jual.is_sdac == true ? jual.Customer.nama_customer : jual.kirim_kepada; var alamat = jual.is_sdac == true ? jual.Customer.alamat : jual.kirim_alamat; var telepon = jual.is_sdac == true ? jual.Customer.telepon : jual.kirim_telepon; textToPrint.Append(namaCustomer).Append(ESCCommandHelper.LineFeed(1)); if (alamat.Length > 0) { textToPrint.Append(alamat).Append(ESCCommandHelper.LineFeed(1)); } if (telepon.Length > 0) { textToPrint.Append("HP: " + telepon).Append(ESCCommandHelper.LineFeed(1)); } } // cetak garis textToPrint.Append(garisPemisah).Append(ESCCommandHelper.LineFeed(1)); // cetak item foreach (var item in jual.item_jual) { var produk = StringHelper.FixedLength(item.Produk.nama_produk, garisPemisah.Length); textToPrint.Append(produk).Append(ESCCommandHelper.LineFeed(1)); var jumlah = StringHelper.RightAlignment(item.jumlah.ToString(), 4); textToPrint.Append(jumlah); textToPrint.Append(" " + StringHelper.FixedLength("x", 3)); var harga = StringHelper.RightAlignment(NumberHelper.NumberToString(item.harga_jual), 10); textToPrint.Append(harga); var diskon = StringHelper.RightAlignment(item.diskon.ToString(), 7); textToPrint.Append(diskon); var subTotal = (item.jumlah - item.jumlah_retur) * item.harga_setelah_diskon; var sSubTotal = StringHelper.RightAlignment(NumberHelper.NumberToString(subTotal), garisPemisah.Length - 26); textToPrint.Append(sSubTotal).Append(ESCCommandHelper.LineFeed(1)); } // cetak garis textToPrint.Append(garisPemisah).Append(ESCCommandHelper.LineFeed(1)); var fixedLengthLabelFooter = 12; var fixedLengthValueFooter = garisPemisah.Length - fixedLengthLabelFooter - 3; // cetak footer if (jual.ongkos_kirim > 0) { textToPrint.Append(StringHelper.FixedLength("Kurir", fixedLengthLabelFooter)); textToPrint.Append(" : " + jual.kurir).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(StringHelper.FixedLength("Ongkos Kirim", fixedLengthLabelFooter)); textToPrint.Append(" : " + StringHelper.RightAlignment(NumberHelper.NumberToString(jual.ongkos_kirim), fixedLengthValueFooter)).Append(ESCCommandHelper.LineFeed(1)); } textToPrint.Append(StringHelper.FixedLength("Total Item", fixedLengthLabelFooter)); textToPrint.Append(" : " + StringHelper.RightAlignment(NumberHelper.NumberToString(jual.item_jual.Count), fixedLengthValueFooter)).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(StringHelper.FixedLength("Diskon", fixedLengthLabelFooter)); textToPrint.Append(" : " + StringHelper.RightAlignment(NumberHelper.NumberToString(jual.diskon), fixedLengthValueFooter)).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(StringHelper.FixedLength("PPN", fixedLengthLabelFooter)); textToPrint.Append(" : " + StringHelper.RightAlignment(NumberHelper.NumberToString(jual.ppn), fixedLengthValueFooter)).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(StringHelper.FixedLength("Total", fixedLengthLabelFooter)); textToPrint.Append(" : " + StringHelper.RightAlignment(NumberHelper.NumberToString(jual.grand_total), fixedLengthValueFooter)).Append(ESCCommandHelper.LineFeed(1)); if (jual.jumlah_bayar > 0) { textToPrint.Append(StringHelper.FixedLength("Jumlah Bayar", fixedLengthLabelFooter)); textToPrint.Append(" : " + StringHelper.RightAlignment(NumberHelper.NumberToString(jual.jumlah_bayar), fixedLengthValueFooter)).Append(ESCCommandHelper.LineFeed(1)); textToPrint.Append(StringHelper.FixedLength("Kembali", fixedLengthLabelFooter)); textToPrint.Append(" : " + StringHelper.RightAlignment(NumberHelper.NumberToString(jual.jumlah_bayar - jual.grand_total), fixedLengthValueFooter)).Append(ESCCommandHelper.LineFeed(1)); } // cetak garis textToPrint.Append(garisPemisah).Append(ESCCommandHelper.LineFeed(2)); if (!Utils.IsRunningUnderIDE()) { textToPrint.Append(ESCCommandHelper.CenterText()); } // cetak footer foreach (var footer in listOfFooterNota) { if (footer.keterangan.Length > 0) { footer.keterangan = StringHelper.FixedLength(footer.keterangan, garisPemisah.Length); textToPrint.Append(footer.keterangan).Append(ESCCommandHelper.LineFeed(1)); } } textToPrint.Append(ESCCommandHelper.LineFeed(lineFeed)); if (!Utils.IsRunningUnderIDE()) { RawPrinterHelper.SendStringToPrinter(_printerName, textToPrint.ToString()); } else { RawPrinterHelper.SendStringToFile(textToPrint.ToString()); } }
public static List <LogInfo> Hash(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_Hash info = cmd.Info.Cast <CodeInfo_Hash>(); string hashTypeStr = StringEscaper.Preprocess(s, info.HashType); string filePath = StringEscaper.Preprocess(s, info.FilePath); Debug.Assert(hashTypeStr != null, $"{nameof(hashTypeStr)} != null"); Debug.Assert(filePath != null, $"{nameof(filePath)} != null"); if (!File.Exists(filePath)) { return(LogInfo.LogErrorMessage(logs, $"File [{filePath}] does not exist")); } long reportInterval = 0; FileInfo fi = new FileInfo(filePath); long fileSize = fi.Length; // If file size is larger than 32MB, turn on progress report if (ReportThreshold <= fileSize) { // reportInterval should be times of 1MB reportInterval = NumberHelper.Round(fileSize / 32, ReportRound); // If reportInterval is larger than 128MB, limit to 128MB if (ReportIntervalMax < reportInterval) { reportInterval = ReportIntervalMax; } } string digest; HashHelper.HashType hashType = HashHelper.ParseHashType(hashTypeStr); if (0 < reportInterval) { s.MainViewModel.SetBuildCommandProgress("Hash Progress"); } try { IProgress <long> progress = new Progress <long>(pos => { double percent = (double)pos / fileSize * 100; s.MainViewModel.BuildCommandProgressValue = percent; s.MainViewModel.BuildCommandProgressText = $"Hashing {hashType}... ({percent:0.0}%)"; }); byte[] rawDigest; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { if (0 < reportInterval) { rawDigest = HashHelper.GetHash(hashType, fs, reportInterval, progress); } else { rawDigest = HashHelper.GetHash(hashType, fs); } } digest = StringHelper.ToHexStr(rawDigest); } finally { if (0 < reportInterval) { s.MainViewModel.ResetBuildCommandProgress(); } } logs.Add(new LogInfo(LogState.Success, $"Hash [{hashType}] digest of [{filePath}] is [{digest}]")); List <LogInfo> varLogs = Variables.SetVariable(s, info.DestVar, digest); logs.AddRange(varLogs); return(logs); }
private void InitGridControl(GridControl grid) { var gridListProperties = new List <GridListControlProperties>(); gridListProperties.Add(new GridListControlProperties { Header = "No", Width = 30 }); gridListProperties.Add(new GridListControlProperties { Header = "Jenis Pengeluaran", Width = 350 }); gridListProperties.Add(new GridListControlProperties { Header = "Jumlah", Width = 50 }); gridListProperties.Add(new GridListControlProperties { Header = "Harga", Width = 90 }); gridListProperties.Add(new GridListControlProperties { Header = "Sub Total", Width = 110 }); gridListProperties.Add(new GridListControlProperties { Header = "Aksi" }); GridListControlHelper.InitializeGridListControl <ItemPengeluaranBiaya>(grid, _listOfItemPengeluaran, gridListProperties); grid.PushButtonClick += delegate(object sender, GridCellPushButtonClickEventArgs e) { if (e.ColIndex == 6) { if (grid.RowCount == 1) { MsgHelper.MsgWarning("Minimal 1 item pengeluaran harus diinputkan !"); return; } if (MsgHelper.MsgDelete()) { var itemPengeluaran = _listOfItemPengeluaran[e.RowIndex - 1]; itemPengeluaran.entity_state = EntityState.Deleted; _listOfItemPengeluaranDeleted.Add(itemPengeluaran); _listOfItemPengeluaran.Remove(itemPengeluaran); grid.RowCount = _listOfItemPengeluaran.Count(); grid.Refresh(); RefreshTotal(); } } }; grid.QueryCellInfo += delegate(object sender, GridQueryCellInfoEventArgs e) { // Make sure the cell falls inside the grid if (e.RowIndex > 0) { if (!(_listOfItemPengeluaran.Count > 0)) { return; } var itemPengeluaran = _listOfItemPengeluaran[e.RowIndex - 1]; var jenisPengeluaran = itemPengeluaran.JenisPengeluaran; if (e.RowIndex % 2 == 0) { e.Style.BackColor = ColorCollection.BACK_COLOR_ALTERNATE; } switch (e.ColIndex) { case 1: // no urut e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.Enabled = false; e.Style.CellValue = e.RowIndex.ToString(); break; case 2: // nama jenis pengeluaran if (jenisPengeluaran != null) { e.Style.CellValue = jenisPengeluaran.nama_jenis_pengeluaran; } break; case 3: // jumlah e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellValue = itemPengeluaran.jumlah; break; case 4: // harga e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.CellValue = NumberHelper.NumberToString(itemPengeluaran.harga); break; case 5: // subtotal e.Style.HorizontalAlignment = GridHorizontalAlignment.Right; e.Style.Enabled = false; e.Style.CellValue = NumberHelper.NumberToString(itemPengeluaran.jumlah * itemPengeluaran.harga); break; case 6: // button hapus e.Style.HorizontalAlignment = GridHorizontalAlignment.Center; e.Style.CellType = GridCellTypeName.PushButton; e.Style.Enabled = true; e.Style.Description = "Hapus"; break; default: break; } e.Handled = true; // we handled it, let the grid know } }; var colIndex = 2; // kolom nama produk grid.CurrentCell.MoveTo(1, colIndex, GridSetCurrentCellOptions.BeginEndUpdate); }
/// <summary> /// PEBakery uses 1-based index for concated list /// </summary> /// <param name="s"></param> /// <param name="cmd"></param> /// <returns></returns> public static List <LogInfo> List(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_List info = cmd.Info.Cast <CodeInfo_List>(); string listStr = string.Empty; string listVar = info.SubInfo.ListVar; if (Variables.ContainsKey(s, listVar) == true) { listStr = StringEscaper.Preprocess(s, listVar); } ListType type = info.Type; string delimiter = "|"; switch (type) { case ListType.Get: { ListInfo_Get subInfo = info.SubInfo.Cast <ListInfo_Get>(); string indexStr = StringEscaper.Preprocess(s, subInfo.Index); if (!NumberHelper.ParseInt32(indexStr, out int index)) { return(LogInfo.LogErrorMessage(logs, $"[{indexStr}] is not a valid positive integer")); } if (index <= 0) { return(LogInfo.LogErrorMessage(logs, $"[{indexStr}] is not a valid positive integer")); } if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); string destStr = list[index - 1]; List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destStr); logs.AddRange(varLogs); } break; case ListType.Set: { ListInfo_Set subInfo = info.SubInfo.Cast <ListInfo_Set>(); string indexStr = StringEscaper.Preprocess(s, subInfo.Index); string item = StringEscaper.Preprocess(s, subInfo.Item); if (!NumberHelper.ParseInt32(indexStr, out int index)) { return(LogInfo.LogErrorMessage(logs, $"[{indexStr}] is not a valid positive integer")); } if (index <= 0) { return(LogInfo.LogErrorMessage(logs, $"[{indexStr}] is not a valid positive integer")); } if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); list[index - 1] = item; listStr = StringEscaper.PackListStr(list, delimiter); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.ListVar, listStr); logs.AddRange(varLogs); } break; case ListType.Append: { ListInfo_Append subInfo = info.SubInfo.Cast <ListInfo_Append>(); string item = StringEscaper.Preprocess(s, subInfo.Item); if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); list.Add(item); listStr = StringEscaper.PackListStr(list, delimiter); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.ListVar, listStr); logs.AddRange(varLogs); } break; case ListType.Insert: { ListInfo_Insert subInfo = info.SubInfo.Cast <ListInfo_Insert>(); string indexStr = StringEscaper.Preprocess(s, subInfo.Index); string item = StringEscaper.Preprocess(s, subInfo.Item); if (!NumberHelper.ParseInt32(indexStr, out int index)) { return(LogInfo.LogErrorMessage(logs, $"[{indexStr}] is not a valid positive integer")); } if (index <= 0) { return(LogInfo.LogErrorMessage(logs, $"[{indexStr}] is not a valid positive integer")); } if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); list.Insert(index - 1, item); listStr = StringEscaper.PackListStr(list, delimiter); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.ListVar, listStr); logs.AddRange(varLogs); } break; case ListType.Remove: case ListType.RemoveX: { ListInfo_Remove subInfo = info.SubInfo.Cast <ListInfo_Remove>(); string item = StringEscaper.Preprocess(s, subInfo.Item); if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); StringComparison comp; switch (type) { case ListType.Remove: comp = StringComparison.OrdinalIgnoreCase; break; case ListType.RemoveX: comp = StringComparison.Ordinal; break; default: throw new InternalException("Internal Logic Error at CommandList"); } int deletedItemCount = list.RemoveAll(x => x.Equals(item, comp)); if (0 < deletedItemCount) { logs.Add(new LogInfo(LogState.Success, $"[{deletedItemCount}] items were deleted")); listStr = StringEscaper.PackListStr(list, delimiter); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.ListVar, listStr); logs.AddRange(varLogs); } else { logs.Add(new LogInfo(LogState.Ignore, "No items were deleted")); } } break; case ListType.RemoveAt: { ListInfo_RemoveAt subInfo = info.SubInfo.Cast <ListInfo_RemoveAt>(); string indexStr = StringEscaper.Preprocess(s, subInfo.Index); if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } if (!NumberHelper.ParseInt32(indexStr, out int index)) { return(LogInfo.LogErrorMessage(logs, $"[{indexStr}] is not a valid positive integer")); } if (index <= 0) { return(LogInfo.LogErrorMessage(logs, $"[{indexStr}] is not a valid positive integer")); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); list.RemoveAt(index - 1); listStr = StringEscaper.PackListStr(list, delimiter); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.ListVar, listStr); logs.AddRange(varLogs); } break; case ListType.Count: { ListInfo_Count subInfo = info.SubInfo.Cast <ListInfo_Count>(); if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); int destInt = list.Count; List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destInt.ToString()); logs.AddRange(varLogs); } break; case ListType.Pos: case ListType.PosX: case ListType.LastPos: case ListType.LastPosX: { ListInfo_Pos subInfo = info.SubInfo.Cast <ListInfo_Pos>(); string item = StringEscaper.Preprocess(s, subInfo.Item); if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); int destInt; switch (type) { case ListType.Pos: destInt = list.FindIndex(x => x.Equals(item, StringComparison.OrdinalIgnoreCase)); break; case ListType.PosX: destInt = list.FindIndex(x => x.Equals(item, StringComparison.Ordinal)); break; case ListType.LastPos: destInt = list.FindLastIndex(x => x.Equals(item, StringComparison.OrdinalIgnoreCase)); break; case ListType.LastPosX: destInt = list.FindLastIndex(x => x.Equals(item, StringComparison.Ordinal)); break; default: throw new InternalException("Internal Logic Error at CommandList"); } destInt += 1; List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destInt.ToString()); logs.AddRange(varLogs); } break; case ListType.Sort: case ListType.SortX: case ListType.SortN: case ListType.SortNX: { ListInfo_Sort subInfo = info.SubInfo.Cast <ListInfo_Sort>(); string order = StringEscaper.Preprocess(s, subInfo.Order); if (subInfo.Delim != null) { delimiter = StringEscaper.Preprocess(s, subInfo.Delim); } bool reverse; if (order.Equals("ASC", StringComparison.OrdinalIgnoreCase)) { reverse = false; } else if (order.Equals("DESC", StringComparison.OrdinalIgnoreCase)) { reverse = true; } else { return(LogInfo.LogErrorMessage(logs, "Order must be [ASC] or [DESC]")); } List <string> list = StringEscaper.UnpackListStr(listStr, delimiter); switch (type) { case ListType.Sort: list = list .OrderBy(x => x, StringComparer.OrdinalIgnoreCase) .ThenBy(x => x, StringComparer.Ordinal) .ToList(); break; case ListType.SortX: list.Sort(StringComparer.Ordinal); break; case ListType.SortN: list = list .OrderBy(x => x, StringComparer.OrdinalIgnoreCase.WithNaturalSort()) .ThenBy(x => x, StringComparer.Ordinal.WithNaturalSort()) .ToList(); break; case ListType.SortNX: list.Sort(StringComparer.Ordinal.WithNaturalSort()); break; default: throw new InternalException("Internal Logic Error at CommandList"); } if (reverse) { list.Reverse(); } listStr = StringEscaper.PackListStr(list, delimiter); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.ListVar, listStr); logs.AddRange(varLogs); } break; default: // Error throw new InternalException("Internal Logic Error at CommandList"); } return(logs); }
/// <summary> /// Converts the nav mesh agent data into psuedo-input that the motion controller /// will use to drive animations. /// </summary> protected void SimulateInput() { float lDeltaTime = TimeManager.SmoothedDeltaTime; // Direction we need to travel in Vector3 lDirection = mWaypointVector; lDirection.y = lDirection.y - _PathHeight; lDirection.Normalize(); // Determine our view Vector3 lVerticalDirection = Vector3.Project(lDirection, _Transform.up); Vector3 lLateralDirection = lDirection - lVerticalDirection; mInputFromAvatarAngle = Vector3Ext.SignedAngle(_Transform.forward, lLateralDirection); // Determine how much we simulate the view x. We temper it to make it smooth float lYawAngleAbs = Mathf.Min(Mathf.Abs(mInputFromAvatarAngle * lDeltaTime), mViewSpeedPer60FPSTick * lDeltaTime); if (lYawAngleAbs < EPSILON) { lYawAngleAbs = 0f; } mViewX = Mathf.Sign(mInputFromAvatarAngle) * lYawAngleAbs; // Determine our movement if (mTargetDistance > _StopDistance) { // Calculate our own slowing float lRelativeMoveSpeed = 1f; if (mIsInSlowDistance && _SlowFactor > 0f) { float lSlowPercent = (mTargetDistance - _StopDistance) / (_SlowDistance - _StopDistance); lRelativeMoveSpeed = ((1f - _SlowFactor) * lSlowPercent) + _SlowFactor; } // TRT 4/5/2016: Force the slow distance as an absolute value if (mIsInSlowDistance && _SlowFactor > 0f) { lRelativeMoveSpeed = _SlowFactor; } mMovementY = 1f * lRelativeMoveSpeed; } // Grab extra input information if we can if (mMotionController._CameraTransform == null) { mInputFromCameraAngle = mInputFromAvatarAngle; } else { Vector3 lInputForward = new Vector3(mMovementX, 0f, mMovementY); // We do the inverse tilt so we calculate the rotation in "natural up" space vs. "actor up" space. Quaternion lInvTilt = QuaternionExt.FromToRotation(_Transform.up, Vector3.up); // Camera forward in "natural up" Vector3 lCameraForward = lInvTilt * mMotionController._CameraTransform.forward; // Create a quaternion that gets us from our world-forward to our camera direction. Quaternion lToCamera = Quaternion.LookRotation(lCameraForward, lInvTilt * _Transform.up); // Transform joystick from world space to camera space. Now the input is relative // to how the camera is facing. Vector3 lMoveDirection = lToCamera * lInputForward; mInputFromCameraAngle = NumberHelper.GetHorizontalAngle(lCameraForward, lMoveDirection); } }
private void RefreshTotal() { lblTotal.Text = NumberHelper.NumberToString(SumGrid(_listOfItemPembayaranPiutang)); }
public static List <LogInfo> WimMount(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(1); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_WimMount)); CodeInfo_WimMount info = cmd.Info as CodeInfo_WimMount; string srcWim = StringEscaper.Preprocess(s, info.SrcWim); string imageIndexStr = StringEscaper.Preprocess(s, info.ImageIndex); string mountDir = StringEscaper.Preprocess(s, info.MountDir); // Check srcWim if (!File.Exists(srcWim)) { logs.Add(new LogInfo(LogState.Error, $"File [{srcWim}] does not exist")); return(logs); } // Check MountDir if (StringEscaper.PathSecurityCheck(mountDir, out string errorMsg) == false) { logs.Add(new LogInfo(LogState.Error, errorMsg)); return(logs); } if (!Directory.Exists(mountDir)) { logs.Add(new LogInfo(LogState.Error, $"Directory [{mountDir}] does not exist")); return(logs); } // Check imageIndex int imageCount = 0; try { using (WimHandle hWim = WimgApi.CreateFile(srcWim, WimFileAccess.Query, WimCreationDisposition.OpenExisting, WimCreateFileOptions.None, WimCompressionType.None)) { WimgApi.SetTemporaryPath(hWim, Path.GetTempPath()); imageCount = WimgApi.GetImageCount(hWim); } } catch (Win32Exception e) { logs.Add(new LogInfo(LogState.Error, $"Unable to get information of [{srcWim}]\r\nError Code [0x{e.ErrorCode:X8}]\r\nNative Error Code [0x{e.NativeErrorCode:X8}]\r\n")); return(logs); } if (!NumberHelper.ParseInt32(imageIndexStr, out int imageIndex)) { logs.Add(new LogInfo(LogState.Error, $"[{imageIndexStr}] is not a valid a positive integer")); return(logs); } if (!(1 <= imageIndex && imageIndex <= imageCount)) { logs.Add(new LogInfo(LogState.Error, $"[{imageIndexStr}] must be [1] ~ [{imageCount}]")); return(logs); } // Mount Wim try { using (WimHandle hWim = WimgApi.CreateFile(srcWim, WimFileAccess.Mount | WimFileAccess.Read, WimCreationDisposition.OpenExisting, WimCreateFileOptions.None, WimCompressionType.None)) { WimgApi.SetTemporaryPath(hWim, Path.GetTempPath()); WimgApi.RegisterMessageCallback(hWim, WimgApiCallback); try { using (WimHandle hImage = WimgApi.LoadImage(hWim, imageIndex)) { s.MainViewModel.BuildCommandProgressTitle = "WimMount Progress"; s.MainViewModel.BuildCommandProgressText = string.Empty; s.MainViewModel.BuildCommandProgressMax = 100; s.MainViewModel.BuildCommandProgressShow = true; // Mount Wim WimgApi.MountImage(hImage, mountDir, WimMountImageOptions.ReadOnly); } } finally { s.MainViewModel.BuildCommandProgressShow = false; s.MainViewModel.BuildCommandProgressTitle = "Progress"; s.MainViewModel.BuildCommandProgressText = string.Empty; s.MainViewModel.BuildCommandProgressValue = 0; WimgApi.UnregisterMessageCallback(hWim, WimgApiCallback); } } } catch (Win32Exception e) { logs.Add(new LogInfo(LogState.Error, $"Unable to mount [{srcWim}]\r\nError Code [0x{e.ErrorCode:X8}]\r\nNative Error Code [0x{e.NativeErrorCode:X8}]\r\n")); return(logs); } logs.Add(new LogInfo(LogState.Success, $"[{srcWim}]'s image [{imageIndex}] mounted to [{mountDir}]")); return(logs); }
/// <summary> /// LateUpdate logic for the controller should be done here. This allows us /// to support dynamic and fixed update times /// </summary> /// <param name="rDeltaTime">Time since the last frame (or fixed update call)</param> /// <param name="rUpdateIndex">Index of the update to help manage dynamic/fixed updates. [0: Invalid update, >=1: Valid update]</param> public override void RigLateUpdate(float rDeltaTime, int rUpdateIndex) { Vector3 lNewAnchorPosition = _Anchor.position + (_Anchor.rotation * _AnchorOffset); Vector3 lNewCameraPosition = _Transform.position; Quaternion lNewCameraRotation = _Transform.rotation; // If we're locking foward, don't process any rotations if (mFrameLockForward) { mFrameLockForward = false; } // At certain times, we may force the rig to face the direction of the actor else if (_FrameForceToFollowAnchor) { // Grab the rotation amount. We do the inverse tilt so we calculate the rotation in // "natural up" space. Later we'll use the tilt to put it back into "anchor up" space. Quaternion lInvTilt = QuaternionExt.FromToRotation(_Anchor.up, Vector3.up); // Determine the global direction the character should face float lAngle = NumberHelper.GetHorizontalAngle(_Transform.forward, _Anchor.forward, _Anchor.up); Quaternion lYaw = Quaternion.AngleAxis(lAngle, lInvTilt * _Anchor.up); // Pitch is more complicated since we can't go beyond the north/south pole Quaternion lPitch = Quaternion.identity; if (mInputSource.IsViewingActivated) { float lPitchAngle = Vector3.Angle(mToCameraDirection, lInvTilt * _Anchor.up); float lPitchDelta = (_InvertPitch ? -1f : 1f) * mInputSource.ViewY; if (lPitchAngle < MIN_PITCH && lPitchDelta > 0f) { lPitchDelta = 0f; } else if (lPitchAngle > MAX_PITCH && lPitchDelta < 0f) { lPitchDelta = 0f; } lPitch = Quaternion.AngleAxis(lPitchDelta, lInvTilt * _Transform.right); } // Calculate the new "natural up" direction mToCameraDirection = lPitch * lYaw * mToCameraDirection; // Update our tilt to match the anchor's tilt mTilt = QuaternionExt.FromToRotation(mTilt.Up(), _Anchor.up) * mTilt; // Put the new direction relative to the anchor's tilt Vector3 lToCameraDirection = mTilt * mToCameraDirection; if (lToCameraDirection.sqrMagnitude == 0f) { lToCameraDirection = -_Anchor.forward; } // Calculate the new orbit center (anchor) and camera position lNewCameraPosition = lNewAnchorPosition + (lToCameraDirection.normalized * _Radius); lNewCameraRotation = Quaternion.LookRotation(lNewAnchorPosition - lNewCameraPosition, _Anchor.up); // Disable the force _FrameForceToFollowAnchor = false; } // If we're not forcing a follow, do our normal processing else { if (mInputSource.IsViewingActivated) { // Grab the rotation amount. We do the inverse tilt so we calculate the rotation in // "natural up" space. Later we'll use the tilt to put it back into "anchor up" space. Quaternion lInvTilt = QuaternionExt.FromToRotation(_Anchor.up, Vector3.up); // Yaw is simple as we can go 360 Quaternion lYaw = Quaternion.AngleAxis(mInputSource.ViewX * mDegreesPer60FPSTick, lInvTilt * _Transform.up); // Pitch is more complicated since we can't go beyond the north/south pole float lPitchAngle = Vector3.Angle(mToCameraDirection, lInvTilt * _Anchor.up); float lPitchDelta = (_InvertPitch ? -1f : 1f) * mInputSource.ViewY; if (lPitchAngle < MIN_PITCH && lPitchDelta > 0f) { lPitchDelta = 0f; } else if (lPitchAngle > MAX_PITCH && lPitchDelta < 0f) { lPitchDelta = 0f; } Quaternion lPitch = Quaternion.AngleAxis(lPitchDelta, lInvTilt * _Transform.right); // Calculate the new "natural up" direction mToCameraDirection = lPitch * lYaw * mToCameraDirection; } // Update our tilt to match the anchor's tilt mTilt = QuaternionExt.FromToRotation(mTilt.Up(), _Anchor.up) * mTilt; // Put the new direction relative to the anchor's tilt Vector3 lToCameraDirection = mTilt * mToCameraDirection; if (lToCameraDirection.sqrMagnitude == 0f) { lToCameraDirection = -_Anchor.forward; } // Calculate the new orbit center (anchor) and camera position lNewCameraPosition = lNewAnchorPosition + (lToCameraDirection.normalized * _Radius); lNewCameraRotation = Quaternion.LookRotation(lNewAnchorPosition - lNewCameraPosition, _Anchor.up); } // Set the values _Transform.position = lNewCameraPosition; _Transform.rotation = lNewCameraRotation; }
/// <summary> /// This function is used to convert the game control stick value to /// speed and direction values for the player. /// </summary> protected void StickToWorldspace(Transform rController, Transform rCamera, ref AdventureControllerState rState) { if (mInputSource == null) { return; } // Grab the movement, but create a bit of a dead zone float lHInput = mInputSource.MovementX; float lVInput = mInputSource.MovementY; // Get out early if we can simply this if (lVInput == 0f && lHInput == 0f) { rState.Speed = 0f; rState.FromAvatarAngle = 0f; rState.InputX = 0f; rState.InputY = 0f; return; } // Determine the relative speed rState.Speed = Mathf.Sqrt((lHInput * lHInput) + (lVInput * lVInput)); // Create a simple vector off of our stick input and get the speed sVector3A.x = lHInput; sVector3A.y = 0f; sVector3A.z = lVInput; // Direction of the avatar Vector3 lControllerForward = rController.forward; lControllerForward.y = 0f; lControllerForward.Normalize(); // Direction of the camera Vector3 lCameraForward = rCamera.forward; lCameraForward.y = 0f; lCameraForward.Normalize(); // Create a quaternion that gets us from our world-forward to our camera direction. // FromToRotation creates a quaternion using the shortest method which can sometimes // flip the angle. LookRotation will attempt to keep the "up" direction "up". //Quaternion rToCamera = Quaternion.FromToRotation(Vector3.forward, Vector3.Normalize(lCameraForward)); Quaternion rToCamera = Quaternion.LookRotation(lCameraForward); // Transform joystick from world space to camera space. Now the input is relative // to how the camera is facing. Vector3 lMoveDirection = rToCamera * sVector3A; rState.FromCameraAngle = NumberHelper.GetHorizontalAngle(lCameraForward, lMoveDirection); rState.FromAvatarAngle = NumberHelper.GetHorizontalAngle(lControllerForward, lMoveDirection); // Set the direction of the movement in ranges of -1 to 1 rState.InputX = lHInput; rState.InputY = lVInput; //Debug.DrawRay(new Vector3(rController.position.x, rController.position.y + 2f, rController.position.z), lControllerForward, Color.gray); //Debug.DrawRay(new Vector3(rController.position.x, rController.position.y + 2f, rController.position.z), lMoveDirection, Color.green); }
private void RefreshTotal() { lblTotal.Text = NumberHelper.NumberToString(SumGrid(_listOfItemBeli)); }
private bool TryReadParsedOfStr <T>(out T value) { value = default; var strBytesLength = TryReadStringHead(); if (strBytesLength > 0) { ReadStringToHGlobal(strBytesLength); if (typeof(T) == typeof(DateTime) && DateTimeHelper.TryParseISODateTime(hGlobal.GetPointer(), hGlobal.Count, out Unsafe.As <T, DateTime>(ref value))) { return(true); } if (typeof(T) == typeof(DateTimeOffset) && DateTimeHelper.TryParseISODateTime(hGlobal.GetPointer(), hGlobal.Count, out Unsafe.As <T, DateTimeOffset>(ref value))) { return(true); } if (typeof(T) == typeof(Guid) && NumberHelper.TryParse(hGlobal.GetPointer(), hGlobal.Count, out Unsafe.As <T, Guid>(ref value)) == hGlobal.Count) { return(true); } if (typeof(T) == typeof(decimal)) { var num = NumberHelper.TryParse(hGlobal.GetPointer(), hGlobal.Count, out Unsafe.As <T, decimal>(ref value)); if (num != hGlobal.Count) { var numberInfo = NumberHelper.GetNumberInfo(hGlobal.GetPointer(), hGlobal.Count, 10); if (numberInfo.IsNumber) { Unsafe.As <T, decimal>(ref value) = numberInfo.ToDecimal(); num = numberInfo.End; } } if (num == hGlobal.Count) { return(true); } } if (typeof(T) == typeof(double)) { var num = NumberHelper.Decimal.TryParse(hGlobal.GetPointer(), hGlobal.Count, out Unsafe.As <T, double>(ref value)); if (num != hGlobal.Count) { var numberInfo = NumberHelper.GetNumberInfo(hGlobal.GetPointer(), hGlobal.Count, 10); if (numberInfo.IsNumber) { Unsafe.As <T, double>(ref value) = numberInfo.ToDouble(); num = numberInfo.End; } } if (num == hGlobal.Count) { return(true); } } if (typeof(T) == typeof(long)) { var num = NumberHelper.Decimal.TryParse(hGlobal.GetPointer(), hGlobal.Count, out Unsafe.As <T, long>(ref value)); if (num != hGlobal.Count) { var numberInfo = NumberHelper.GetNumberInfo(hGlobal.GetPointer(), hGlobal.Count, 10); if (numberInfo.IsNumber) { Unsafe.As <T, long>(ref value) = numberInfo.ToInt64(); num = numberInfo.End; } } if (num == hGlobal.Count) { return(true); } } if (typeof(T) == typeof(ulong)) { var num = NumberHelper.Decimal.TryParse(hGlobal.GetPointer(), hGlobal.Count, out Unsafe.As <T, ulong>(ref value)); if (num != hGlobal.Count) { var numberInfo = NumberHelper.GetNumberInfo(hGlobal.GetPointer(), hGlobal.Count, 10); if (numberInfo.IsNumber) { Unsafe.As <T, ulong>(ref value) = numberInfo.ToUInt64(); num = numberInfo.End; } } if (num == hGlobal.Count) { return(true); } } var str = new string(hGlobal.GetPointer(), 0, hGlobal.Count); if (typeof(T) == typeof(DateTime)) { Unsafe.As <T, DateTime>(ref value) = DateTime.Parse(str); return(true); } if (typeof(T) == typeof(DateTimeOffset)) { Unsafe.As <T, DateTimeOffset>(ref value) = DateTimeOffset.Parse(str); return(true); } if (typeof(T) == typeof(Guid)) { Unsafe.As <T, Guid>(ref value) = new Guid(str); return(true); } if (typeof(T) == typeof(decimal)) { Unsafe.As <T, decimal>(ref value) = decimal.Parse(str); return(true); } if (typeof(T) == typeof(double)) { Unsafe.As <T, double>(ref value) = double.Parse(str); return(true); } if (typeof(T) == typeof(long)) { Unsafe.As <T, long>(ref value) = long.Parse(str); return(true); } if (typeof(T) == typeof(ulong)) { Unsafe.As <T, ulong>(ref value) = ulong.Parse(str); return(true); } //value = XConvert<T>.Convert(str); //return true; } return(false); }