private ConfigRequest ParseConfigRequest(String[] partes) { var crq = new ConfigRequest(Id, 0) { GeoPoint = null }; var res = String.Format("H9;{0:D5}", Id); res += res.TakeWhile(b => b != '@').Aggregate <char, byte>(0, (current, b) => (byte)(current + b)).ToString("X2"); crq.AddStringToSend(res); crq.StringParameters.Add(Indication.indicatedIMEI, partes[1]); crq.StringParameters.Add(Indication.indicatedSecret, partes[2]); crq.StringParameters.Add(Indication.indicatedFirmwareSignature, partes[3]); if (partes.Length > 4) { crq.IntegerParameters.Add(Indication.indicatedConfigurationRevision, SafeConvert.ToInt32(partes[4], -1)); } if (partes.Length > 5) { crq.IntegerParameters.Add(Indication.indicatedCannedMessagesTableRevision, SafeConvert.ToInt32(partes[5], -1)); } return(crq); }
public List <DbColumn> GetDbColumns(string database, string table) { List <DbColumn> list = new List <DbColumn>(); DataTable dt = MySqlHelper.ExecuteDataset(ConnString, string.Format("SELECT * FROM `COLUMNS` WHERE TABLE_SCHEMA='{0}' AND TABLE_NAME='{1}';", database, table)).Tables[0]; foreach (DataRow row in dt.Rows) { list.Add(new DbColumn { ByteLength = SafeConvert.ToInt32(row["CHARACTER_OCTET_LENGTH"]), CharLength = SafeConvert.ToInt32(row["CHARACTER_MAXIMUM_LENGTH"]), ColumnName = row["COLUMN_NAME"].ToString(), ColumnType = row["DATA_TYPE"].ToString(), IsIdentity = row["EXTRA"].ToString() == "auto_increment", IsNullable = row["IS_NULLABLE"].ToString() == "YES", IsPrimaryKey = row["COLUMN_KEY"].ToString() == "PRI", Remark = row["COLUMN_COMMENT"].ToString(), //Precision = SafeConvert.ToInt32(row["NUMERIC_PRECISION"]), Scale = SafeConvert.ToInt32(row["NUMERIC_SCALE"]), CSharpType = MySqlDbMap.CsharpType(row["DATA_TYPE"].ToString()), JavaType = MySqlDbMap.JavaType(row["DATA_TYPE"].ToString()), }); } return(list); }
public override INode Factory(IFrame frame, int formerId) { if (frame.Payload.Length < 2) { return(null); } var s = Encoding.ASCII.GetString(frame.Payload, 0, frame.Payload.Length); if (s.StartsWith("G")) { STrace.Debug(typeof(Parser).FullName, formerId, "Ack Unex V1 sin dispositivo (GA)"); return(DataProvider.Get(formerId, this)); } if (frame.Payload[0] == 'H' && frame.Payload[1] == '0') { return(DataProvider.FindByIMEI(s.Substring(24, 16), this)); } var did = "0"; if (s.StartsWith("E")) { did = s.Substring(3, 5); } if (s.StartsWith("Q")) { did = s.Substring(2, 5); } if (s.StartsWith("K") && s.Length > 6) { did = s.Substring(1, 5); } return(DataProvider.Get(SafeConvert.ToInt32(did, 0), this)); }
public static string GetDeviceType(object o) { int deviceType = SafeConvert.ToInt32(o, 1); string str = "ico-pc"; switch (deviceType) { case 1: str = "ico-pc"; break; case 2: str = "ico-android"; break; case 3: str = "ico-apple"; break; case 5: str = "ico-weixin"; break; } return(str); }
public IEnumerable <Store> GetStores() { try { var stores = new List <Store>(); using (var connection = new OdbcConnection(this.ConnetionString)) { connection.Open(); var query = $@"SELECT * FROM storeHDR"; var command = new OdbcCommand(query); command.Connection = connection; using (var reader = command.ExecuteReader()) { while (reader.Read()) { stores.Add(new Store { No = SafeConvert.ToInt32(reader["No"]), Name = SafeConvert.ToString(reader["Name"]) }); } } return(stores); } } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } }
public bool ingresoCredito() { CreditoClass creditoDB = new CreditoClass(); creditoDB.TransacionId = 1; creditoDB.NumeroTC = SafeConvert.ToInt32(txtNumTC.Text); creditoDB.TipoTC = "TC"; creditoDB.Cuotas = SafeConvert.ToInt32(numericCuotas.Value); creditoDB.NumeroOperacion = SafeConvert.ToInt32(txtNumOperacion.Text); creditoDB.Monto = SafeConvert.ToInt32(txtMonto.Text); creditoDB.Autorizacion = SafeConvert.ToInt32(txtAutorizacion.Text); StringBuilder sb = new StringBuilder(); sb.AppendFormat("INSERT INTO bes_credito (transaction_id,num_tc,tipo_tc,cuotas,num_operacion,monto,autorizacion) VALUES ({0},{1},{2},{3},{4},{5},{6})", creditoDB.TransacionId, creditoDB.NumeroTC, SqlHelper.Quote(creditoDB.TipoTC), creditoDB.Cuotas, creditoDB.NumeroOperacion, creditoDB.Monto, creditoDB.Autorizacion); int num = BL.DB.ExecuteNonQuery(sb.ToString()); if (num > 0) { BL.MsgInfo("Se ha Ingresado una Transaccion"); return(true); } return(false); }
public void SetupForm(BLogic BL) { this.BL = BL; UserInterfaceHelper.TranslateForm(this); UserInterfaceHelper.CenterWindow(this); UserInterfaceHelper.VisibleForms.Add(this); DataTable bancos = BL.DB.ExecuteDataTable("SELECT id, description FROM bes_banks WHERE status=0 ORDER BY description"); int contador = bancos.Rows.Count; var dataSource = new List <TestObject>(); foreach (DataRow banco in bancos.Rows) { String description = banco["description"].ToString(); int id = SafeConvert.ToInt32(banco["id"]); dataSource.Add(new TestObject() { Name = description, Value = id }); } this.x_banco_cheque.DataSource = dataSource; this.x_banco_cheque.DisplayMember = "Name"; this.x_banco_cheque.ValueMember = "Value"; this.x_banco_cheque.DropDownStyle = ComboBoxStyle.DropDownList; // Dia for (int i = 1; i <= 31; i++) { x_dia_cheque.Items.Add(i.ToString()); } // Mes for (int i = 1; i <= 12; i++) { x_mes_cheque.Items.Add(i.ToString()); } // Año for (int i = 2016; i <= 2018; i++) { x_anio_cheque.Items.Add(i.ToString()); } // Colores --> Verde: #2a9800 - Rojo: #d74a2b - Naranja: #ffa909 aceptar.BackColor = ColorTranslator.FromHtml("#2a9800"); cancelar.BackColor = ColorTranslator.FromHtml("#d74a2b"); // Valores de Prueba por Defecto x_numero_cheque.Text = "0987654"; //x_tasas_interes.Text = "2"; rut_cheque.Text = "12345678A"; x_nombre_completo_cheque.Text = "Domingo José Ilarreta Heydras"; x_dia_cheque.Text = DateTime.Now.ToString("dd"); x_mes_cheque.Text = DateTime.Now.ToString("MM"); x_anio_cheque.Text = DateTime.Now.ToString("yyyy"); nro_cta_corriente.Text = "09876543"; x_cod_auth_cheque.Text = "098768000000"; x_monto.Text = BL.CurrentTransaction.FoodToPay().ToString(); }
public void TestNoOverflows() { XAssert.AreEqual(0, SafeConvert.ToInt32(double.MaxValue), "bigInt"); XAssert.AreEqual(0, SafeConvert.ToInt32(double.MinValue), "smallInt"); XAssert.AreEqual(15, SafeConvert.ToInt32(15.3234)); XAssert.AreEqual(0, SafeConvert.ToLong(double.MaxValue), "bigLong"); XAssert.AreEqual(0, SafeConvert.ToLong(double.MinValue), "smallLong"); XAssert.AreEqual(15, SafeConvert.ToLong(15.3234)); }
public override void Execute() { this.WriteHeader(); this.AddResult("int.Parse", i => int.Parse("12345")); this.AddResult("int.TryParse", i => this.TryParse("12345")); this.AddResult("int.TryParse cond", i => this.TryParseCond("12345")); this.AddResult("int.TryParse static", i => TryParseStatic("12345")); this.AddResult("IntParseFast", i => IntParseFast("12345")); this.AddResult("SafeIntParseFast", i => SafeIntParseFast("12345")); this.AddResult("SafeConvert", i => SafeConvert.ToInt32("12345")); this.AddResult("SafeNullableConvert", i => SafeNullableConvert.ToInt32("12345")); }
public List <DbTable> GetDbTables(string database) { string sql = string.Format("SELECT * from `TABLES` where TABLE_SCHEMA='{0}'", database); DataTable dt = MySqlHelper.ExecuteDataset(ConnString, sql).Tables[0]; return(dt.Rows.Cast <DataRow>().Select(row => new DbTable { HasPrimaryKey = true, TableName = row["TABLE_NAME"].ToString(), SchemaName = row["TABLE_SCHEMA"].ToString(), Rows = SafeConvert.ToInt32(row["TABLE_ROWS"]), }).ToList()); }
public override INode Factory(IFrame frame, int formerId) { var payload = frame.Payload; if (payload.Length < 2) { return(null); } // HACK el equipo de sampe esta mandando una 'Y' if (payload[0] == 'H' && payload[1] == '0') { payload[2] = Convert.ToByte(';'); } var partes = Encoding.ASCII.GetString(frame.Payload, 0, frame.Payload.Length).Split('@')[0].Split(';'); if (partes.Length < 3) { return(null); } if (payload[0] == 'H' && payload[1] == '0') { return(DataProvider.FindByIMEI(partes[1], this)); } if (payload[0] == 'T' && payload[1] == '0') { return(DataProvider.FindByIMEI(partes[4], this)); } if (payload[0] == 'A' && payload[1] == '0') { return(DataProvider.FindByIMEI(partes[4], this)); } if (payload[0] == 'V' && payload[1] == '0') { return(DataProvider.FindByIMEI(partes[4], this)); } if ((payload[0] == 'E') && (payload[1] != 'V')) { return(DataProvider.FindByIMEI(partes[2], this)); } var devid = SafeConvert.ToInt32(partes[2], 0); return(devid == 0 ? null : DataProvider.Get(devid, this)); }
public virtual TDbContext GetOrCreateDbContext <TDbContext, TEntity>(MultiTenancySides?multiTenancySide = null) where TDbContext : DbContext { var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext)); var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide); connectionStringResolveArgs["DbContextType"] = typeof(TDbContext); connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType; var connectionString = ResolveConnectionString(connectionStringResolveArgs); var entityAssemblyId = typeof(TEntity).Assembly.GetName().Name; if (!entityConfigurations.Any(e => string.Equals(e.EntityModule, entityAssemblyId, StringComparison.OrdinalIgnoreCase))) { throw new BlocksDBORMException(StringLocal.Format($"{entityAssemblyId} not found in EntityConfigurations.")); } var moduleName = entityAssemblyId; //extensionManager.GetExtension(typeof(TEntity).Assembly.GetName().Name).Name; var dbContextKey = moduleName + "#" + concreteDbContextType.FullName + "#" + connectionString; DbContext dbContext; if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext)) { if (Options.IsTransactional == true) { dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString, _dbContextResolver, moduleName); } else { dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString, moduleName); } if (Options.Timeout.HasValue && !dbContext.Database.GetCommandTimeout().HasValue) { dbContext.Database.SetCommandTimeout(SafeConvert.ToInt32(Options.Timeout.Value.TotalSeconds)); } //TODO ObjectMaterialize //((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) => //{ // ObjectContext_ObjectMaterialized(dbContext, args); //}; // FilterExecuter.As<IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext); ActiveDbContexts[dbContextKey] = dbContext; } return((TDbContext)dbContext); }
/// <summary> /// 获取设备当前电量 /// </summary> /// <returns></returns> public int GetBatteryCurrentCapacity() { try { string s = Convert.ToString(this.GetDeviceValue("com.apple.mobile.battery", DeviceInfoKey.BatteryCurrentCapacity)) + string.Empty; if (s.Length > 0) { return(SafeConvert.ToInt32(s)); } } catch (Exception ex) { } return(-1); }
private static ConfigRequest ParseLogin(String[] partes, INode node) { var mid = Convert.ToUInt64(partes[1]); var crq = new ConfigRequest(node.Id, mid) { GeoPoint = null, }; crq.AddStringToSend(String.Format(@"RV0;{0:D3};{1:D5};{2:yy/MM/dd,HH:mm:ss}", mid, node.Id, DateTime.UtcNow)); crq.StringParameters.Add(Indication.indicatedIMEI, partes[4]); crq.StringParameters.Add(Indication.indicatedSecret, partes[5]); crq.StringParameters.Add(Indication.indicatedFirmwareSignature, partes[6]); crq.IntegerParameters.Add(Indication.indicatedConfigurationRevision, SafeConvert.ToInt32(partes[7], -1)); return(crq); }
public virtual TDbContext GetOrCreateDbContext <TDbContext>(MultiTenancySides?multiTenancySide = null) where TDbContext : DbContext { var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext)); var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide); connectionStringResolveArgs["DbContextType"] = typeof(TDbContext); connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType; var connectionString = ResolveConnectionString(connectionStringResolveArgs); var dbContextKey = concreteDbContextType.FullName + "#" + connectionString; DbContext dbContext; if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext)) { if (Options.IsTransactional == true) { dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString, _dbContextResolver); } else { dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString); } if (Options.Timeout.HasValue && !dbContext.Database.CommandTimeout.HasValue) { dbContext.Database.CommandTimeout = SafeConvert.ToInt32(Options.Timeout.Value.TotalSeconds); } ((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) => { ObjectContext_ObjectMaterialized(dbContext, args); }; // FilterExecuter.As<IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext); ActiveDbContexts[dbContextKey] = dbContext; } return((TDbContext)dbContext); }
private static ConfigRequest ParseALogin(String[] partes, INode node) { var mid = Convert.ToUInt64(partes[1]); var crq = new ConfigRequest(node.Id, mid) { GeoPoint = null, }; //A0;Msgid;Serie;IMEI;Pass;Version ;Versión de Parámetros ;Tiempo entre tomas ;IP primaria ;IP secundaria@checksum //A0;000;00000;0000000000;0355826019078657;E57290F2;7.01;00000;30;190.2.37.141:4040;unex.hopto.org:3030@3D crq.AddStringToSend(String.Format(@"RA0;{0:D3};{1:D5};{2:yy/MM/dd,HH:mm:ss}", mid, node.Id, DateTime.UtcNow)); crq.StringParameters.Add(Indication.indicatedIMEI, partes[3]); crq.StringParameters.Add(Indication.indicatedSecret, partes[4]); crq.StringParameters.Add(Indication.indicatedFirmwareSignature, partes[5]); crq.IntegerParameters.Add(Indication.indicatedConfigurationRevision, SafeConvert.ToInt32(partes[6], -1)); return(crq); }
private static Event ParseEvento(String asString, INode node) { var idEquipo = Convert.ToInt32(asString.Substring(3, 5)); if (node.Id != SafeConvert.ToInt32(idEquipo, -1)) { STrace.Debug(typeof(Parser).FullName, node.Id, String.Format("ENTRANTE DESCARTAD0, NO COINCIDE. raw_data={0}", asString)); return(null); } //se cambian algunos codigos por que hay conflictos var code = Convert.ToInt16(asString.Substring(1, 2)); switch (code) { case 90: code = (short)MessageIdentifier.BateryReConected; break; case 91: code = (short)MessageIdentifier.PanicButtonOff; break; case 92: code = (short)MessageIdentifier.PanicButtonOn; break; case 93: code = (short)MessageIdentifier.SlowingTicket; break; case 94: code = (short)MessageIdentifier.EngineOnInternal; break; case 95: code = (short)MessageIdentifier.EngineOffInternal; break; case 96: code = (short)MessageIdentifier.SpeedingTicketEnd; break; case 97: code = (short)MessageIdentifier.BateryDisconected; break; case 99: code = (short)MessageIdentifier.DisplayProblem; break; } var idMsg = Convert.ToUInt32(asString.Substring(8, 5)); return(((MessageIdentifier)code) .FactoryEvent(node.Id, idMsg, null, DateTime.UtcNow, null, null) .AddStringToSend(String.Format("GA{0:D5}", idMsg))); }
public MainWindow() { log.DebugFormat("Обновление запущено {0}", typeof(MainWindow).Assembly.Location); var args = Environment.GetCommandLineArgs(); var pid = args.Skip(1).Select(v => SafeConvert.ToInt32(v, -1)).FirstOrDefault(-1); var exe = args.Skip(2).FirstOrDefault(); Closed += (sender, eventArgs) => { log.DebugFormat("Обновление завершено"); }; var task = Run(pid, exe, FileHelper.MakeRooted(".")); task.ContinueWith(t => { if (t.IsFaulted) { log.Error("Процесс обновления завершился ошибкой", t.Exception); App.NotifyAboutException(t.Exception); } Close(); }, TaskScheduler.FromCurrentSynchronizationContext()); InitializeComponent(); ResizeMode = ResizeMode.NoResize; SizeToContent = SizeToContent.Manual; }
public IEnumerable <Item> Find(ItemSearchParams searchParams) { var hasSiteSync = this.IsColumnExists($"Items", "SITESYNC"); var hasKupaSync = this.IsColumnExists($"Items", "KUPASYNC"); var hasUpdDate = this.IsColumnExists($"Items", "UitemDate"); try { var items = new List <Item>(); // ignore tables search with updated-date filter but no updated-date column // to prevent receiving incorrect data var hasUpdDateFilter = searchParams.FromUpdateDate.HasValue || searchParams.ToUpdateDate.HasValue; if (searchParams.PauseIfNoUpdateDateColumn && !hasUpdDate && hasUpdDateFilter) { return(items); } using (var connection = new OdbcConnection(this.ConnetionString)) { connection.Open(); var query = $@" SELECT * FROM Items WHERE ('{searchParams.ItemId ?? ""}' = '' OR ItemNo = '{searchParams.ItemId}') AND ('{searchParams.Barcode ?? ""}' = '' OR Barcode = '{searchParams.Barcode}') AND ({searchParams.SortCode} = 0 OR SortCode1 = {searchParams.SortCode} OR SortCode2 = {searchParams.SortCode} OR SortCode3 = {searchParams.SortCode}) "; /// AND (totqty >= {searchParams.QtyInStock}) if (searchParams.IsBlocked.HasValue) { query += $"AND(TITLE {(searchParams.IsBlocked.Value ? "=" : "<>")} '{ SafeConvert.ToPervasiveString("כ")}') "; } if (hasSiteSync) { query += $"AND SITESYNC = {(searchParams.SyncToSite ? 1 : 0)} "; } if (hasKupaSync) { query += $"AND KUPASYNC = {(searchParams.SyncToFunds ? 1 : 0)} "; } if (hasUpdDate) { query += $@" AND({ PervasiveDBHelper.ToPervasiveDate(searchParams.FromUpdateDate)} <= 0 OR UitemDate >= { PervasiveDBHelper.ToPervasiveDate(searchParams.FromUpdateDate)}) AND({ PervasiveDBHelper.ToPervasiveDate(searchParams.ToUpdateDate)} <= 0 OR UitemDate <= { PervasiveDBHelper.ToPervasiveDate(searchParams.ToUpdateDate)}) "; } query += "ORDER BY ItemNo DESC"; var command = new OdbcCommand(query); command.Connection = connection; /// throw new Exception(query); using (var reader = command.ExecuteReader()) { while (reader.Read()) { items.Add(new Item { Id = SafeConvert.ToString(reader["ItemNo"]), ItemNameHE = SafeConvert.ToString(reader["ItemName"]), ItemNameEN = SafeConvert.ToString(reader["Ename"]), Barcode = SafeConvert.ToString(reader["Barcode"]), Characteristic1 = SafeConvert.ToString(reader["ifun1"]), Characteristic2 = SafeConvert.ToString(reader["ifun2"]), CurrencyCode1 = SafeConvert.ToInt32(reader["FC1"]), CurrencyCode2 = SafeConvert.ToInt32(reader["FC2"]), CurrencyCode3 = SafeConvert.ToInt32(reader["FC3"]), CurrencyCode4 = SafeConvert.ToInt32(reader["FC4"]), CurrencyCode5 = SafeConvert.ToInt32(reader["FC5"]), CurrencyCode6 = SafeConvert.ToInt32(reader["FC6"]), CurrencyCode7 = SafeConvert.ToInt32(reader["FC7"]), CurrencyCode8 = SafeConvert.ToInt32(reader["FC8"]), CurrencyCode9 = SafeConvert.ToInt32(reader["FC9"]), CurrencyCode10 = SafeConvert.ToInt32(reader["FC10"]), Price1 = SafeConvert.ToSingle(reader["Prc1"]), Price2 = SafeConvert.ToSingle(reader["Prc2"]), Price3 = SafeConvert.ToSingle(reader["Prc3"]), Price4 = SafeConvert.ToSingle(reader["Prc4"]), Price5 = SafeConvert.ToSingle(reader["Prc5"]), Price6 = SafeConvert.ToSingle(reader["Prc6"]), Price7 = SafeConvert.ToSingle(reader["Prc7"]), Price8 = SafeConvert.ToSingle(reader["Prc8"]), Price9 = SafeConvert.ToSingle(reader["Prc9"]), Price10 = SafeConvert.ToSingle(reader["Prc10"]), SortCode1 = SafeConvert.ToInt32(reader["SortCode1"]), SortCode2 = SafeConvert.ToInt32(reader["SortCode2"]), SortCode3 = SafeConvert.ToInt32(reader["SortCode3"]), SupplerId1 = SafeConvert.ToInt32(reader["Supl1"]), SupplerId2 = SafeConvert.ToInt32(reader["Supl2"]), SupplerId3 = SafeConvert.ToInt32(reader["Supl3"]), SupplerId4 = SafeConvert.ToInt32(reader["Supl4"]), Unit = SafeConvert.ToString(reader["Unit"]), ///QtyInStock = SafeConvert.ToSingle(reader["totqty"]), VatFlag = SafeConvert.ToBoolean(reader["Patur"]), SyncToSite = SafeConvert.ToBoolean(reader.ReadOrDefault <bool>("SITESYNC")), SyncToFunds = SafeConvert.ToBoolean(reader.ReadOrDefault <bool>("KUPASYNC")), IsBlocked = SafeConvert.ToBoolean(reader["TITLE"]), UpdatedDate = FromPervasiveDate(Convert.ToDouble(reader.ReadOrDefault <double>("UitemDate"))), ProviderId = 0 }); } } return(items); } } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } }
private ConfigRequest ParseConfigRequest(String asString) { var crq = new ConfigRequest(Id, 0) { GeoPoint = null }; const int keepalive = 3; const int retry = 3; crq.AddStringToSend(String.Format("H9{0:D5}{1:D5}{2:D2}{3:D2}", 10000, Id, keepalive, retry)); crq.StringParameters.Add(Indication.indicatedIMEI, asString.Substring(24, 16)); crq.StringParameters.Add(Indication.indicatedSecret, asString.Substring(59, 8)); crq.StringParameters.Add(Indication.indicatedFirmwareSignature, asString.Substring(54, 4)); crq.IntegerParameters.Add(Indication.indicatedConfigurationRevision, 0); crq.IntegerParameters.Add(Indication.indicatedCannedMessagesTableRevision, SafeConvert.ToInt32(asString.Substring(58, 1), -1)); return(crq); }
/// <summary> /// Compute machine perf info to get more human-readable resource usage info /// </summary> /// <param name="ensureSample">when true and no performance measurement samples are registered, immediately forces a collection of a performance /// measurement sample</param> public MachinePerfInfo ComputeMachinePerfInfo(bool ensureSample = false) { if (ensureSample && Volatile.Read(ref m_sampleCount) == 0) { m_parent.CollectOnce(); } MachinePerfInfo perfInfo = default(MachinePerfInfo); using (var sbPool = Pools.GetStringBuilder()) using (var sbPool2 = Pools.GetStringBuilder()) { StringBuilder consoleSummary = sbPool.Instance; StringBuilder logFileSummary = sbPool2.Instance; perfInfo.CpuUsagePercentage = SafeConvert.ToInt32(MachineCpu.Latest); consoleSummary.AppendFormat("CPU:{0}%", perfInfo.CpuUsagePercentage); logFileSummary.AppendFormat("CPU:{0}%", perfInfo.CpuUsagePercentage); if (MachineTotalPhysicalMB.Latest > 0) { var availableRam = SafeConvert.ToInt32(MachineAvailablePhysicalMB.Latest); var totalRam = SafeConvert.ToInt32(MachineTotalPhysicalMB.Latest); var ramUsagePercentage = SafeConvert.ToInt32(((100.0 * (totalRam - availableRam)) / totalRam)); Contract.Assert(ramUsagePercentage >= 0 && ramUsagePercentage <= 100); perfInfo.RamUsagePercentage = ramUsagePercentage; perfInfo.TotalRamMb = totalRam; perfInfo.AvailableRamMb = availableRam; consoleSummary.AppendFormat(" RAM:{0}%", ramUsagePercentage); logFileSummary.AppendFormat(" RAM:{0}%", ramUsagePercentage); } if (ModifiedPagelistMB.Latest > 0) { perfInfo.ModifiedPagelistMb = SafeConvert.ToInt32(ModifiedPagelistMB.Latest); } if (FreePagelistMB.Latest > 0) { perfInfo.FreePagelistMb = SafeConvert.ToInt32(FreePagelistMB.Latest); } if (StandbyPagelistMB.Latest > 0) { perfInfo.StandbyPagelistMb = SafeConvert.ToInt32(StandbyPagelistMB.Latest); } if (perfInfo.TotalRamMb.HasValue) { perfInfo.EffectiveAvailableRamMb = perfInfo.AvailableRamMb.Value + (perfInfo.ModifiedPagelistMb ?? 0); perfInfo.EffectiveRamUsagePercentage = SafeConvert.ToInt32(100.0 * (perfInfo.TotalRamMb.Value - perfInfo.EffectiveAvailableRamMb.Value) / perfInfo.TotalRamMb.Value); } if (CommitLimitMB.Latest > 0) { var commitUsed = SafeConvert.ToInt32(CommitUsedMB.Latest); var commitLimit = SafeConvert.ToInt32(CommitLimitMB.Latest); var commitUsagePercentage = SafeConvert.ToInt32(((100.0 * commitUsed) / commitLimit)); perfInfo.CommitUsagePercentage = commitUsagePercentage; perfInfo.CommitUsedMb = commitUsed; perfInfo.CommitLimitMb = commitLimit; } if (MachineBandwidth.Latest > 0) { perfInfo.MachineBandwidth = (long)MachineBandwidth.Latest; perfInfo.MachineKbitsPerSecSent = MachineKbitsPerSecSent.Latest; perfInfo.MachineKbitsPerSecReceived = MachineKbitsPerSecReceived.Latest; } int diskIndex = 0; perfInfo.DiskAvailableSpaceGb = new int[DiskStats.Count]; foreach (var disk in DiskStats) { var availableSpaceGb = SafeConvert.ToInt32(disk.AvailableSpaceGb.Latest); perfInfo.DiskAvailableSpaceGb[diskIndex] = availableSpaceGb; diskIndex++; } if (!OperatingSystemHelper.IsUnixOS) { perfInfo.DiskUsagePercentages = new int[DiskStats.Count]; perfInfo.DiskQueueDepths = new int[DiskStats.Count]; string worstDrive = "N/A"; int highestActiveTime = -1; int highestQueueDepth = 0; // Loop through and find the worst looking disk diskIndex = 0; foreach (var disk in DiskStats) { if (disk.ReadTime.Maximum == 0) { perfInfo.DiskUsagePercentages[diskIndex] = 0; perfInfo.DiskQueueDepths[diskIndex] = 0; diskIndex++; // Don't consider samples unless some activity has been registered continue; } var activeTime = disk.CalculateActiveTime(lastOnly: true); var queueDepth = SafeConvert.ToInt32(disk.QueueDepth.Latest); perfInfo.DiskUsagePercentages[diskIndex] = activeTime; perfInfo.DiskQueueDepths[diskIndex] = queueDepth; diskIndex++; logFileSummary.Append(FormatDiskUtilization(disk.Drive, activeTime)); if (activeTime > highestActiveTime) { worstDrive = disk.Drive; highestActiveTime = activeTime; highestQueueDepth = queueDepth; } } if (highestActiveTime != -1) { consoleSummary.Append(FormatDiskUtilization(worstDrive, highestActiveTime)); } } perfInfo.ProcessCpuPercentage = SafeConvert.ToInt32(ProcessCpu.Latest); logFileSummary.AppendFormat(" DominoCPU:{0}%", perfInfo.ProcessCpuPercentage); perfInfo.ProcessWorkingSetMB = SafeConvert.ToInt32(ProcessWorkingSetMB.Latest); logFileSummary.AppendFormat(" DominoRAM:{0}MB", perfInfo.ProcessWorkingSetMB); perfInfo.ConsoleResourceSummary = consoleSummary.ToString(); perfInfo.LogResourceSummary = logFileSummary.ToString(); } return(perfInfo); }
protected void ReloadTextFile(string FileName, TextView view, bool isTraining = false, SpinButton counter = null) { try { var current = DelimiterBox.Active; var delimiter = current >= 0 && current < Delimiters.Count ? Delimiters[current].Character : '\t'; var categories = new List <int>(); if (File.Exists(FileName) && view != null) { var text = ""; using (TextReader reader = File.OpenText(FileName)) { string line; var count = 0; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (!string.IsNullOrEmpty(line)) { if (isTraining && counter != null) { var tokens = line.Split(delimiter); if (tokens.Length > 1) { var last = SafeConvert.ToInt32(tokens[tokens.Length - 1]); if (!categories.Contains(last) && last > 0) { categories.Add(last); } } } text += count > 0 ? "\n" + line : line; count++; } } } if (isTraining && counter != null) { counter.Value = Convert.ToDouble(categories.Count, ci); } view.Buffer.Clear(); view.Buffer.Text = text.Trim(); } } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); } }
//private JunTeEntities dbread = JunTeEntities.Read(); public void GetSMBJingZhiPageList() { int pagesize = SafeConvert.ToInt32(Context.Request.Form["pagesize"], 6); int pageindex = SafeConvert.ToInt32(Context.Request.Form["pageindex"], 1); if (pageindex < 1) { pageindex = 1; } Guid projectid = SafeConvert.ToGuid(Context.Request.Form["projectid"]) ?? Guid.Empty; if (projectid == Guid.Empty) { PrintJson("-1", "项目编号有误"); } string sql = @"SELECT @Total=COUNT(1) FROM ProjectFundDetail_SM(NOLOCK) WHERE projectId=@projectId; SELECT * FROM ( SELECT ROW_NUMBER() OVER(ORDER BY PriceDate DESC) AS RowNumber,* FROM ProjectFundDetail_SM(NOLOCK) WHERE projectId=@projectId )T WHERE T.RowNumber BETWEEN (@pageIndex-1)*@pageSize+1 AND @pageIndex*@pageSize"; //var whereParams = new[] //{ // new SqlParameter("@Total", 0), new SqlParameter("@projectId", projectid), // new SqlParameter("@pageIndex", pageindex), // new SqlParameter("@pageSize", pagesize) //}; //whereParams[0].Direction = ParameterDirection.Output; var paras = new Dapper.DynamicParameters(); paras.Add("@Total", 0, DbType.Int32, ParameterDirection.Output); paras.Add("@pageIndex", pageindex); paras.Add("@pageSize", pagesize); paras.Add("@projectId", projectid); var list = new List <SMBProjectFundDetailInfo>(); //list = dbread.ExecuteStoreQuery<SMBProjectFundDetailInfo>(sql, whereParams).ToList(); list = TuanDai.DB.TuanDaiDB.Query <SMBProjectFundDetailInfo>(TdConfig.DBRead, sql, ref paras); int totalItemCount = paras.Get <int>("@Total"); //int.TryParse(whereParams[0].Value.ToString(), out totalItemCount); var sb = new StringBuilder(); int index = 1; double divide = totalItemCount / pagesize; double floor = Math.Floor(divide); if (totalItemCount % pagesize != 0) { floor++; } int pageCount = Convert.ToInt32(floor); //总页数 sb.Append("{\"result\":\"1\",\"pageCount\":\"" + pageCount + "\",\"list\":["); foreach (SMBProjectFundDetailInfo item in list) { sb.Append("{"); sb.AppendFormat("\"PriceDate\":\"{0}\",", item.PriceDate.ToString("yyyy-MM-dd")); sb.AppendFormat("\"Price\":\"{0}\",", item.Price); sb.AppendFormat("\"TotalPrice\":\"{0}\"", item.TotalPrice); sb.Append("},"); if (list.Count == index) { sb.Length = sb.Length - 1; } index++; } sb.Append("]}"); Context.Response.Write(sb.ToString()); Context.Response.End(); }
public static int _ToInt32(this object obj) { return(SafeConvert.ToInt32(obj)); }
}//FINISH PM_OnSerializeToDbTransItemInElement //ANTES DEL CIERRE DE LA TRANSACCION void PM_OnBeforeCloseTransaction(Transaction transaction, ref bool abort) { //throw new NotImplementedException(); // ARROJA ERROR SI EL SERVICIO NO ESTA DISPONIBLE if (webservice == null) { abort = true; BL.MsgError("WEBSERVICE NO COMUNICATION"); return; } else { string printoutType = ""; if (transaction.ManualPrintoutSelected == DbPayment.PrintoutType.KeepDefault || transaction.ManualPrintoutSelected == DbPayment.PrintoutType.NoPrintout) { printoutType = "39"; } if (transaction.ManualPrintoutSelected == DbPayment.PrintoutType.Invoice) { printoutType = "33"; } if (transaction.ManualPrintoutSelected == DbPayment.PrintoutType.Bill) { printoutType = "39"; } if (transaction.ManualPrintoutSelected == DbPayment.PrintoutType.Invoice && transaction.Customer == null) { BL.MsgError("WE NEED A CUSTOMER"); abort = true; return; } //string xmlData = ""; //string documentType = ""; DbCustomer receptorDTE = new DbCustomer(); receptorDTE = customer; XmlStringWriter writer = new XmlStringWriter(BL.DB); writer.WriteRaw(@"<?xml version=""1.0"" encoding=""ISO-8859-1""?>"); if (printoutType == "33")//FACTURA { //INICIO DTE writer.WriteStartElement("DTE"); writer.WriteAttribute("version", "1.0"); writer.WriteAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); writer.WriteAttribute("xmlns", "http://www.sii.cl/SiiDte"); //FIN DTE } else//BOLETA { //INICIO EnvioBOLETA writer.WriteStartElement("EnvioBOLETA"); writer.WriteAttribute("version", "1.0"); writer.WriteAttribute("xmlns", "http://www.sii.cl/SiiDte"); writer.WriteAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttribute("xsi:schemaLocation", "http://www.sii.cl/SiiDte EnvioBOLETA_v11.xsd"); //FIN EnvioBoleta } //RUT RECEPTOR string rrecep; rrecep = getRutReceptorDTE(); //RUT RECEPTOR if (printoutType == "39")//BOLETA { //ONLY BOLETA writer.WriteStartElement("SetDTE"); writer.WriteAttribute("ID", string.Format("ENVBOL-{0}", transaction.TransDate.ToString("yyyyMMddHHmmss"))); writer.WriteStartElement("Caratula"); writer.WriteAttribute("version", "1.0"); //string shopRut = BL.DB.Shop["rut"].ToString(); //string shopRut = "76328464-6"; string shopRut = dataEmisor.RutBoleta; writer.WriteElement("RutEmisor", shopRut); //string RutEnvia = BL.DB.Shop["RutEnvia"].ToString(); //string RutEnvia = "8833649-6"; string RutEnvia = dataEmisor.RutRepLegal; writer.WriteElement("RutEnvia", RutEnvia); //string RutReceptor = BL.DB.Shop["RutReceptor"].ToString(); //string RutReceptor = "66666666-6"; writer.WriteElement("RutReceptor", rrecep); //DateTime FchResol = Convert.ToDateTime(BL.DB.Shop["FchResol"]); //DateTime FchResol = new DateTime(2014, 04, 22); DateTime FchResol = (dataEmisor.ResolDate); writer.WriteElement("FchResol", FchResol.ToString("yyyy-MM-dd")); //writer.WriteElement("NroResol", 0); writer.WriteElement("NroResol", dataEmisor.NumResol); writer.WriteElement("TmstFirmaEnv", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")); writer.WriteStartElement("SubTotDTE"); writer.WriteElement("TpoDTE", printoutType); writer.WriteElement("NroDTE", 1); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("DTE"); writer.WriteAttribute("version", "1.0"); //END ONLY BOLETA } //string besRut = "76054473-6"; //MANAGE THIS FROM DB ON FRONTEND dataEmisor.Rut // string besRut = dataEmisor.Rut; if (printoutType == "39") { //ONLY BOLETA writer.WriteStartElement("Documento"); //string besRut = myClassPAramData["besRUT"].ToString(); string besRutBoletaE = dataEmisor.RutBoleta; solicitarFolio = webservice.Solicitar_Folio(besRutBoletaE, 39); writer.WriteAttribute("ID", string.Format("R{0}T{1}F{2}", besRutBoletaE, printoutType, solicitarFolio.Folio)); //END ONLY BOLETA } else { solicitarFolio = webservice.Solicitar_Folio(besRut, 33); writer.WriteStartElement("Documento"); } writer.WriteStartElement("Encabezado"); writer.WriteStartElement("IdDoc"); writer.WriteElement("TipoDTE", printoutType); writer.WriteElement("Folio", solicitarFolio.Folio); writer.WriteElement("FchEmis", DateTime.Now.ToString("yyyy-MM-dd")); if (printoutType == "39") { //SOLO BOLETA writer.WriteElement("IndServicio", 3); //SOLO BOLETA } else { //TermPagoGlosa //FchVenc writer.WriteElement("TermPagoGlosa", "30 dias Precio Contado"); ///////////////////////////////////////////ASK 4 THIS FIELD writer.WriteElement("FchVenc", "2016-06-30"); /////////////////////////////////////////////////////////////ASK 4 THIS FIELD } writer.WriteEndElement(); //IdDoc //FIN DATOS EMISOR if (printoutType == "39") { writer.WriteStartElement("Emisor"); writer.WriteElement("RUTEmisor", dataEmisor.Rut); writer.WriteElement("RznSocEmisor", dataEmisor.RazonEmisor); writer.WriteElement("GiroEmisor", dataEmisor.GiroEmisor); writer.WriteElement("CdgSIISucur", dataEmisor.CodigoSII); writer.WriteElement("DirOrigen", dataEmisor.DireccionEm); writer.WriteElement("CmnaOrigen", dataEmisor.ComunaEm); writer.WriteElement("CiudadOrigen", dataEmisor.CiudadEm); writer.WriteEndElement(); //Emisor } else { writer.WriteStartElement("Emisor"); //<Acteco>602300</Acteco> writer.WriteElement("Acteco", dataEmisor.ActEco); writer.WriteElement("RUTEmisor", dataEmisor.Rut); writer.WriteElement("RznSoc", dataEmisor.RazonEmisor); writer.WriteElement("GiroEmis", dataEmisor.GiroEmisor); writer.WriteElement("DirOrigen", dataEmisor.DireccionEm); writer.WriteElement("CmnaOrigen", dataEmisor.ComunaEm); writer.WriteElement("CiudadOrigen", dataEmisor.CiudadEm); writer.WriteElement("CdgVendedor", BL.CurrentOperator.Code); writer.WriteEndElement(); //Emisor } //OBJETO RECEPTOR DbCustomer receptorC = BL.DB.GetCustomerByCardNum((rrecep.Replace("-", "")), false); //OBJETO RECEPTOR writer.WriteStartElement("Receptor"); writer.WriteElement("RUTRecep", rrecep); if (printoutType == "33")//FACTURA { //<CdgIntRecep>76124037C</CdgIntRecep> writer.WriteElement("CdgIntRecep", getCodeIntRecep(rrecep)); writer.WriteElement("RznSocRecep", receptorC.C_o); //<GiroRecep>VENTA AL POR MAYOR DE OTROS PRODUCTOS N.</GiroRecep> writer.WriteElement("GiroRecep", receptorC.C_o); writer.WriteElement("DirRecep", receptorC.Street); writer.WriteElement("CmnaRecep", receptorC.Notes1); writer.WriteElement("CiudadRecep", receptorC.City); writer.WriteEndElement(); //Receptor } else//BOLETA { writer.WriteElement("RznSocRecep", null); writer.WriteElement("Contacto", null);//ASK NUM TELEFONO writer.WriteElement("DirRecep", null); writer.WriteElement("CmnaRecep", null); writer.WriteElement("CiudadRecep", null); writer.WriteElement("DirPostal", null); writer.WriteElement("CmnaPostal", null); writer.WriteElement("CiudadPostal", null); writer.WriteEndElement(); //Receptor } writer.WriteStartElement("Totales"); if (printoutType == "33")//FACTURA { double monto, neto, iva; string netoS, ivaS; monto = SafeConvert.ToInt32(transaction.Total); neto = monto * 0.81; iva = monto - neto; netoS = SafeConvert.ToString(neto); ivaS = SafeConvert.ToString(iva); writer.WriteElement("TpoMoneda", "PESO CL"); writer.WriteElement("MntNeto", netoS); writer.WriteElement("TasaIVA", "19.00"); writer.WriteElement("IVA", ivaS); } writer.WriteElement("MntTotal", SafeConvert.ToInt32(transaction.Total)); writer.WriteEndElement(); //Totales writer.WriteEndElement(); //Encabezado int position = 1; foreach (TransArticle art in transaction.GetItems <TransArticle>()) { writer.WriteStartElement("Detalle"); writer.WriteElement("NroLinDet", position); writer.WriteStartElement("CdgItem"); writer.WriteElement("TpoCodigo", "Interna"); writer.WriteElement("VlrCodigo", art.Data.Code); writer.WriteEndElement(); //CdgItem writer.WriteElement("NmbItem", art.Data.Description); if (printoutType == "33") { writer.WriteElement("DscItem", art.Data.Description); } writer.WriteElement("QtyItem", art.Data.MeasureUnit == DbArticle.Units.Pieces ? art.Quantity : 1); //writer.WriteElement("QtyItem", 1); writer.WriteElement("UnmdItem", null); writer.WriteElement("PrcItem", art.UnitPrice); //writer.WriteElement("MontoItem", art.TotalPrice); string totalprice = art.TotalPrice.ToString(); totalprice = totalprice.Replace(".00", ""); writer.WriteElement("MontoItem", totalprice); writer.WriteEndElement(); //Detalle position++; } writer.WriteEndElement(); //Documento writer.WriteEndElement(); //DTE if (printoutType == "39") { writer.WriteEndElement(); //SetDTE writer.WriteEndElement(); //EnvioBOLETA || DTE } string xmlString = writer.ToString(); if (printoutType == "33") { resultProcesarTXTDTE = webservice.Carga_TXTDTE(xmlString, "XML"); } else { resultProcesarTXTBoleta = webservice.Carga_TXTBoleta(xmlString, "XML"); } string fob; if (printoutType == "33") { fob = "Factura"; } else { fob = "Boleta"; } if (dataEmisor.SaveXML == 1) { //SAVE TO FILE XML string path = Path.GetPathRoot(Environment.SystemDirectory); System.IO.Directory.CreateDirectory("C:\\xmlTCPOS"); //System.IO.File.WriteAllText(@"C:\xmlTCPOS\" + fob + "" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xml", xmlString); System.IO.File.WriteAllText(@"" + path + "xmlTCPOS\\" + fob + "" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xml", xmlString); //END SAVE TO FILE XML } if (printoutType == "33") { if (resultProcesarTXTDTE.XML != "") { XmlDocument doc = new XmlDocument(); doc.LoadXml(resultProcesarTXTDTE.XML); XmlElement root = doc.DocumentElement; if (root == null) { abort = true; throw new Exception("XML BAD FORMAT"); } XmlNodeList SignatureValue = root.GetElementsByTagName("TED"); string signature = ""; foreach (XmlNode tableNode in SignatureValue) { signature = tableNode.InnerXml; } if (signature != "") { signature = string.Format("<TED version=\"1.0\">" + signature + "</TED>"); } transaction.SetCustomField("webservice_bes_signature", signature); transaction.SetCustomField("dte_doc_type", printoutType); XmlNodeList folioNUMValue = root.GetElementsByTagName("F"); string folioNUM = ""; foreach (XmlNode tableNode in folioNUMValue) { folioNUM = tableNode.InnerXml; } if (folioNUM != "") { folioNUM = string.Format("" + folioNUM + ""); } transaction.SetCustomField("webservice_bes_folionum", folioNUM); //GUARDA FOLIO 2 PRINT if (folioNUM != "") { transaction.SetCustomField("bes_folio_num", folioNUM); } //END GUARDA FOLIO 2 PRINT //PRINT TIPO DOC transaction.SetCustomField("tipo_documento", "FACTURA ELECTRONICA"); //END PRINT TIPO DOC } else { abort = true; BL.MsgError("No answer from webservice,\nelectronic invoice cannot be accepted\nPlease use another type of document"); } } else { //if response from webservice read xml response and get the signature, save it into transaction and print signature if (resultProcesarTXTBoleta.XML != "") { XmlDocument doc = new XmlDocument(); doc.LoadXml(resultProcesarTXTBoleta.XML); XmlElement root = doc.DocumentElement; if (root == null) { abort = true; throw new Exception("XML BAD FORMAT"); } //OBTENER TED Y GUARDAR XmlNodeList SignatureValue = root.GetElementsByTagName("TED"); string signature = ""; foreach (XmlNode tableNode in SignatureValue) { signature = tableNode.InnerXml; } if (signature != "") { signature = string.Format("<TED version=\"1.0\">" + signature + "</TED>"); } transaction.SetCustomField("webservice_bes_signature", signature); transaction.SetCustomField("dte_doc_type", printoutType); //FIN OBTENER TED Y GUARDAR //OBTENER FOLIONUM Y GUARDAR XmlNodeList folioNUMValue = root.GetElementsByTagName("F"); string folioNUM = ""; foreach (XmlNode tableNode in folioNUMValue) { folioNUM = tableNode.InnerXml; } if (folioNUM != "") { folioNUM = string.Format("" + folioNUM + ""); } transaction.SetCustomField("webservice_bes_folionum", folioNUM); //FIN FOLIONUM Y GUARDAR //GUARDA FOLIO 2 PRINT if (folioNUM != "") { transaction.SetCustomField("bes_folio_num", folioNUM); } //END GUARDA FOLIO 2 PRINT transaction.SetCustomField("tipo_documento", "BOLETA ELECTRONICA"); } else { abort = true; BL.MsgError("No answer from webservice,\nelectronic invoice cannot be accepted\nPlease use another type of document"); } } } }//FINISH PM_OnBeforeCloseTransaction