public bool CreateGame(string Username, Transfer.AddGame addGame) { if (!Utilities.Encryption.isAlphaNumeric(addGame.SaveName)) throw new Code.ExceptionResponse("Save name can only contain alphanumeric characters and spaces"); Data.User user = Model_.Users.Where(e => e.Username == Username).First(); var saves = Model_.Saves.Where(e => (e.UserId == user.UserId) && (e.SaveName.ToLower() == addGame.SaveName.ToLower())); if (saves.Count() > 0) throw new Code.ExceptionResponse("Save name already exists"); var result = Model_.Saves.Create(); result.Code = new byte[256]; result.AbilityData = new byte[256]; result.BerryData = new byte[16]; result.EggGroupData = new byte[16]; result.DittoData = new byte[16]; result.TMData = new byte[16]; result.User = user; result.SaveName = addGame.SaveName; result.Game = Model_.Games.Where(e => e.GameId == addGame.Identifier).First(); Model_.Saves.Add(result); Model_.SaveChanges(); return true; }
static void Main(string[] args) { // connect to default instance on local machine Server server = new Server("."); ScriptingOptions so = new ScriptingOptions(); so.Triggers = true; Microsoft.SqlServer.Management.Smo.Transfer tr = new Transfer(); // Note: Make sure that srcdb exists on local machine's default instance tr.Database = server.Databases["srcdb"]; tr.DestinationDatabase = "targetdb"; tr.DestinationServer = "."; tr.DestinationLoginSecure = true; tr.Options = so; // Enumerate scripts List<string> scripts = tr.EnumScriptTransfer().ToList<string>(); // print generated scripts to console foreach (string script in scripts) { Console.WriteLine(script); Console.WriteLine("GO"); } }
private void successMessage(Transfer transfer) { TransferResultTxt.Foreground = new SolidColorBrush(Colors.Black); TransferInformationTxt.Foreground = new SolidColorBrush(Colors.Black); TransferResultTxt.Text = "The transfer was a success."; TransferInformationTxt.Text = "Amount:" + transfer.amount + "\n" + "To: " + transfer.recipientPhoneNum + "\n" + "Date: " + DateTime.Now + "\n" + "Transfer Id: " + transfer.id; }
public string Put(Transfer transferModel) { if (!ModelState.IsValid) { var values = ModelState.Values; foreach (var value in values) { return value.Errors[0].ErrorMessage; } } return "Data posted successfully"; }
public void Can_Encode_And_Decode_Binary_Fields() { var buffer = new ByteBuffer(1024, false); var value = new Transfer(); value.DeliveryTag = new byte[] { (byte)randNum.Next(0, 10), (byte)randNum.Next(0, 10), (byte)randNum.Next(0, 10), (byte)randNum.Next(0, 10) }; AmqpCodec.EncodeObject(buffer, value); var decodedValue = AmqpCodec.DecodeObject<Transfer>(buffer); CollectionAssert.AreEqual(value.DeliveryTag, decodedValue.DeliveryTag); }
protected override void OnNavigatedTo(NavigationEventArgs e) { List<Object> list = e.Parameter as List<Object>; p = list[0] as Person; response = list[1] as Transfer; if (response.transferStatus.Equals("SUCCESS")|| response.transferStatus.Equals("IN_PROGRESS")) { successMessage(response); } else { errorMessage(); } }
/// <summary> /// Imports content from a transferable item, or returns null if not possible. /// </summary> public static Disposable<Content> Import(Transfer.Item Item) { /*Transfer.StringItem si = Item as Transfer.StringItem; if (si != null) { return new StaticContent(StringType.Instance, si.String); } Transfer.FileItem fi = Item as Transfer.FileItem; if (fi != null) { return new StaticContent(FileType.Instance, fi.GetFile()); }*/ return null; }
public override string ToString() { s = (Transfer)base.Tag; Binding myBinding = new Binding("destination"); myBinding.Mode = BindingMode.TwoWay; myBinding.Source = s; txtdest.SetBinding(TextBox.TextProperty, myBinding); Binding descbinding = new Binding("Description"); descbinding.Mode = BindingMode.TwoWay; descbinding.Source = s; txtdesc.SetBinding(TextBox.TextProperty, descbinding); return base.ToString(); }
public Transfer MakeTransfer(string counterAccount, Money amount) { // 1. Check withdrawal limit: if (amount.GreaterThan(this.transferLimit)) { throw new BusinessException("Limit exceeded!"); } if (Accounts.IsValid(counterAccount)) { // <1> // 2. Look up counter account and make transfer object: CheckingAccount acct = Accounts.FindAcctByNumber(counterAccount); Transfer result = new Transfer(this, acct, amount); // <2> return result; } else { throw new BusinessException("Invalid account number!"); } }
private static void CopySourceDatabaseToTarget(DatabaseInfo source, DatabaseInfo target) { //Manually creating and opening connection because SMO with LocalDB has //a bug in opening the connection when querying the database. using (var connection = new SqlConnection(source.ConnectionString)) { try { var server = new Server(new ServerConnection(connection)); var transfer = new Transfer(server.Databases[source.Database]); transfer.DestinationServer = target.Server; transfer.DestinationDatabase = target.Database; transfer.CopyData = false; transfer.CopyAllObjects = false; transfer.CopyAllSchemas = true; transfer.CopyAllTables = true; transfer.Options.DriAll = true; transfer.CopyAllDefaults = true; transfer.CopyAllViews = false; transfer.CopyAllSynonyms = true; transfer.CreateTargetDatabase = true; transfer.DropDestinationObjectsFirst = true; //transfer.CopyAllUserDefinedFunctions = true; //transfer.CopyAllUserDefinedTypes = true; transfer.TargetDatabaseFilePath = GetServerDirectory(target); RemapServerFiles(server, transfer, source, target); transfer.TransferData(); } finally { connection.Close(); } } }
public Transfer MakeTransfer(string counterAccount, Money amount) { // 1. Assuming result is 9-digit bank account number, validate 11-test: if (Accounts.IsValid(counterAccount)) { // <1> // 2. Look up counter account and make transfer object: CheckingAccount acct = Accounts.FindAcctByNumber(counterAccount); Transfer result = new Transfer(this, acct, amount); // <2> if (result.CounterAccount.Equals(this.RegisteredCounterAccount)) { return result; } else { throw new BusinessException("Counter-account not registered!"); } } else { throw new BusinessException("Invalid account number!!"); } }
// TODO Build Matrix. private void init(Point center, Vector direction, double angle) { Matrix transformZero = new Matrix(); transformZero.Matr[0, 0] = Math.Pow(direction.Vect[0], 2) + (1 - Math.Pow(direction.Vect[0], 2)) * Math.Cos(angle); transformZero.Matr[0, 1] = direction.Vect[0] * direction.Vect[1] * (1 - Math.Cos(angle)) - direction.Vect[2] * Math.Sin(angle); transformZero.Matr[0, 2] = 0; transformZero.Matr[0, 3] = 0; transformZero.Matr[1, 0] = 0; transformZero.Matr[1, 1] = 0; transformZero.Matr[1, 2] = 0; transformZero.Matr[1, 3] = 0; transformZero.Matr[2, 0] = 0; transformZero.Matr[2, 1] = 0; transformZero.Matr[2, 2] = 0; transformZero.Matr[2, 3] = 0; transformZero.Matr[3, 0] = 0; transformZero.Matr[3, 1] = 0; transformZero.Matr[3, 2] = 0; transformZero.Matr[3, 3] = 1; // Transfer transfer0 = new Transfer(); }
/// <summary> /// Scripts the schema. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns></returns> public static string ScriptSchema(string connectionString) { StringBuilder result = new StringBuilder(); SqlConnection conn = new SqlConnection(connectionString); SqlConnectionStringBuilder cString = new SqlConnectionStringBuilder(connectionString); ServerConnection sconn = new ServerConnection(conn); Server server = new Server(sconn); Database db = server.Databases[cString.InitialCatalog]; Transfer trans = new Transfer(db); //set the objects to copy trans.CopyAllTables = true; trans.CopyAllDefaults = true; trans.CopyAllUserDefinedFunctions = true; trans.CopyAllStoredProcedures = true; trans.CopyAllViews = true; trans.CopyData = true; trans.CopySchema = true; trans.DropDestinationObjectsFirst = true; trans.UseDestinationTransaction = true; trans.Options.AnsiFile = true; trans.Options.ClusteredIndexes = true; trans.Options.DriAll = true; trans.Options.IncludeHeaders = true; trans.Options.IncludeIfNotExists = true; trans.Options.SchemaQualify = true; StringCollection script = trans.ScriptTransfer(); foreach(string s in script) result.AppendLine(s); result.AppendLine(); result.AppendLine(); return result.ToString(); }
private bool calculateTransferTimes() { int errorCount = 0; PathFinder pathFinder = new PathFinder(); pathFinder.LoadData(Path.Combine(config.KnowledgePath, "transfers.xml")); var stops = sdb.GetTable <Stop>().ToArray(); for (int i = 0; i < stops.Length - 1; i++) { for (int k = i + 1; k < stops.Length; k++) { if (PathFinder.IsNear(stops[i], stops[k])) { WalkPath path = null; short dist = (short)stops[i].StraightLineDistanceTo(stops[k]); bool notSame = PathFinder.IsNearNotSamePace(stops[i], stops[k]); if (notSame) { path = pathFinder.GetPath( new Point { Latitude = stops[i].Latitude, Longitude = stops[i].Longitude }, new Point { Latitude = stops[k].Latitude, Longitude = stops[k].Longitude } ); if (path == null) { errorCount++; continue; } dist = short.Parse(Math.Round(path.Distance).ToString()); } Transfer transfer1 = new Transfer { Distance = dist, Origin = stops[i], Target = stops[k] }; Transfer transfer2 = new Transfer { Distance = dist, Origin = stops[k], Target = stops[i] }; if (notSame) { if (stops[i].Latitude == path.From.Latitude && stops[i].Longitude == path.From.Longitude) { createInnerPoints(transfer1, path, false); createInnerPoints(transfer2, path, true); } else if (stops[k].Latitude == path.From.Latitude && stops[k].Longitude == path.From.Longitude) { createInnerPoints(transfer1, path, true); createInnerPoints(transfer2, path, false); } else { throw new Exception("Something is wrong."); } } sdb.AddEntity(transfer1); sdb.AddEntity(transfer2); } } log(i * 100 / (stops.Length - 1), null); } if (errorCount > 0) { log(0, "Missing transfers: " + errorCount + ". Calculate transfers then rerun the process."); return(false); } return(true); }
public void Can_Encode_And_Decode_Nested_Polymorphic_DescribedList() { var buffer = new ByteBuffer(1024, false); var value = new Transfer(); value.State = new Received() { SectionNumber = (uint)randNum.Next(0, 1000), SectionOffset = (uint)randNum.Next(0, 1000), }; AmqpCodec.EncodeObject(buffer, value); var decodedValue = AmqpCodec.DecodeObject<Transfer>(buffer); var decodedState = decodedValue.State as Received; Assert.NotNull(decodedState); Assert.AreEqual(((Received)value.State).SectionNumber, decodedState.SectionNumber); Assert.AreEqual(((Received)value.State).SectionOffset, decodedState.SectionOffset); }
public ChildGetterTransferPromptBackgrounAction(TransferPromptController controller, Transfer transfer, Path path, List<Path> isLoadingListingInBackground) { _controller = controller; _transfer = transfer; _path = path; _isLoadingListingInBackground = isLoadingListingInBackground; }
void upload_DoWork(object sender, DoWorkEventArgs e) { if (upload.CancellationPending) { e.Cancel = true; return; } bool again = false; bool attached = false; First: try { #region BackUp First if (!serverMode) { BackUpDatabase bak = new BackUpDatabase(); bak.doBackUp(); } #endregion #region InitVariables and Save Info In File progress = 1; again = false; attached = false; progress = 2; StreamWriter sw = new StreamWriter("UploadConfig.conf"); sw.WriteLine(destinationServer); sw.WriteLine(destinationDatabase); sw.WriteLine(username); sw.WriteLine(MyCrypt.encryptWithDefaultValues(pass)); if (serverMode) { sw.WriteLine(sourceServer); sw.WriteLine(sourceDatabase); } sw.Close(); sw.Dispose(); #endregion #region ServerCreation and Delete All Objects On Destination Database progress = 3; ServerConnection destinationCon; if (!String.IsNullOrEmpty(username) || !String.IsNullOrEmpty(pass)) { destinationCon = new ServerConnection(destinationServer, username, pass); } else { destinationCon = new ServerConnection(destinationServer); } Server destServer = new Server(destinationCon); String fp = Environment.CurrentDirectory + "\\query.sql"; FileInfo file = new FileInfo(fp); string script = file.OpenText().ReadToEnd(); script = script.Replace("dbo", username); try { destServer.ConnectionContext.ExecuteNonQuery(script); } catch (Exception excep) { MessageBox.Show("Error In Removing All Objects \n" + excep.Message, "ERROR", MessageBoxButton.OK, MessageBoxImage.Error); //MessageBox.Show("خطای تکنیکی \n" + excep.InnerException.Message + "\n" + excep.StackTrace, "خطا", MessageBoxButton.OK, MessageBoxImage.Error); } // Connect to server Server server = new Server(sourceServer); progress = 4; #endregion #region AttachDatabaseOnServer progress = 5; if (!serverMode) { System.Collections.Specialized.StringCollection files = new System.Collections.Specialized.StringCollection(); string datab = Environment.CurrentDirectory + "\\Negindb.mdf"; string logDb = Environment.CurrentDirectory + "\\Negindb_log.ldf"; files.Add(datab); server.AttachDatabase(sourceDatabase, files); attached = true; server.Refresh(); } progress = 6; #endregion #region DatabaseCreation progress = 7; // Get the Database to Transfer Database db = server.Databases[sourceDatabase]; progress = 8; #endregion #region TransferConfigAndRun progress = 9; // Setup transfer // I want to copy all objects // both Data and Schema Transfer t = new Transfer(db); t.CopyAllObjects = true; t.CopySchema = true; t.CopyData = true; t.DestinationServer = destinationServer; t.DestinationDatabase = destinationDatabase; // if username or password entered so server must be create for mixed authentication // else connect to server simple only with its name for windows authentication t.DestinationLoginSecure = true; // for windows authentication if (!String.IsNullOrEmpty(username) || !String.IsNullOrEmpty(pass)) { t.DestinationLoginSecure = false; t.DestinationLogin = username; t.DestinationPassword = pass; } t.Options.ContinueScriptingOnError = true; t.Options.IncludeIfNotExists = true; t.DropDestinationObjectsFirst = true; //t.UseDestinationTransaction = true; <<Check Here>> (long time exec) if (createDb == true) t.CreateTargetDatabase = true; progress = 10; // Transfer Schema and Data t.TransferData(); progress = 11; #endregion #region DestructEveryThing progress = 12; if (!serverMode) { server.DetachDatabase(sourceDatabase, false); } progress = 13; #endregion progress = 14; MessageBox.Show("پایگاه داده ها با موفقیت کامل بر روی وب قرار گرفت", "ارسال موفق", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { #region DetachDb if (attached && !serverMode) { try { Server server = new Server(sourceServer); server.DetachDatabase(sourceDatabase, false); } catch (Exception exc) { MessageBox.Show("خطایی در هنگام حذف پایگاه داده های موقتی در همین سیستم رخ داده است", "خطا", MessageBoxButton.OK, MessageBoxImage.Error); MessageBox.Show("خطای تکنیکی \n" + exc.Message + "\n" + exc.StackTrace, "خطا", MessageBoxButton.OK, MessageBoxImage.Error); if (exc.InnerException.InnerException != null) { MessageBox.Show("خطای تکنیکی داخلی \n" + exc.InnerException.InnerException.Message, "خطا", MessageBoxButton.OK, MessageBoxImage.Error); } } } #endregion #region HandlingLdfError if (ex.InnerException != null && ex.InnerException.InnerException != null && ex.InnerException.InnerException.Message.Contains("LDF' because it already exists")) { try { File.Delete(Environment.CurrentDirectory + "\\Negindb_log.ldf"); MessageBox.Show("در حین اجرای درخواست مشکلی بوجود آمد که توسط برنامه شناسایی و حل شد حال دوباره سعی می گردد", "حل مشکل", MessageBoxButton.OK, MessageBoxImage.Information); again = true; } catch (Exception exx) { MessageBox.Show("خطایی در هنگام ارسال رخ داده است", "خطا", MessageBoxButton.OK, MessageBoxImage.Error); MessageBox.Show("خطای تکنیکی \n" + exx.Message + "\n" + exx.StackTrace, "خطا", MessageBoxButton.OK, MessageBoxImage.Error); } } #endregion else { MessageBox.Show("خطایی در هنگام ارسال رخ داده است", "خطا", MessageBoxButton.OK, MessageBoxImage.Error); MessageBox.Show("خطای تکنیکی \n" + ex.Message + "\n" + ex.StackTrace, "خطا", MessageBoxButton.OK, MessageBoxImage.Error); if (ex.InnerException.InnerException != null) { MessageBox.Show("خطای تکنیکی داخلی \n" + ex.InnerException.InnerException.Message, "خطا", MessageBoxButton.OK, MessageBoxImage.Error); } } } #region Restore At Last if (!serverMode) { BackUpDatabase ba = new BackUpDatabase(); ba.doRestore(); } #endregion progress = 0; if (again) goto First; progressTimer.Stop(); //upload.CancelAsync(); }
public JsonNetResult GetTransfer(string transferId) { var user = AuthenticationCookieManager.GetAuthenticationCookie(); Transfer transfer = null; #region (Plan A) Get data from Redis Cache /* * try * { * IDatabase cache = CoreServiceSettings.RedisConnectionMultiplexers.AccountManager_Multiplexer.GetDatabase(); * * string hashKey = "accountbyid:" + accountId.ToString().Replace("-", ""); * string hashField = "creditcard"; * * var redisValue = cache.HashGet(hashKey, hashField); * * if (redisValue.HasValue) * { * accountCreditCardInfo = JsonConvert.DeserializeObject<AccountCreditCardInfo>(redisValue); * } * } * catch (Exception e) * { * var error = e.Message; * //TODO: Log: error message for Redis call * }*/ #endregion if (transfer == null) { #region (Plan B) Get data from WCF var platformBillingServiceClient = new PlatformBillingService.PlatformBillingServiceClient(); try { platformBillingServiceClient.Open(); transfer = platformBillingServiceClient.GetTransfer( transferId, Common.SharedClientKey);//, //user.Id, //PlatformAdminSite.AccountManagementService.RequesterType.PlatformUser); //Close the connection WCFManager.CloseConnection(platformBillingServiceClient); } catch (Exception e) { #region Manage Exception string exceptionMessage = e.Message.ToString(); var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name; // Abort the connection & manage the exception WCFManager.CloseConnection(platformBillingServiceClient, exceptionMessage, currentMethodString); #endregion } #endregion } JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResult.Data = transfer; return(jsonNetResult); }
public Tuple<Transfer, Entity> Transfer(int entryUserID, EntityCollection entityCollection, decimal[] baseTransfer) { User _user = (new UserAccessClient(EndpointName.UserAccess)).QueryuserID(entryUserID)[0]; Entity _exchangeDiffEntity = EntityService.Instance.LoadEntity(int.Parse(PropertiesService.Instance.GetPropertyValue(SpecialProperty.ExchangeDiff)[0].PropertyValue))[0]; WeeklySummaryCollection _weeklySummaryCollection = new WeeklySummaryCollection(); foreach (Entity _entity in entityCollection) { _weeklySummaryCollection.AddRange(GetWeeklySummary(_entity.EntityID)); } Record _record = RecordHelper.GenerateTempRecord(); _record.Type = RecordType.Transfer; int _index = 0; //Transfer Transfer _transfer = new Transfer() { RecordID = _record.RecordID, ToEntity = entityCollection[_index], Currency = new Currency() { CurrencyID = _weeklySummaryCollection[_index].BaseCurrency }, ExchangeRate = _weeklySummaryCollection[_index].ExchangeRate, BaseBefore = _weeklySummaryCollection[_index].BaseBalance, SGDBefore = _weeklySummaryCollection[_index].SGDBalance, }; foreach (Entity _entity in entityCollection) { if (_index == 0) { _index++; continue; } TransferDetail _transferDetail = new TransferDetail() { RecordID = _record.RecordID, Entity = _entity, BaseCurrency = _weeklySummaryCollection[_index].BaseCurrency, ExchangeRate = _weeklySummaryCollection[_index].ExchangeRate, BaseBefore = _weeklySummaryCollection[_index].BaseBalance, SGDBefore = _weeklySummaryCollection[_index].SGDBalance, }; _transferDetail.BaseTransfer = baseTransfer[_index]; _transferDetail.SGDTransfer = (_transferDetail.BaseTransfer / _transfer.ExchangeRate).ExtRound(); _transferDetail.ProfitAndLoss = (_transferDetail.BaseTransfer / _transferDetail.ExchangeRate).ExtRound() - _transferDetail.SGDTransfer; _transferDetail.BaseResult = 0; _transferDetail.SGDResult = 0; _transfer.TransferDetailCollection.Add(_transferDetail); _index++; } _transfer.BaseResult = _transfer.TransferDetailCollection.Sum(x=>x.BaseTransfer)+_transfer.BaseBefore; _transfer.SGDResult = (_transfer.BaseResult / _transfer.ExchangeRate).ExtRound(); //Record _index = 0; Journal _journal = new Journal() { RecordID = _record.RecordID, EntityID = entityCollection[_index].EntityID, BaseCurrency = _transfer.Currency.CurrencyID, ExchangeRate = _transfer.ExchangeRate, BaseAmount = _transfer.TransferDetailCollection.Sum(TransferDetail => TransferDetail.BaseTransfer), SGDAmount = _transfer.TransferDetailCollection.Sum(TransferDetail => TransferDetail.SGDTransfer), EntryUser = _user, }; _record.JournalCollection.Add(_journal); foreach (Entity _entity in entityCollection) { if (_index == 0) { _index++; continue; } _journal = new Journal() { RecordID = _record.RecordID, EntityID = _entity.EntityID, BaseCurrency = _transfer.TransferDetailCollection[_index - 1].BaseCurrency, ExchangeRate = _transfer.TransferDetailCollection[_index - 1].ExchangeRate, BaseAmount = _transfer.TransferDetailCollection[_index - 1].BaseTransfer * -1, SGDAmount = (_transfer.TransferDetailCollection[_index - 1].SGDTransfer + _transfer.TransferDetailCollection[_index - 1].ProfitAndLoss) * -1, EntryUser = _user, }; _record.JournalCollection.Add(_journal); _index++; } _journal = new Journal() { RecordID = _record.RecordID, EntityID = _exchangeDiffEntity.EntityID, SGDAmount = _transfer.TransferDetailCollection.Sum(TransferDetail => TransferDetail.ProfitAndLoss) }; _record.JournalCollection.Add(_journal); _transfer.RecordNotInDB = _record; return new Tuple<Transfer, Entity>(_transfer, _exchangeDiffEntity); }
public static bool Batchable(this Transfer transfer) { return(transfer.Batchable == null ? false : transfer.Batchable.Value); }
public ActionResult Save(int?id, int?senderOTP, string meterId, decimal?amount) { int rc; Topup[] topup = Topup.GetTopups(new TopupParameters { OTP = senderOTP }, out rc); //get senderotp meterid Meter[] meters = Meter.GetMeters(new MeterParameters { Meterid = topup[0].MeterId }, out rc); //get meterid customer Customer customer = (Session["customer"] as Customer); //check if senderotp customer as session customer Meter[] meters1 = Meter.GetMeters(new MeterParameters { Meterid = meterId }, out rc); // get userid will take the amount Customer customer1 = new Customer(meters1[0].UserId.Value); //get customer info if (Session["customer"] != null) { if (customer.Id == meters[0].UserId) { SMS sms = new SMS(); sms.To_number = customer.Telephone; sms.Msg = $"أهلا وسلا بك في تطبيقنا أنت تحاول الان تحويل قيمة {amount} الي حساب {customer1.Name} "; string status = sms.Send(); sms.SaveData(); SMS sms1 = new SMS(); sms.To_number = customer1.Telephone; sms.Msg = $"يحاول {customer.Name} تحويل قيمة {amount} الى عدادك"; string status1 = sms1.Send(); sms1.SaveData(); if (status == "OK" && status1 == "OK") { Transfer transfer = new Transfer(id, senderOTP, meterId, amount); Topup[] result = null; result = transfer.SaveData(); ViewBag.result = result; } } else if (customer.Id != meters[0].UserId) { Customer customer2 = new Customer(meters[0].UserId.Value); SMS sms = new SMS(); sms.To_number = customer2.Telephone; sms.Msg = $"أهلا وسلا بك في تطبيقنا أنت تحاول الان تحويل قيمة {amount} الي حساب {customer1.Name} "; string status = sms.Send(); sms.SaveData(); SMS sms1 = new SMS(); sms.To_number = customer1.Telephone; sms.Msg = $"يحاول {customer2.Name} تحويل قيمة {amount} الى عدادك"; string status1 = sms1.Send(); sms1.SaveData(); if (status == "OK" && status1 == "OK") { Transfer transfer = new Transfer(id, senderOTP, meterId, amount); Topup[] result = null; result = transfer.SaveData(); ViewBag.result = result; } } return(View()); } else { return(RedirectToAction("Save", "Transfer")); } }
public void Init(Transfer transfer) { this.lbName.Text = transfer.Name; this.simpleClampUC1.Init(transfer.Station); }
// GET: Transaction public ActionResult StartTransfer() { Transfer Transfer = new Transfer(); return(View(Transfer)); }
public void complete(Transfer t) { ; }
public void StartTransfer(Transfer transfer, TransferOptions options) { StartTransfer(transfer, options, new NoopTransferCallback()); }
/// <summary> /// /// </summary> /// <param name="transfer"></param> public void StartTransfer(Transfer transfer) { StartTransfer(transfer, new TransferOptions()); }
public string TestTransfer(int amount) { WxPayData wpd = Transfer.Run(amount, "你好雅心!", "okn8I0bp6xDylvYC9jlVwV9yGnFQ", ObjectId.GenerateNewId().ToString()); return(wpd.ToPrintStr()); }
private void tsbSaveStudy_Click(object sender, EventArgs e) { string UploadToFtp(string vPath, string mediaFile) { //上传到ftp FTPFileHelp ftp = Transfer.GetFtp(vPath, _serialData.存储ID, _dbHelper); if (ftp == null) { throw new Exception("FTP对象创建失败。"); } System.IO.FileInfo fi = new System.IO.FileInfo(mediaFile); ftp.MakeDirectory(ftp.VPath); ftp.FileUpLoad(ftp.VPath + fi.Name, fi); return(fi.Name); } try { int imgIndex = _images.FindIndex(T => T.MediaId == _selectImageID); if (imgIndex < 0) { MessageBox.Show("未检索到对应的检查图像,不能进行保存。", "提示"); return; } Image processImg = imageProcessControl1.ExportImage(); TileImageInfo imageInfo = _images[imgIndex]; //序列信息为空或为不同的申请,则需要重新获取序列信息 if (_serialData == null || _serialData.申请ID.Equals(_applyId) == false) { _serialData = _studyMediaModel.GetApplySerialInfoById(imageInfo.SerialId); } if (_serialData == null) { MessageBox.Show("尚未产生图像序列,不能进行保存。", "提示"); return; } StudyMediaData sourceMedia = _studyMediaModel.GetMediaInfoById(imageInfo.MediaId); string vPath = GetImageVpath(_applyId, _serialData.序列信息.申请日期); if (string.IsNullOrEmpty(sourceMedia.媒体信息.来源媒体ID)) { string localPath = FormatFilePath(Dir.GetAppTempDir() + @"\" + vPath); string mediaFile = FormatFilePath(localPath + @"\" + GetImgFileName("bmp")); if (System.IO.Directory.Exists(localPath) == false) { System.IO.Directory.CreateDirectory(localPath); } //保存修改图像 processImg.Save(mediaFile); //先上传图像到ftp string mediaName = UploadToFtp(vPath, mediaFile); //新增数据 StudyMediaData mediaData = new StudyMediaData(); mediaData.DcmUID = SqlHelper.GetDcmUID("3"); mediaData.媒体ID = SqlHelper.GetNumGuid(); mediaData.序列ID = _serialData.序列ID; mediaData.申请ID = _serialData.申请ID; mediaData.序号 = _studyMediaModel.GetMaxMediaNo(_serialData.序列ID) + 1; mediaData.媒体信息.媒体名称 = mediaName; mediaData.媒体信息.创建人 = _userData.Name; mediaData.媒体信息.创建日期 = _studyMediaModel.GetServerDate(); mediaData.媒体信息.媒体类型 = "图像";// MediaType.图像; mediaData.媒体信息.媒体描述 = ""; mediaData.媒体信息.来源媒体ID = sourceMedia.媒体ID; mediaData.媒体信息.最后处理人 = _userData.Name; mediaData.媒体信息.最后处理时间 = mediaData.媒体信息.创建日期; mediaData.媒体信息.最后版本 = 1; mediaData.媒体信息.CopyBasePro(mediaData); _studyMediaModel.NewMedia(mediaData); //添加图像到缩略图中显示 TileImageInfo newImg = new TileImageInfo(); newImg.CopyFrom(imageInfo); newImg.MediaId = mediaData.媒体ID; newImg.MediaName = mediaName; newImg.Order = Convert.ToString(mediaData.序号); newImg.File = mediaFile; _images.Add(newImg); imageView1.AddImage(newImg); imageView1.Selected(0); _selectImageID = newImg.MediaId; } else { //if (File.Exists(imageInfo.File)) //{ // File.Delete(imageInfo.File); //} //保存修改图像 processImg.Save(imageInfo.File); //先上传图像到ftp string mediaName = UploadToFtp(vPath, imageInfo.File); sourceMedia.媒体信息.最后版本 = sourceMedia.媒体信息.最后版本 + 1; sourceMedia.媒体信息.最后处理人 = _userData.Name; sourceMedia.媒体信息.最后处理时间 = _studyMediaModel.GetServerDate(); //更新数据库 _studyMediaModel.UpdateMedia(sourceMedia); //更新缩略图显示 imageView1.UpdateTileImage(null, imageInfo.File); } OnImageSave?.Invoke(imageInfo); } catch (Exception ex) { MsgBox.ShowException(ex, this); } }
/// <summary> /// Used to withdraw funds from your account. Note: please account for txfee. /// </summary> /// <param name="currency_name">base coin or quote coin name</param> /// <param name="address">coin address for send</param> /// <param name="tag">Secondary address identifier for coins like XRP,XMR etc.</param> /// <param name="quantity">amount of coin</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async Task <Transfer> CoinWithdraw(string currency_name, string address, string tag, decimal quantity, Dictionary <string, object> args = null) { var _result = new Transfer(); var _currency_id = await publicApi.LoadCurrencyId(currency_name); if (_currency_id.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _params = new Dictionary <string, object>(); { _params.Add("currency", _currency_id.result); _params.Add("quantity", quantity); _params.Add("address", address); privateClient.MergeParamsAndArgs(_params, args); } var _json_value = await privateClient.CallApiPost1Async("/v1.1/account/withdraw", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _json_data = privateClient.DeserializeObject <BWithdraw>(_json_value.Content); if (_json_data.success == true) { var _transfer = new BWithdrawItem { transferId = _json_data.result.transferId, transactionId = privateClient.GenerateNonceString(16), timestamp = CUnixTime.NowMilli, transactionType = TransactionType.Withdraw, currency = currency_name, toAddress = address, toTag = tag, amount = quantity, fee = 0, confirmations = 0, isCompleted = _json_data.success }; _result.result = _transfer; } else { _json_result.SetFailure(_json_data.message); } } _result.SetResult(_json_result); } else { _result.SetResult(_currency_id); } return(_result); }
public Transfer SelecteerTransfer(int transferID) { Transfer transfer = ctx.transfers.Single(s => s.transferid == transferID); return(transfer); }
static void Main(string[] args) { //Source Database ; // Connect to Server var fileName = "TrnasferDB_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log"; using (var logFile = File.CreateText(fileName)) { try { var sourceDb = (new Server(new ServerConnection( new SqlConnection( ConfigurationManager.ConnectionStrings["Source"].ToString() ) ) )).Databases[ConfigurationManager.AppSettings["SourceDB"]]; // Setup transfer // I want to copy all objects // both Data and Schema var dropScript = new Transfer(sourceDb) { CopyAllObjects = true, DropDestinationObjectsFirst = true, CopySchema = true, CopyData = false, Options = { IncludeIfNotExists = true,ScriptDrops = true,ScriptSchema = true,ContinueScriptingOnError = true} }; //t.DestinationDatabase = destinationDb.Name; //t.DestinationLogin = destinationDb.UserName; //t.DestinationPassword=destinationDb. //t.DestinationPassword = "******"; StringBuilder dropScriptSb = new StringBuilder(); dropScript.EnumScriptTransfer().ToList().ForEach(k => { Console.WriteLine(k); logFile.WriteLine(k); dropScriptSb.Append(k); }); // //destinationDb.ExecuteNonQuery(dropScriptSb.ToString()); var createScript = new Transfer(sourceDb) { CopyAllObjects = true, DropDestinationObjectsFirst = true, CopySchema = true, CopyData = false, Options = { IncludeIfNotExists = true,TargetServerVersion = SqlServerVersion.Version105} }; //t.DestinationDatabase = destinationDb.Name; //t.DestinationLogin = destinationDb.UserName; //t.DestinationPassword=destinationDb. //t.DestinationPassword = "******"; StringBuilder createScriptSb = new StringBuilder(); createScript.EnumScriptTransfer().ToList().ForEach(k => { Console.WriteLine(k); logFile.WriteLine(k); createScriptSb.Append(k); }); // var initScript = File.ReadAllText(ConfigurationManager.AppSettings["IntializationFile"]); Console.WriteLine(initScript); logFile.WriteLine(initScript); //destinationDb.ExecuteNonQuery(File.ReadAllText(ConfigurationManager.AppSettings["IntializationFile"])); } finally { logFile.Close(); logFile.Dispose(); } try { var readFile = File.ReadAllText(fileName); var destinationDb = (new Server(new ServerConnection( new SqlConnection( ConfigurationManager.ConnectionStrings["Destination"].ToString() ) ) )).Databases[ConfigurationManager.AppSettings["DestinationDB"]]; destinationDb.ExecuteNonQuery(readFile); } catch (Exception) { throw; } } //string sqlConnectionString = // "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True"; //FileInfo file = new FileInfo("C:\\myscript.sql"); //string script = file.OpenText().ReadToEnd(); //SqlConnection conn = new SqlConnection(sqlConnectionString); //Server server = new Server(new ServerConnection(conn)); //server.ConnectionContext.ExecuteNonQuery(script); //// Transfer Schema and Data //t.TransferData(); // Kill It }
/// <summary> /// Withdraw funds /// </summary> /// <param name="currency_name">base coin or quote coin name</param> /// <param name="address">coin address for send</param> /// <param name="tag">Secondary address identifier for coins like XRP,XMR etc.</param> /// <param name="quantity">amount of coin</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async ValueTask <Transfer> CoinWithdrawAsync(string currency_name, string address, string tag, decimal quantity, Dictionary <string, object> args = null) { var _result = new Transfer(); var _currency_id = await publicApi.LoadCurrencyIdAsync(currency_name); if (_currency_id.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _params = new Dictionary <string, object>(); { _params.Add("amount", quantity); // Withdrawal amount(maximum accurates to eight decimal places) _params.Add("currency", _currency_id.result); // asset being withdrawn _params.Add("receiveAddr", address); // Deposit address (Must be a verified address, BTS should in the form of "account _ memo". _params.Add("method", "withdraw"); //if (tag != null || tag != "") // _params.Add("addr-tag", tag); // only in xrp,xem,bts,steem,eos,xmr privateClient.MergeParamsAndArgs(_params, args); } var _json_value = await privateClient.CallApiGet1Async("/withdraw", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _json_data = privateClient.DeserializeObject <ZWithdraw>(_json_value.Content); { var _now = CUnixTime.NowMilli; var _withdraw = new ZWithdrawItem { transferId = _now.ToString(), // transferId 없음 transactionId = (_now * 1000).ToString(), // transactionId 없음 timestamp = _now, transactionType = TransactionType.Withdraw, currency = currency_name, toAddress = address, toTag = tag, amount = quantity, fee = 0, confirmations = 0, isCompleted = true }; _result.result = _withdraw; } } _result.SetResult(_json_result); } else { _result.SetResult(_currency_id); } return(_result); }
private void HandleTransferFrame(Transfer transfer, ByteBuffer buffer) { if (State != LinkStateEnum.ATTACHED) throw new AmqpException(ErrorCode.IllegalState, $"Received Transfer frame but link state is {State.ToString()}."); if (LinkCredit <= 0) throw new AmqpException(ErrorCode.TransferLimitExceeded, "The link credit has dropped to 0. Wait for messages to finishing processing."); if (!IsReceiverLink) throw new AmqpException(ErrorCode.NotAllowed, "A Sender Link cannot receive Transfers."); Delivery delivery; if (continuationDelivery == null) { // new transfer delivery = new Delivery(); delivery.Link = this; delivery.DeliveryId = transfer.DeliveryId.Value; delivery.DeliveryTag = transfer.DeliveryTag; delivery.Settled = transfer.Settled.IsTrue(); delivery.State = transfer.State; delivery.PayloadBuffer = new ByteBuffer(buffer.LengthAvailableToRead, true); delivery.ReceiverSettlementMode = receiverSettlementMode; if (transfer.ReceiverSettlementMode.HasValue) { delivery.ReceiverSettlementMode = (LinkReceiverSettlementModeEnum)transfer.ReceiverSettlementMode.Value; if (receiverSettlementMode == LinkReceiverSettlementModeEnum.First && delivery.ReceiverSettlementMode == LinkReceiverSettlementModeEnum.Second) throw new AmqpException(ErrorCode.InvalidField, "rcv-settle-mode: If the negotiated link value is first, then it is illegal to set this field to second."); } } else { // continuation if (transfer.DeliveryId.HasValue && transfer.DeliveryId.Value != continuationDelivery.DeliveryId) throw new AmqpException(ErrorCode.NotAllowed, "Expecting Continuation Transfer but got a new Transfer."); if (transfer.DeliveryTag != null && !transfer.DeliveryTag.SequenceEqual(continuationDelivery.DeliveryTag)) throw new AmqpException(ErrorCode.NotAllowed, "Expecting Continuation Transfer but got a new Transfer."); delivery = continuationDelivery; } if (transfer.Aborted.IsTrue()) { continuationDelivery = null; return; // ignore message } // copy and append the buffer (message payload) to the cached PayloadBuffer AmqpBitConverter.WriteBytes(delivery.PayloadBuffer, buffer.Buffer, buffer.ReadOffset, buffer.LengthAvailableToRead); if (transfer.More.IsTrue()) { continuationDelivery = delivery; return; // expecting more payload } // assume transferred complete payload at this point continuationDelivery = null; if (!delivery.Settled) { Session.NotifyUnsettledIncomingDelivery(this, delivery); } LinkCredit--; DeliveryCount++; Session.Connection.Container.OnDelivery(this, delivery); }
public void Release(Transfer s) { }
/// <summary> /// Scripts the schema. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns>A Hashtable containing a list of table names and their corresponding StringBuilder</returns> public static Dictionary<string, StringBuilder> ScriptSchema(string connectionString, DataProvider provider, bool oneFile) { StringBuilder result = new StringBuilder(); SqlConnection conn = new SqlConnection(connectionString); SqlConnectionStringBuilder cString = new SqlConnectionStringBuilder(connectionString); ServerConnection sconn = new ServerConnection(conn); Server server = new Server(sconn); Database db = server.Databases[cString.InitialCatalog]; Dictionary<string, StringBuilder> dict = new Dictionary<string, StringBuilder>(); if (oneFile) { Transfer trans = new Transfer(db); //set the objects to copy trans.CopyAllTables = false; trans.CopyAllDefaults = false; trans.CopyAllUserDefinedFunctions = true;//we don't have logic in SubSonic to decide which ones should or should not be generated, so better to be safe. trans.CopyAllStoredProcedures = false; trans.CopyAllViews = false; trans.CopySchema = false; trans.CopyAllLogins = false; foreach (Table tbl in db.Tables) { if (!CodeService.ShouldGenerate(tbl.Name, provider.Name)) continue; Utilities.Utility.WriteTrace(string.Format("Adding table {0}", tbl.Name)); trans.ObjectList.Add(tbl); } foreach (View v in db.Views) { if (!CodeService.ShouldGenerate(v.Name, provider.Name)) continue; Utilities.Utility.WriteTrace(string.Format("Adding view {0}", v.Name)); trans.ObjectList.Add(v); } foreach (Microsoft.SqlServer.Management.Smo.StoredProcedure sp in db.StoredProcedures) { if (!provider.UseSPs || !CodeService.ShouldGenerate(sp.Name, provider.IncludeProcedures, provider.ExcludeProcedures, provider)) continue; Utilities.Utility.WriteTrace(string.Format("Adding sproc {0}", sp.Name)); trans.ObjectList.Add(sp); } trans.CopyData = false; trans.DropDestinationObjectsFirst = true; trans.UseDestinationTransaction = true; trans.Options.AnsiFile = true; trans.Options.ScriptBatchTerminator = true; trans.Options.WithDependencies = true; //if this setting is false and you get an error, try installing SQL Server 2008 SP1 cumulative update 5 or higher..see http://support.microsoft.com/kb/976413 trans.Options.DriAll = true; trans.Options.IncludeHeaders = false; trans.Options.IncludeIfNotExists = true; trans.Options.SchemaQualify = true; Utilities.Utility.WriteTrace("Scripting objects..."); StringCollection script = trans.ScriptTransfer(); foreach (string s in script) result.AppendLine(s); result.AppendLine(); result.AppendLine(); dict.Add(provider.Name, result); return dict; } else { //use this method to append single tables and all of their dependencies one at a time Scripter scr = new Scripter(server); scr.Options.AnsiFile = true; scr.Options.ClusteredIndexes = true; scr.Options.DriAll = true; scr.Options.IncludeHeaders = false; scr.Options.IncludeIfNotExists = true; scr.Options.SchemaQualify = true; scr.Options.WithDependencies = false; UrnCollection u = new UrnCollection(); foreach (Table tbl in db.Tables) { if (CodeService.ShouldGenerate(tbl.Name, provider.Name)) { u = new UrnCollection(); u.Add(tbl.Urn); if (!tbl.IsSystemObject) { Utilities.Utility.WriteTrace(string.Format("Adding table {0}", tbl.Name)); result = new StringBuilder(); StringCollection sc = scr.Script(u); foreach (string s in sc) result.AppendLine(s); dict.Add(string.Concat("Table_",tbl.Name), result); } } } foreach (View v in db.Views) { if (CodeService.ShouldGenerate(v.Name, provider.Name)) { u = new UrnCollection(); u.Add(v.Urn); if (!v.IsSystemObject) { Utilities.Utility.WriteTrace(string.Format("Adding view {0}", v.Name)); result = new StringBuilder(); StringCollection sc = scr.Script(u); foreach (string s in sc) result.AppendLine(s); dict.Add(string.Concat("View_",v.Name), result); } } } foreach (Microsoft.SqlServer.Management.Smo.StoredProcedure sp in db.StoredProcedures) { if (CodeService.ShouldGenerate(sp.Name, provider.IncludeProcedures, provider.ExcludeProcedures, provider)) { u = new UrnCollection(); u.Add(sp.Urn); if (!sp.IsSystemObject) { Utilities.Utility.WriteTrace(string.Format("Adding sproc {0}", sp.Name)); result = new StringBuilder(); StringCollection sc = scr.Script(u); foreach (string s in sc) result.AppendLine(s); dict.Add(string.Concat("Sproc_",sp.Name), result); } } } foreach (UserDefinedFunction udf in db.UserDefinedFunctions) { if (CodeService.ShouldGenerate(udf.Name, provider.IncludeProcedures, provider.ExcludeProcedures, provider)) { u = new UrnCollection(); u.Add(udf.Urn); if (!udf.IsSystemObject) { Utilities.Utility.WriteTrace(string.Format("Adding udf {0}", udf.Name)); result = new StringBuilder(); StringCollection sc = scr.Script(u); foreach (string s in sc) result.AppendLine(s); dict.Add(string.Concat("UDF_", udf.Name), result); } } } return dict; } }
public TransferPromptListAction(TransferPromptModel model, TransferPromptController controller, SessionPool source, SessionPool destination, TransferItem directory, Transfer transfer, TransferItemCache cache) : base( controller, source, new InnerTransferPromptListWorker(model, controller, transfer, directory, cache)) { }
public void Setup(Transfer transfer) { _logger.Trace("Starting transfer setup"); TransferModel = new TransferModel(transfer); AutoItX.MouseClick(_pbv.CollectionTab); _tradeFileHandler.ClearTradableCards(_applicationSettings.BotName); _tradeFileHandler.WriteTradeFile(TransferModel.Cards.Values.ToList()); _tradeFileHandler.LoadTradableCards(); }
protected TransferPromptModel(TransferPromptController controller, SessionPool source, SessionPool destination, Transfer transfer) { _controller = controller; _source = source; _destination = destination; Transfer = transfer; _action = TransferAction.forName( PreferencesFactory.get() .getProperty(String.Format("queue.prompt.{0}.action.default", transfer.getType().name()))); }
protected TransferPromptModel(TransferPromptController controller, Transfer transfer) { _controller = controller; Transfer = transfer; }
public DownloadPromptController(WindowController parent, Transfer transfer, SessionPool source, SessionPool destination) : base(parent, transfer, source, destination) { TransferPromptModel = new DownloadPromptModel(this, source, destination, Transfer); }
internal abstract void OnTransfer(Delivery delivery, Transfer transfer, ByteBuffer buffer);
public static void Generate(IModel model, Aquarium aquarium, string fileName) { if (model == null || aquarium == null) { return; } fDocument = new RtfDocument(PaperSize.A4, PaperOrientation.Portrait, Lcid.English); try { var titleFont = CreateFont("", 16.0f, true, false, Color.Black); var textFont = CreateFont("", 12.0f, false, false, Color.Black); var dateFont = CreateFont("", 12.0f, true, true, Color.Black); AddParagraph(Localizer.LS(LSID.LogBook), titleFont, Align.Center, 0.0f, 16.0f); var events = new List <IEventEntity>(); events.AddRange(model.QueryTransfers(aquarium.Id)); events.AddRange(model.QueryNotes(aquarium.Id)); events.AddRange(model.QueryMaintenances(aquarium.Id)); events.AddRange(model.QueryMeasures(aquarium.Id)); events.Sort((x, y) => { return(x.Timestamp.CompareTo(y.Timestamp)); }); string prevDate = string.Empty, curDate; foreach (IEventEntity evnt in events) { curDate = ALCore.GetDateStr(evnt.Timestamp); if (!prevDate.Equals(curDate)) { AddParagraph(curDate, dateFont, Align.Left, 6.0f, 6.0f); prevDate = curDate; } if (evnt is Transfer) { Transfer rec = (Transfer)evnt; string strType = Localizer.LS(ALData.TransferTypes[(int)rec.Type]); string itName = model.GetRecordName(rec.ItemType, rec.ItemId); if (rec.Type == TransferType.Purchase || rec.Type == TransferType.Sale) { AddListItem(string.Format("{0}: {1} ({2} x {3:C2})", strType, itName, rec.Quantity, rec.UnitPrice), textFont); } else { AddListItem(string.Format("{0}: {1} ({2})", strType, itName, rec.Quantity), textFont); } } if (evnt is Note) { Note note = (Note)evnt; AddListItem(string.Format("{0}: {1}", note.Event, note.Content), textFont); } if (evnt is Maintenance) { Maintenance mnt = (Maintenance)evnt; string strType = Localizer.LS(ALData.MaintenanceTypes[(int)mnt.Type].Name); string notes = (string.IsNullOrEmpty(mnt.Note)) ? string.Empty : " (" + mnt.Note + ")"; AddListItem(string.Format("{0}: {1}{2}", strType, ALCore.GetDecimalStr(mnt.Value), notes), textFont); } if (evnt is Measure) { Measure msr = (Measure)evnt; AddListItem(string.Format("{0}: {1}", Localizer.LS(LSID.Measure), msr.ToString()), textFont); } } } finally { fDocument.save(fileName); } }
static void Main2(string[] args) { //string templateDbName = "MyTestDB"; //string templateServer = "localhost"; string templateDbName = "SemDissectorGlobalManagement"; string templateServer = "10.200.50.173"; //ServerConnection conn = new ServerConnection(""); Server server = new Server(templateServer); Database templateDb = server.Databases[templateDbName]; Transfer transfer = new Transfer(templateDb); //transfer.CopyAllDatabaseTriggers = true; transfer.CopyAllDefaults = true; transfer.CopyAllObjects = true; transfer.CopyAllUsers = true; transfer.CopyData = true; transfer.DestinationDatabase = "DBByCS"; transfer.CreateTargetDatabase = true; transfer.DestinationServer = "localhost"; //transfer.Scripter //transfer.Options.ExtendedProperties = true; Console.WriteLine("begin scriptTransfer。。。"); //StringCollection sqlStrs = transfer.ScriptTransfer(); //IEnumerable<string> sqlStrs2 = transfer.EnumScriptTransfer(); transfer.TransferData(); //Console.WriteLine("begin writeFiles。。。"); ////--------输出到文件----- //string sqlFilePath = @"D:\sqlScript.sql"; //using (StreamWriter sw = new StreamWriter(sqlFilePath, false, Encoding.UTF8)) //{ // foreach (var sql in sqlStrs) // { // sw.WriteLine(sql); // } //} //string sqlFilePath2 = @"D:\sqlScript2.sql"; //using (StreamWriter sw = new StreamWriter(sqlFilePath2, false, Encoding.UTF8)) //{ // foreach (var sql in sqlStrs2) // { // sw.WriteLine(sql); // } //} //--------输出到文件----- //--------输出到console----- //StringBuilder sb = new StringBuilder(); //foreach (var sql in sqlStrs) //{ // sb.AppendLine(sql); //} //Console.WriteLine(sb.ToString()); //--------输出到console----- //var conn = new ServerConnection(connection); //var server = new Microsoft.SqlServer.Management.Smo.Server("localhost"); //Database database = server.Databases[templateDbName]; //var transfer = new Transfer(database); //transfer.CopyAllObjects = true; //transfer.DropDestinationObjectsFirst = true; //transfer.CopyData = true; //transfer.CopySchema = true; //transfer.CreateTargetDatabase = true; //transfer.CopyAllPartitionFunctions = true; //transfer.CopyAllPartitionSchemes = true; //transfer.Options.DriForeignKeys = true; //transfer.Options.Indexes = true; //transfer.Options.DriAll = true; //transfer.Options.Triggers = true; //transfer.Options.NoCollation = false; //transfer.Options.IncludeDatabaseRoleMemberships = true; ////添加注释 //transfer.Options.ExtendedProperties = true; //return transfer.ScriptTransfer(); Console.WriteLine("end。。。"); Console.ReadKey(); }
public void CreateTransfer(Vector3 worldPosition, WaterCell water1, WaterCell water2, byte amount) { Transfer transfer = new Transfer(); transfer.amount = amount; transfer.cellFrom = water1; transfer.cellTo = water2; transfer.worldLocation = worldPosition; Transfers.Enqueue(transfer); }
private void ImagePageView(List <TileImageInfo> imgInfos) { // BackgroundWorker bgWork = new BackgroundWorker(); // bgWork.DoWork += DoWork; // bgWork.ProgressChanged += ProgessChanged; // bgWork.RunWorkerCompleted += WorkerCompleted; // bgWork.WorkerReportsProgress = false; // bgWork.WorkerSupportsCancellation = true; // imageView1.Clear(); // bgWork.RunWorkerAsync(imgRanges); //} //private object objLockWork = new object(); //private void DoWork(object sender, DoWorkEventArgs e) //{ // if (e.Argument == null) // { // throw new Exception("图像加载参数传递无效。"); // } //List<TileImageInfo> imgInfos = e.Argument as List<TileImageInfo>; imageView1.Clear(); if (imgInfos == null || imgInfos.Count <= 0) { throw new Exception("无需要加载的图像信息。"); } try { //lock (objLockWork) //{ FTPFileHelp ftp = null; imgInfos.Reverse(); foreach (TileImageInfo imgInfo in imgInfos) { string strErr = ""; if (File.Exists(imgInfo.File) == false) { if (ftp == null || Convert.ToString(ftp.Tag) != imgInfo.StorageId) { ftp = Transfer.GetFtp(imgInfo.VPath, imgInfo.StorageId, _dbHelper); ftp.Tag = imgInfo.StorageId; } try { ftp.FileDownLoad(ftp.VPath + imgInfo.MediaName, imgInfo.File, true); } catch (Exception ex) { strErr = ex.Message; } } if (File.Exists(imgInfo.File) == false) { imageView1.AddErrorImage("文件加载失败:" + strErr, imgInfo); } else { imageView1.AddImage(imgInfo); } } //} } catch (Exception ex) { throw new Exception("图像加载失败", ex); } }
public void Init(Transfer transfer = null) { _transfer = transfer == null ? new Transfer() : transfer; RaiseAllPropertiesChanged(); }
public bool SetSaveData(string username, Transfer.Saves data) { var user = Model_.Users.SingleOrDefault(e => e.Username == username); if (user == null) throw new Code.ExceptionResponse("Invalid user"); var save = user.Saves.SingleOrDefault(e => e.SaveName.ToLower() == data.SaveName.ToLower()); if (save == null) throw new Code.ExceptionResponse("No game found"); var actual = save; if (data.SaveData != null) actual.Code = Convert.FromBase64String(data.SaveData); if (data.AbilityData != null) actual.AbilityData = Convert.FromBase64String(data.AbilityData); if (data.BerryData != null) actual.BerryData = Convert.FromBase64String(data.BerryData); if (data.DittoData != null) actual.DittoData = Convert.FromBase64String(data.DittoData); if (data.EggGroupData != null) actual.EggGroupData = Convert.FromBase64String(data.EggGroupData); if (data.TMData != null) actual.TMData = Convert.FromBase64String(data.TMData); Model_.SaveChanges(); return true; }
public abstract bool DoInTransfer(Transfer transfer); //zapis do pliku tekstowego lub bazy danych public abstract bool DoOutTransfer(Transfer transfer);
static void Main(string[] args) { double batchDataSize = 100000; //kB bool showHelp = false; string sourceServerName = null, sourceUsername = null, sourcePassword = null, sourceDatabaseName = null, destinationServerName = null, destinationUsername = null, destinationPassword = null, destinationDatabaseName = null; bool clearDestinationDatabase = false, checkIdentityExists = false; bool periodicBackup = false; string backupFilePath = null; IEnumerable<string> ignoredTables = Enumerable.Empty<string>(); var optionSet = new OptionSet() { { "h|help", "show this message and exit", x => showHelp = x != null}, { "srcserver=", "source server (eg. db000.appharbor.net)", x => sourceServerName = x }, { "srcusername="******"username on source server", x => sourceUsername = x }, { "srcpassword="******"password on source server", x => sourcePassword = x }, { "srcdatabasename=", "source database name", x => sourceDatabaseName = x }, { "dstserver=", "destination server", x => destinationServerName = x }, { "dstusername="******"username on destination server", x => destinationUsername = x }, { "dstpassword="******"password on destination server", x => destinationPassword = x }, { "dstdatabasename=", "destination database name", x => destinationDatabaseName = x }, { "ignoretables=", "names of tables not to copy", x => ignoredTables = x.Split(',') }, { "cleardstdatabase", "clears the destination database before copying the data", x => clearDestinationDatabase = x != null }, { "checkidentityexists", "only reseed identity if table has identity column", x => checkIdentityExists = x != null }, { "periodicBackup", "create full backup version of the source database", x => periodicBackup = x != null }, { "backupFilePath", "backup file path if you want to store on an external backup disc, leave blank for default. If set ensure filepath exists and is writable", x => backupFilePath = x } }; try { optionSet.Parse(args); if (showHelp) { ShowHelp(optionSet); return; } //Use settings from App.config if specified so can be more conveniently configured as a scheduled task sourceServerName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceServerName"]) ? sourceServerName : ConfigurationSettings.AppSettings["sourceServerName"]; sourceUsername = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceUsername"]) ? sourceUsername : ConfigurationSettings.AppSettings["sourceUsername"]; sourcePassword = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourcePassword"]) ? sourcePassword : ConfigurationSettings.AppSettings["sourcePassword"]; sourceDatabaseName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceDatabaseName"]) ? sourceDatabaseName : ConfigurationSettings.AppSettings["sourceDatabaseName"]; destinationServerName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationServerName"]) ? destinationServerName : ConfigurationSettings.AppSettings["destinationServerName"]; destinationUsername = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationUsername"]) ? destinationUsername : ConfigurationSettings.AppSettings["destinationUsername"]; destinationPassword = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationPassword"]) ? destinationPassword : ConfigurationSettings.AppSettings["destinationPassword"]; destinationDatabaseName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationDatabaseName"]) ? destinationDatabaseName : ConfigurationSettings.AppSettings["destinationDatabaseName"]; ignoredTables = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["ignoredTables"]) ? ignoredTables : ConfigurationSettings.AppSettings["ignoredTables"].Split(','); clearDestinationDatabase = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["clearDestinationDatabase"]) ? clearDestinationDatabase : ConfigurationSettings.AppSettings["clearDestinationDatabase"] == "true"; checkIdentityExists = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["checkIdentityExists"]) ? checkIdentityExists : ConfigurationSettings.AppSettings["checkIdentityExists"] == "true"; periodicBackup = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["periodicBackup"]) ? periodicBackup : ConfigurationSettings.AppSettings["periodicBackup"] == "true"; backupFilePath = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["backupFilePath"]) ? backupFilePath : ConfigurationSettings.AppSettings["backupFilePath"]; if (sourceServerName == null) { throw new OptionException("source server not specified", "srcserver"); } if (sourceUsername == null && sourcePassword != null) { throw new OptionException("source username not specified", "srcusername"); } if (sourcePassword == null && sourceUsername != null) { throw new OptionException("source password not specified", "srcpassword"); } if (sourceDatabaseName == null) { throw new OptionException("source database name not specified", "srcdatabasename"); } if (destinationServerName == null) { throw new OptionException("destination server not specified", "dstserver"); } if (destinationUsername == null && destinationPassword != null) { throw new OptionException("destination username not specified", "dstusername"); } if (destinationPassword == null && destinationUsername != null) { throw new OptionException("destination password not specified", "dstpassword"); } if (!periodicBackup && destinationDatabaseName == null) //for periodic backup we create databases daily so not required { throw new OptionException("destination database name not specified", "dstdatabasename"); } } catch (OptionException exception) { Console.Write(string.Format("{0}: ", AppDomain.CurrentDomain.FriendlyName)); Console.WriteLine(exception.Message); Console.WriteLine("Try {0} --help for more information", AppDomain.CurrentDomain.FriendlyName); return; } Console.WriteLine("Retrieving source database table information..."); var usingTrustedConnection = string.IsNullOrEmpty(sourceUsername) && string.IsNullOrEmpty(sourcePassword); var sourceConnection = usingTrustedConnection ? new ServerConnection(sourceServerName) { LoginSecure = true } : new ServerConnection(sourceServerName, sourceUsername, sourcePassword); var sourceServer = new Server(sourceConnection); var sourceDatabase = sourceServer.Databases[sourceDatabaseName]; var tables = sourceDatabase.Tables .OfType<Table>() .Where(x => !x.IsSystemObject) .Select(x => '[' + x.Schema + ']' + ".[" + x.Name + ']') .ToList(); var actualExcludedTables = tables.Intersect(ignoredTables); if (actualExcludedTables.Any()) { Console.WriteLine(string.Format("Ignoring: {0}", string.Join(",", actualExcludedTables))); } tables = tables.Except(ignoredTables).ToList(); Console.WriteLine(string.Format("Copying {0} tables: {1}", tables.Count(), string.Join(",", tables))); var destinationConnectionString = GetConnectionString(destinationServerName, destinationDatabaseName, destinationUsername, destinationPassword); var sourceConnectionString = GetConnectionString(sourceServerName, sourceDatabaseName, sourceUsername, sourcePassword); var watch = Stopwatch.StartNew(); // clear the data before copying if (!periodicBackup && clearDestinationDatabase) //no need to clear if doing backups { using (var connection = new SqlConnection(destinationConnectionString)) { using (SqlCommand command = connection.CreateCommand()) { // http://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql/156813#156813 StringBuilder commandBuilder = new StringBuilder(); commandBuilder.Append( @" -- disable all constraints EXEC sp_msforeachtable ""ALTER TABLE ? NOCHECK CONSTRAINT all"" -- delete data in all tables EXEC sp_msforeachtable ""DELETE FROM ?"" -- enable all constraints exec sp_msforeachtable ""ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"" "); if (checkIdentityExists) { // http://stackoverflow.com/questions/6542061/reseed-sql-server-identity-columns commandBuilder.Append( @"-- reseed (auto increment to 0) on user tables with identity column DECLARE @reseedSql NVARCHAR(MAX); SET @reseedSql = N''; SELECT @reseedSql = @reseedSql + N'DBCC CHECKIDENT(''' + QUOTENAME(OBJECT_SCHEMA_NAME(col.[object_id])) + '.' + QUOTENAME(OBJECT_NAME(col.[object_id])) + ''', RESEED, 0);' + CHAR(13) + CHAR(10) FROM sys.columns as col JOIN sys.tables as tbl ON col.[object_id] = tbl.[object_id] WHERE tbl.[type] = 'U' AND col.[is_identity] = 1; EXEC sp_executesql @reseedSql;"); } else { commandBuilder.Append(@" -- reseed (auto increment to 0) EXEC sp_msforeachtable ""DBCC CHECKIDENT ( '?', RESEED, 0)"" "); } command.CommandText = commandBuilder.ToString(); Console.WriteLine("Clearing the destination database"); connection.Open(); command.ExecuteNonQuery(); } } } /// If we are running to create a periodic backup if(periodicBackup) { Console.WriteLine("Creating backup database with filename format databasename_dd-MMM-HH-mm-ss"); //create a database name based on the date var dateFilename = DateTime.UtcNow.ToString("dd-MMM-HH-mm-ss"); var newDatabaseName = String.Format("{0}_{1}", sourceDatabaseName, dateFilename); var newDatabaseData = String.Format("{0}_{1}_Data", sourceDatabaseName, dateFilename); var mdfPath = String.Format("{0}{1}_{2}.mdf", backupFilePath, sourceDatabaseName, dateFilename); var newDatabaseLog = String.Format("{0}_{1}_log", sourceDatabaseName, dateFilename); var ldfPath = String.Format("{0}{1}_{2}_log.ldf", backupFilePath, sourceDatabaseName, dateFilename); try { using (SqlConnection sourceCon = new SqlConnection(sourceConnectionString)) { ServerConnection sourceServerConnection = new ServerConnection(sourceCon); Server sourceServ = new Server(sourceServerConnection); Database db; db = sourceServ.Databases[sourceDatabaseName]; //Create a new database that is to be destination database. using (SqlConnection destCon = new SqlConnection(destinationConnectionString)) { ServerConnection destinationServerConnection = new ServerConnection(destCon); Server destinationServer = new Server(destinationServerConnection); Database dbCopy; dbCopy = new Database(destinationServer, newDatabaseName); //if being backed up to non default location if (!String.IsNullOrEmpty(backupFilePath)) { //Adding Primary FileGroup dbCopy.FileGroups.Add(new FileGroup(dbCopy, "PRIMARY")); DataFile dtPrimary = new DataFile(dbCopy.FileGroups["PRIMARY"], newDatabaseData, mdfPath); dtPrimary.GrowthType = FileGrowthType.Percent; dtPrimary.Growth = 7; dbCopy.FileGroups["PRIMARY"].Files.Add(dtPrimary); //Adding LogFile LogFile logFile = new LogFile(dbCopy, newDatabaseLog, ldfPath); logFile.GrowthType = FileGrowthType.Percent; logFile.Growth = 7; dbCopy.LogFiles.Add(logFile); } //Create database. dbCopy.Create(); //Define a Transfer object and set the required options and properties. Transfer xfr; xfr = new Transfer(db); // additional options can be set here if required xfr.Options.WithDependencies = true; xfr.Options.ContinueScriptingOnError = true; xfr.DestinationDatabase = newDatabaseName; //if being backed up to non default location if (!String.IsNullOrEmpty(backupFilePath)) { xfr.TargetLogFilePath = ldfPath; xfr.TargetDatabaseFilePath = mdfPath; } xfr.CopyData = false; // not used as we are doing this below and was causing memory issues for me doing it this way with App Harbor db server - but would be simpler xfr.DestinationServer = destinationServer.Name; xfr.DestinationLoginSecure = true; xfr.CopySchema = true; xfr.CopyAllDefaults = true; xfr.CopyAllSchemas = true; xfr.CopyAllStoredProcedures = true; xfr.CopyAllTables = true; xfr.CopyAllUserDefinedAggregates = true; xfr.CopyAllUserDefinedDataTypes = true; xfr.CopyAllUserDefinedFunctions = true; xfr.CopyAllUserDefinedTableTypes = true; xfr.CopyAllUserDefinedTypes = true; xfr.CopyAllViews = true; xfr.Options.Default = true; xfr.Options.Indexes = true; xfr.Options.DriDefaults = true; xfr.Options.DriAllKeys = true; xfr.Options.DriForeignKeys = true; xfr.Options.DriIndexes = true; xfr.Options.DriPrimaryKey = true; xfr.Options.DriUniqueKeys = true; xfr.TransferData(); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //reset this to the new database now it's been created destinationConnectionString = GetConnectionString(destinationServerName, newDatabaseName, destinationUsername, destinationPassword); } foreach (var table in tables) { using (var connection = new SqlConnection(sourceConnectionString)) { double rowBatchSize = 10000; double rows = 0; double dataSize; connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = string.Format("exec sp_spaceused '{0}'", table); using (var reader = command.ExecuteReader()) { reader.Read(); var rowString = (string)reader["rows"]; rows = double.Parse(rowString); var dataSizeString = (string)reader["data"]; dataSize = double.Parse(dataSizeString.Split(' ').First()); //kB if (rows > 0 && dataSize > 0) { double rowSize = dataSize / rows; rowBatchSize = (int)(batchDataSize / rowSize); } } } if (rows > 0) { var columns = GetColumnNames(connection, table); Console.Write(string.Format("Copying {0} - {1} rows, {2:0.00} MB: ", table, rows, dataSize/1024)); using (var command = connection.CreateCommand()) { command.CommandText = string.Format("select * from {0}", table); using (var reader = command.ExecuteReader()) { using (var bulkCopy = new SqlBulkCopy( destinationConnectionString, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.TableLock)) { bulkCopy.NotifyAfter = Math.Max((int)rows / 10, 1); bulkCopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(SqlRowsCopied); bulkCopy.DestinationTableName = table; bulkCopy.BatchSize = (int)rowBatchSize; bulkCopy.BulkCopyTimeout = int.MaxValue; foreach (var columnName in columns) { bulkCopy.ColumnMappings.Add(columnName, columnName); } bulkCopy.WriteToServer(reader); } } } Console.WriteLine(); } else { Console.WriteLine(string.Format("{0} had no rows", table)); } } } watch.Stop(); Console.WriteLine("Copy complete, total time {0} s", watch.ElapsedMilliseconds/1000); }
internal override void OnTransfer(Delivery delivery, Transfer transfer, ByteBuffer buffer) { throw new InvalidOperationException(); }
public Transfer Subtotal(int entryUserID, Entity entity) { User _user = (new UserAccessClient(EndpointName.UserAccess)).QueryuserID(entryUserID)[0]; Dictionary<Entity, WeeklySummary> _pair = new Dictionary<Entity, WeeklySummary>(); HasWeeklySummary(entity, _pair); Record _record = RecordHelper.GenerateTempRecord(); _record.Type = RecordType.WinAndLoss; WeeklySummary _weeklySummary = _pair[entity]; //Transfer Transfer _transfer = new Transfer() { RecordID = _record.RecordID, ToEntity = entity, }; if (_weeklySummary == null) { using (WeeklySummaryAccessClient _weeklySummaryAccessClient = new WeeklySummaryAccessClient(EndpointName.WeeklySummaryAccess)) { _weeklySummaryAccessClient.Insert1(_weeklySummary = new WeeklySummary(PeriodService.Instance.GetCurrentPeriod()[0], entity)); } } _transfer.ExchangeRate = _weeklySummary.ExchangeRate; _transfer.BaseBefore = _weeklySummary.BaseBalance; _transfer.SGDBefore = _weeklySummary.SGDBalance; _transfer.Currency.CurrencyID = _weeklySummary.BaseCurrency; foreach (Entity _entity in _pair.Keys) { if (_entity == entity) { continue; } else if ((_weeklySummary = _pair[_entity]) == null) { using (WeeklySummaryAccessClient _weeklySummaryAccessClient = new WeeklySummaryAccessClient(EndpointName.WeeklySummaryAccess)) { _weeklySummaryAccessClient.Insert1(_weeklySummary = new WeeklySummary(PeriodService.Instance.GetCurrentPeriod()[0], _entity)); } } TransferDetail _transferDetail = new TransferDetail() { RecordID = _record.RecordID, Entity = _entity, BaseCurrency = _weeklySummary.BaseCurrency, ExchangeRate = _weeklySummary.ExchangeRate, BaseBefore = _weeklySummary.BaseBalance, SGDBefore = _weeklySummary.SGDBalance, }; _transferDetail.BaseTransfer = _transferDetail.BaseBefore; _transferDetail.SGDTransfer = _transferDetail.SGDBefore; _transferDetail.ProfitAndLoss = 0; _transferDetail.BaseResult = 0; _transferDetail.SGDResult = 0; _transfer.TransferDetailCollection.Add(_transferDetail); } _transfer.SGDResult = _transfer.TransferDetailCollection.Sum(TransferDetail => TransferDetail.SGDBefore).ExtRound(); _transfer.BaseResult = (_transfer.SGDResult * _transfer.ExchangeRate).ExtRound(); //Record Journal _journal = new Journal() { RecordID = _record.RecordID, EntityID = entity.EntityID, BaseCurrency = entity.Currency.CurrencyID, ExchangeRate = _transfer.ExchangeRate, BaseAmount = _transfer.TransferDetailCollection.Sum(TransferDetail => TransferDetail.BaseTransfer), SGDAmount = _transfer.TransferDetailCollection.Sum(TransferDetail => TransferDetail.SGDTransfer), EntryUser = _user, }; _record.JournalCollection.Add(_journal); foreach (Entity _entity in _pair.Keys) { if (_entity == entity) { continue; } else if ((_weeklySummary = _pair[_entity]) == null) { continue; } _journal = new Journal() { RecordID = _record.RecordID, EntityID = _entity.EntityID, BaseCurrency = _weeklySummary.BaseCurrency, ExchangeRate = _weeklySummary.ExchangeRate, BaseAmount = _weeklySummary.BaseBalance * -1, SGDAmount = _weeklySummary.SGDBalance * -1, EntryUser = _user, }; _record.JournalCollection.Add(_journal); } _transfer.RecordNotInDB = _record; return _transfer; }
private static void Main() { // 2. var customer = new Customer { Address = "Perla 3", City = "Sofia", CompanyName = "PeshoEOOD", ContactName = "Pesho", ContactTitle = "Pesho", Country = "Bulgaria", CustomerID = "AAAAA", Fax = "222/ 222222", Phone = "089999999", PostalCode = "1367", Region = null, }; DAO.InsertCustomer(customer); // The last one in database //DAO.DeleteCustomer("WOLZA"); var newCust = new Customer(); newCust.Address = "Pirotska 12"; // It must update only Address in concrete CustomerID DAO.UpdateCustomer("AAAAA", newCust); Console.WriteLine(); // 3. var customers = FindAllCustomersByOrdersIn1997AndShippedToCanada(); foreach (var cust in customers) { Console.WriteLine(cust.ContactName); } Console.WriteLine(); // 4. FindAllCustomersByOrdersIn1997AndShippedToCanadaNative(); Console.WriteLine(); // 5. string region = "Lara"; DateTime startDate = new DateTime(1996, 10, 16); DateTime endDate = new DateTime(1996, 11, 13); var orders = FindAllOrdersRegionAndPeriod(region, startDate, endDate); foreach (var order in orders) { Console.WriteLine(order.OrderDate + "->" + order.RequiredDate + "->" + order.ShipRegion); } Console.WriteLine(); // 6. Use SQL Server Management Objects (SMO) library installed with NuGet Packages // Change server name for your computer var server = new Server(@"DESKTOP-CTR5RI6\SQLEXPRESS"); Database newdb = new Database(server, "NorthwindTwin"); newdb.Create(); Transfer transfer = new Transfer(server.Databases["Northwind"]); transfer.CopyAllObjects = true; transfer.CopyAllUsers = true; transfer.Options.WithDependencies = true; transfer.DestinationDatabase = newdb.Name; transfer.DestinationServer = server.Name; transfer.DestinationLoginSecure = true; transfer.CopySchema = true; transfer.CopyData = true; transfer.Options.ContinueScriptingOnError = true; transfer.TransferData(); // 7. var db1 = new NorthwindEntities(); var db2 = new NorthwindEntities(); var customer1 = db1.Customers.Where(cust => cust.ContactName == "Ana Trujillo").FirstOrDefault(); var customer2 = db1.Customers.Where(cust => cust.ContactName == "Ana Trujillo").FirstOrDefault(); customer1.ContactName = "Pesho"; customer2.ContactName = "Gosho"; db1.SaveChanges(); db2.SaveChanges(); db1.Dispose(); db2.Dispose(); //Concurrency control //Entity Framework uses optimistic concurrency control (no locking by default) //Provides automatic concurrency conflict detection and means for conflicts resolution // 8. EmployeeExtension }
public static bool Aborted(this Transfer transfer) { return(transfer.Aborted == null ? false : transfer.Aborted.Value); }
public IActionResult OnPostRemove(long accountNumber, string returnUrl) { Transfer.RemoveLine(Transfer.Lines.First(tl => tl.Account.AccountNumber == accountNumber).Account); return(RedirectToPage(new { returnUrl = returnUrl })); }
public UploadPromptController(WindowController parent, Transfer transfer) : base(parent, transfer) { }
private void _ws_OnMessage(object sender, MessageEventArgs e) { //Pre-parsing message. Doesn't fully deserialize now to dynamic to improve performance if (e.Data.StartsWith("{\"stream\":\"orders\"")) { Orders.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"trades\"")) { Trades.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"accounts\"")) { Account.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"marketDiff\"")) { DiffDepth.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"marketDepth\"")) { BookDepth.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"blockheight\"")) { BlockHeight.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"allMiniTickers\"")) { AllMiniTicker.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"miniTicker\"")) { IndividualMiniTicker.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"allTickers\"")) { AllTicker.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"ticker\"")) { IndividualTicker.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"kline_")) { Klines.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"transfers\"")) { Transfer.ProcessRecievedMessage(e.Data); } else if (e.Data.StartsWith("{\"stream\":\"transfers\"")) { Transfer.ProcessRecievedMessage(e.Data); } else if (!string.IsNullOrWhiteSpace(e.Data)) { //We might received an error text from backend, have to raise attention if so. if (e.Data.Contains("error")) { throw new WebSocketConnectionException(string.Format("Websocket DEX backend sent error message: {0}", e.Data)); } } }
/// <summary> /// Withdraws funds to a crypto address. /// </summary> /// <param name="currency_name">base coin or quote coin name</param> /// <param name="address">coin address for send</param> /// <param name="tag">Secondary address identifier for coins like XRP,XMR etc.</param> /// <param name="quantity">amount of coin</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async ValueTask <Transfer> CoinWithdraw(string currency_name, string address, string tag, decimal quantity, Dictionary <string, object> args = null) { var _result = new Transfer(); var _currency_id = await publicApi.LoadCurrencyId(currency_name); if (_currency_id.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _params = new Dictionary <string, object>(); { _params.Add("currency", _currency_id.result); _params.Add("amount", quantity); _params.Add("crypto_address", address); privateClient.MergeParamsAndArgs(_params, args); } var _json_value = await privateClient.CallApiPost1Async($"/withdrawals/crypto", _params); #if RAWJSON _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _json_data = privateClient.DeserializeObject <GTransferItem>(_json_value.Content); if (String.IsNullOrEmpty(_json_data.transferId) == false) { var _withdraw = new GTransferItem { transferId = _json_data.transferId, transactionId = privateClient.GenerateNonceString(16), timestamp = CUnixTime.NowMilli, transactionType = TransactionType.Withdraw, currency = _json_data.currency, toAddress = address, toTag = tag, amount = _json_data.amount, fee = 0, confirmations = 0, isCompleted = true }; _result.result = _withdraw; } else { _json_result.SetFailure(); } } _result.SetResult(_json_result); } else { _result.SetResult(_currency_id); } return(_result); }
public TransferModel(IBankRepository repo, Transfer transferService) { repository = repo; Transfer = transferService; }
public UploadPromptModel(TransferPromptController controller, Transfer transfer) : base(controller, transfer) { ; }
public abstract bool DoInTransfer(Transfer transfer); //zapis do pliku tekstowego lub bazy danych