public FormMain() { InitializeComponent(); workersFarm.WorkerProcessType = workerProcessType; workersFarm.Log = (msg) => { if (msg.StartsWith("stats")) { var statType = msg.Replace("stats ", ""); switch (statType) { case "done": lblDone.Text = (int.Parse(lblDone.Text) + 1).ToString(); break; case "failed": lblFailed.Text = (int.Parse(lblFailed.Text) + 1).ToString(); break; case "contentFound": lblContentFound.Text = (int.Parse(lblContentFound.Text) + 1).ToString(); break; } } else if (cbShowLog.Checked) Console.Items.Add(msg); }; wp = (MyWorkerProcess)Activator.CreateInstance(workerProcessType); db = wp.GetNewDatabaseInstance(); }
/// <summary> /// Returns the instance of DIData based on the importFile type /// </summary> /// <param name="importFileType"></param> /// <param name="sourceFileNamesWPath">List of source files with path</param> /// <param name="targetFileNamesWPath">Target file name with path</param> /// <param name="tempFolderPath">Temproray folder path</param> /// <param name="htmlLogOutputPath">Spreadsheet folder path</param> /// <returns></returns> public static DIData CreateInstance(DIImportFileType importFileType, List<string> sourceFileNamesWPath, string targetFileNamesWPath, string tempFolderPath, string htmlLogOutputPath) { DIData RetVal = null; switch (importFileType) { case DIImportFileType.DataEntrySpreasheet: RetVal = new DataEntrySpreadsheets(sourceFileNamesWPath, targetFileNamesWPath, tempFolderPath, htmlLogOutputPath); break; case DIImportFileType.Database: RetVal = new Database.Database(sourceFileNamesWPath, targetFileNamesWPath, tempFolderPath, htmlLogOutputPath); break; case DIImportFileType.Template: break; case DIImportFileType.SDMXXml: RetVal = new SDMX.SDMXXml(sourceFileNamesWPath, targetFileNamesWPath, tempFolderPath, htmlLogOutputPath); break; case DIImportFileType.CSV: RetVal = new CSV.CSVImporter(sourceFileNamesWPath, targetFileNamesWPath, tempFolderPath, htmlLogOutputPath); break; default: break; } if (RetVal != null) { RetVal.ImportFileType = importFileType; } return RetVal; }
private void btnShowDatabases_Click(object sender, EventArgs e) { DatabaseProvider provider = cbProvider.Text.ToEnum<DatabaseProvider>(); if (provider == DatabaseProvider.SQLite) { OpenFileDialog ofd = new OpenFileDialog(); ofd.CheckFileExists = false; if (ofd.ShowDialog() == DialogResult.OK) txtDBName.Text = ofd.FileName; } else { Database.Database db = new Database.Database(); db.SetConnectionString(provider, txtHost.Text, null, txtUserName.Text, txtPassword.Text); db.CreateDbProvider(false); ListBoxDialog lbd = new ListBoxDialog(); lbd.ListBox.DataSource = db.GetDatabases(); lbd.ListBox.SelectionMode = SelectionMode.One; lbd.Message = "Select a database"; if (lbd.ShowDialog() == DialogResult.OK) txtDBName.Text = lbd.GetSelectedItems<string>()[0]; } }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { db = new Database.Database(); } else { db = new Database.Database(); } }
public OrderDialog() { InitializeComponent(); Database.Database db = new Database.Database(); ClientSelect.ItemsSource = from client in db.Clients select client; ProductItemSource = (from product in db.Products select product).ToList(); OrderElemList.ItemsSource = ListOrderElements; this.ListOrderElements.Add(new OrderElement { Order = this.DataContext as Order, LastModification = DateTime.Now }); }
public static Database.Database GetDb(int index) { try { if (!listDb.ContainsKey(index)) listDb[index] = new Database.Database(Provider.GetConnectionString(index), Provider.GetDbProvider(index), Application.ExecutablePath.ToLowerInvariant().Replace("cinar.cms.desktopeditor.exe", "db" + index + ".config")); return listDb[index]; } catch{ return null; } }
public static void Run() { Database.Database db = new Database.Database(DatabaseProvider.MySQL, "localhost", "issuetracking", "root", "bk", 30); foreach (var table in db.Tables) { Console.WriteLine(table.Name); foreach (var column in table.Columns) { Console.WriteLine(" - " + column.Name); } } }
/// <summary></summary> /// <param name="database"></param> /// <param name="session"></param> public FSDeletionHandler(Database.Database database, ISession session) { if (database == null) { throw new ArgumentNullException("Argument null in FSDeletionHandler Constructor", "database"); } if (session == null) { throw new ArgumentNullException("Argument null in FSDeletionHandler Constructor", "session"); } this.database = database; this.session = session; }
public Home() { InitializeComponent(); try { var db = new Database.Database(); } catch (Exception e) { MessageBox.Show(e.Message); } }
public void InitializeDatabase() { if (Database == null) { Database = new Database.Database(Provider, Host, DbName, UserName, Password, TIMEOUT, null, CreateDatabaseIfNotExist); } else { Database.DefaultCommandTimeout = TIMEOUT; Database.SetConnectionString(Provider, Host, DbName, UserName, Password); Database.SetCollectionParents(); Database.CreateDbProvider(false); } }
/// <summary> /// Ładuje wszystkie animacje z bazy danych. /// </summary> public static void LoadAnimations() { double startTime = Global.GetTimestampMs(); using (Database.Database db = new Database.Database()) { List <Animation> animations = db.Animations.ToList(); foreach (Animation entry in animations) { AnimationsList.Add(entry.AnimationCommand, entry); } Log.ConsoleLog("ANIMATIONS", $"Załadowano animacje ({AnimationsList.Count}) | {Global.GetTimestampMs() - startTime}ms"); } }
/// <summary> /// Laduje interiory z bazy danych do pamięci. /// </summary> public static void LoadInteriors() { double startTime = Global.GetTimestampMs(); using (Database.Database db = new Database.Database()) { List <Interior> interiors = db.Interiors.ToList(); foreach (Interior entry in interiors) { InteriorsList.Add(entry.Id, entry); } Log.ConsoleLog("INTERIORS", $"Załadowano interiory ({InteriorsList.Count}) | {Global.GetTimestampMs() - startTime}ms"); } }
public static void LoadCorners() { double startTime = Global.GetTimestampMs(); using (Database.Database db = new Database.Database()) { List <Corner> loaded = db.Corners.ToList(); foreach (var entry in loaded) { CornerList.Add(entry.Id, entry); } Log.ConsoleLog("CORNERS", $"Załadowano cornery ({CornerList.Count}) | {Global.GetTimestampMs() - startTime}ms"); } }
public void DirectDatabaseInitializationConstructorWithCollectionOfNumbersWorksCorrectly(params int[] numbers) { // Arrange this.database = new Database.Database(numbers); // Act this.database.Add(int.MaxValue); this.database.Remove(); var databaseContent = this.database.Fetch(); // Assert for (int i = 0; i < numbers.Length; i++) { Assert.AreEqual(databaseContent[i], numbers[i]); } }
public void FetchShouldReturnAllValidElements() { // Arange int[] expected = new int[] { 1, 2 }; var database = new Database.Database(1, 2, 3); // Act database.Add(4); database.Add(5); database.Remove(); database.Remove(); database.Remove(); int[] fetched = database.Fetch(); // Assert Assert.AreEqual(expected, fetched); }
public static void BanPlayer(Character charData, Character adminData, int lengthInDays, string reason) { if (charData == null) { return; } reason = Command.UpperFirst(reason); Penalty penaltyData = new Penalty { AdminId = adminData?.MemberId ?? 0, TargetId = charData.Id, TargetGlobalId = charData.MemberId, Type = PenaltyType.Ban, Reason = reason, Timestamp = Global.GetTimestamp(), Expired = (int)((DateTimeOffset)DateTime.Now.AddDays(lengthInDays)).ToUnixTimeSeconds() }; Ban newBan = new Ban { Ip = charData.PlayerHandle.Address, SocialClubName = charData.PlayerHandle.SocialClubName, MemberId = charData.MemberId, Reason = reason, Expire = (int)((DateTimeOffset)DateTime.Now.AddDays(lengthInDays)).ToUnixTimeSeconds(), Canceled = false, Serial = charData.PlayerHandle.Serial, AdminId = adminData?.MemberId ?? 0 }; using (Database.Database db = new Database.Database()) { db.Penalties.Add(penaltyData); db.Bans.Add(newBan); db.SaveChanges(); } Player.SendFormattedChatMessage(charData.PlayerHandle, "Zostałeś zbanowany.", Constants.ColorDarkRed); Player.SendFormattedChatMessage(charData.PlayerHandle, $"Powód: {reason}", Constants.ColorDarkRed); ShowMessage(charData, adminData, PenaltyType.Ban, reason); charData.PlayerHandle.Kick("Zostałeś zbanowany."); }
public bool Update(Class.Personal personal) { try { database = new Database.Database(); string query = string.Format("UPDATE Personal SET PersonalName='{0}',PersonalSurname='{1}',PersonalNationalNumber='{2}',PersonalNumber='{3}',PersonalAddress='{4}',PersonalEmail='{5}',PersonalTitle='{6}',PersonalNickName='{7}',PersonalPassword='******'WHERE Personalid='{9}'", personal.PersonalName, personal.PersonalSurname, personal.PersonalNationalNumber, personal.PersonalNumber, personal.PersonalAddress, personal.PersonalEmail, personal.PersonalTitle, personal.PersonalNickName, personal.PersonalPassword, personal.PersonalId); database.ExecuteQueries(query); } catch (Exception ex) { MessageBox.Show(ex.Message); return(false); } return(true); }
public async void OnDelete(object sender, EventArgs e) { //Get the selected item to be delted from our ListView var selectedItem = (MedicineListItem)((MenuItem)sender).CommandParameter; var alertResult = await DisplayAlert("Delete Medicine Item", "Proceed and delete medicine item?", "OK", "Cancel"); if (alertResult == true) { var itemDeleted = new Database.Database().DeleteItem(selectedItem.Id); _viewModel.MedicineList.Remove(selectedItem); } else { return; } }
public bool Insert(Customer customer) { try { database = new Database.Database(); string query = string.Format("INSERT INTO Customer (CustomerName, CustomerSurname, CustomerNumber, CustomerAddress, CustomerEmail) VALUES ('{0}','{1}','{2}','{3}','{4}')", customer.name, customer.Surname, customer.Number, customer.address, customer.email); database.ExecuteQueries(query); } catch (Exception ex) { MessageBox.Show(ex.Message); return(false); } return(true); }
public bool Update(Customer customer) { try { database = new Database.Database(); string query = string.Format("UPDATE Customer SET CustomerName='{0}',CustomerSurname='{1}',customerNumber='{2}',customerAddress='{3}',customerEmail='{4}'WHERE customerid='{5}'", customer.name, customer.Surname, customer.Number, customer.address, customer.email, customer.id); database.ExecuteQueries(query); } catch (Exception ex) { MessageBox.Show(ex.Message); return(false); } return(true); }
/* * Method name: SaveNew Event * Purpose: To save a new picture event */ public bool SaveNewEvent(bool ticked) { Database.Database db = new Database.Database(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "ShareMyDay.db3"); StoryEvent storyEvent = new StoryEvent { Value = DateTime.Now.ToLongTimeString() + "-" + "Picture Taken", DateTime = DateTime.Now, Finished = ticked }; var picture = new Picture { EventId = storyEvent.Id, Path = GetImageUrl() }; return(db.InsertEvent(true, storyEvent, null, picture, null) != 0); }
/* * Method name: OnCreate * Purpose: To set up the story page depending whether the user has selected the favourite or todays story button */ protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.StoryView); _storyId = Intent.GetStringExtra("Story"); _storyIndex = Intent.GetStringExtra("StoryIndex"); ImageView pictureButton = FindViewById <ImageView>(Resource.Id.pictureBox); _db = new Database.Database(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "ShareMyDay.db3"); var options = new BitmapFactory.Options { InJustDecodeBounds = true }; var sample = 4; options.InSampleSize = sample; options.InJustDecodeBounds = false; Database.Models.Story story; if (_storyId == "Favourite") { story = _db.FindFavouriteStory(); if (story != null) { SetupStory(story, options, pictureButton, _db, true); } else { Intent noFavouriteStories = new Intent(this, typeof(NoStoriesActivity)); noFavouriteStories.PutExtra("StoryType", "Favourite"); StartActivity(noFavouriteStories); } } else { story = _db.FindStoryById(_storyId); SetupStory(story, options, pictureButton, _db, false); } }
public static void DestroyShop(Shop shop) { if (NAPI.Entity.DoesEntityExist(shop.ShopMarker)) { shop.ShopMarker.Delete(); } using (Database.Database db = new Database.Database()) { db.Shops.Remove(shop); db.SaveChanges(); } if (ShopsList.ContainsKey(shop.Id)) { ShopsList.Remove(shop.Id); } shop = null; }
public DataTable Search(string UserName) { database = new Database.Database(); string query = "SELECT * FROM User "; string options = string.Empty; if (!string.IsNullOrEmpty(UserName)) { options = "WHERE UserName= '******'"; } query = query + options; var user = database.ShowDataInGridView(query); return(user); }
public virtual bool Insert(Saler saler) { try { database = new Database.Database(); string query = string.Format("INSERT INTO Saler (FirmName,FirmTitle,TaxNumber,TaxOffice,Address,WorkPhone,CellPhone,FaxNumber,Email) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", saler.FirmName, saler.FirmTitle, saler.TaxNumber, saler.TaxOffice, saler.Address, saler.WorkPhone, saler.CellPhone, saler.FaxNumber, saler.Email); database.ExecuteQueries(query); } catch (Exception ex) { return(false); } return(true); }
public bool Update(Saler saler) { try { database = new Database.Database(); string query = string.Format("UPDATE Saler SET FirmName='{0}',FirmTitle='{1}',TaxNumber='{2}',TaxOffice='{3}',Address='{4}',WorkPhone='{5}',CellPhone='{6}',FaxNumber='{7}',Email='{8}' WHERE SalerId='{9}'", saler.FirmName, saler.FirmTitle, saler.TaxNumber, saler.TaxOffice, saler.Address, saler.WorkPhone, saler.CellPhone, saler.FaxNumber, saler.Email, saler.SalerId); database.ExecuteQueries(query); } catch (Exception ex) { return(false); } return(true); }
public bool Update(Storage storage) { try { database = new Database.Database(); string query = string.Format("UPDATE Storage SET StorageType='{0}',StorageTaxNumber='{1}''StorageSize{2}',StorageAdress='{3}',StoragePhoneNumber='{4}',StorageFaxNumber='{5}' WHERE StorageID ='{6}'", storage.StorageType, storage.StorageTaxNumber, storage.StorageSize, storage.StorageAddress, storage.StoragePhoneNumber, storage.StorageFaxNumber, storage.StorageId); database.ExecuteQueries(query); } catch (Exception ex) { return(false); } return(true); }
public bool Update(Store store) { try { database = new Database.Database(); string query = string.Format("UPDATE Store SET StoreName='{0}',StoreAdress='{1}',StoreOpenHour='{2}',StoreCloseHour='{3}',StoreStorage='{4}' WHERE StoreID='{5}'" , store.storeName, store.StoreAdress, store.StoreOpenHour, store.StoreCloseHour, store.StoreStorage, store.StoreID); database.ExecuteQueries(query); } catch (Exception ex) { return(false); } return(true); }
public bool Insert(Store store) { try { database = new Database.Database(); string query = string.Format("INSERT INTO Store (StoreName,StoreAdress,StoreOpenHour,StoreCloseHour,StoreStorage) VALUES ('{0}','{1}','{2}','{3}','{4}')" , store.StoreName, store.StoreAdress, store.StoreOpenHour, store.StoreCloseHour, store.StoreStorage); database.ExecuteQueries(query); } catch (Exception ex) { return(false); } return(true); }
public static void ReadFromJson(ref Database.Database db) { //Database.Database db = null; List <Worker> workers = null; List <Employer> employers = null; var serializer = new JsonSerializer(); try { using (var sr = new StreamReader(@"Data\Workers.json", Encoding.UTF8)) { using (var jr = new JsonTextReader(sr)) { workers = serializer.Deserialize <List <Worker> >(jr); } } } catch (Exception e) { Console.WriteLine(e.Message); ConsoleScreen.Clear(); } workers?.ForEach(db.Users.Add); try { using (var sr = new StreamReader(@"Data\Employers.json", Encoding.UTF8)) { using (var jr = new JsonTextReader(sr)) { employers = serializer.Deserialize <List <Employer> >(jr); } } } catch (Exception e) { Console.WriteLine(e.Message); ConsoleScreen.Clear(); } employers?.ForEach(db.Users.Add); }
public static void WriteToJson(Database.Database db) { var serializer = new JsonSerializer(); try { var workers = db.GetWorkers(); using (var fs = new FileStream(@"Data\Workers.json", FileMode.Create)) { using (var sw = new StreamWriter(fs, Encoding.UTF8)) { using (var jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; serializer.Serialize(jw, workers); } } } } catch (Exception) { } try { var employers = db.GetEmployers(); using (var fs = new FileStream(@"Data\Employers.json", FileMode.Create)) { using (var sw = new StreamWriter(fs, Encoding.UTF8)) { using (var jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; serializer.Serialize(jw, employers); } } } } catch (Exception) { } }
/// <summary> /// Laduje drzwi interiorów z bazy danych do pamięci. /// </summary> public static void LoadInteriorsDoors() { double startTime = Global.GetTimestampMs(); using (Database.Database db = new Database.Database()) { List <InteriorDoor> doors = db.InteriorDoors.ToList(); foreach (InteriorDoor entry in doors) { Interior interiorData = GetInteriorData(entry.ParentId); if (interiorData == null) { db.InteriorDoors.Remove(entry); continue; } entry.MarkerOut = NAPI.Marker.CreateMarker(20, new Vector3(entry.OutX, entry.OutY, entry.OutZ + 1), new Vector3(), new Vector3(), 0.5f, new Color(255, 255, 255, 255), true, (uint)entry.OutDim); entry.MarkerOut.Transparency = 255; if ((int)Math.Floor(entry.InX) != 0) { entry.MarkerIn = NAPI.Marker.CreateMarker(20, new Vector3(entry.InX, entry.InY, entry.InZ + 1), new Vector3(), new Vector3(), 0.5f, new Color(255, 255, 255, 255), true, (uint)entry.InDim); entry.MarkerIn.Transparency = 255; } if (entry.Blip > 0) { entry.BlipHandle = NAPI.Blip.CreateBlip(entry.Blip, new Vector3(entry.OutX, entry.OutY, entry.OutZ), 1.0f, 3, entry.Name, 255, 999999.0f, true, 0, (uint)entry.OutDim); } InteriorDoorsList.Add(entry.Id, entry); } Log.ConsoleLog("INTERIORS-DOORS", $"Załadowano drzwi interiorów ({InteriorDoorsList.Count}) | " + $"{Global.GetTimestampMs() - startTime}ms"); } }
private void UpdateDataContexts() { try { Database.Database db = new Database.Database(); string search = OrderSearchTextBox.Text; this.OrdersListing.DataContext = (search.Length > 0 ? from order in db.Orders // TODO where order.Comments.Contains(search) select order : db.Orders); } catch (Exception e) { MessageBox.Show(e.Message); } }
public async void OnDelete(object sender, EventArgs e) { // Get the selected item to be deleted from our ListView var selectedItem = (SmoothieListItem)((MenuItem)sender).CommandParameter; // Prompt the user with a confirmation dialog to confirm var alertResult = await DisplayAlert("Delete Medicine Item", "Proceed and delete medicine item?", "OK", "Cancel"); if (alertResult == true) { // Remove item from our SQLite Database and MedicineList collection var itemDeleted = new Database.Database().DeleteItem(selectedItem.Id); _viewModel.SmoothieList.Remove(selectedItem); } else { return; } }
private void UpdateDataContexts() { try { Database.Database db = new Database.Database(); string search = ProductSearchTextBox.Text; this.ProductsListing.DataContext = (search.Length > 0 ? from product in db.Products where product.Name.Contains(search) select product : db.Products); } catch (Exception e) { MessageBox.Show(e.Message); } }
public static void BindDropDownList(DropDownList ddl, string displayField, string valueField, string query) { Database.Database myDatabase = new Database.Database("cesConnectionString"); myDatabase.CreateConnection(); myDatabase.InitializeSQLCommandObject(myDatabase.GetCurrentConnection, query); try { myDatabase.OpenConnection(); ddl.DataSource = myDatabase.obj_sqlcommand.ExecuteReader(); ddl.DataTextField = displayField; ddl.DataValueField = valueField; ddl.DataBind(); } finally { myDatabase.CloseConnection(); myDatabase.obj_sqlcommand.Dispose(); } }
public bool Save(User user) { try { database = new Database.Database(); string query = string.Format("UPDATE User SET UserName= '******',Password='******',Name='{2}',Surname='{3}',Email='{4}',PhoneNumber='{5}',Salary='{6}',FirstLogin='******',SecurityQuestion='{8}',SecurityAnswer = '{9}' WHERE UserId={10}", user.UserName, user.Password, user.Name, user.Surname, user.Email, user.PhoneNumber, user.Salary, user.Firstlogin, user.SecurityQuestion, user.SecurityAnswer, user.UserID); database.ExecuteQueries(query); } catch (Exception ex) { return(false); } return(true); }
private void loadAuthors(bool silent) { editAuthor.Items.Clear(); Database.Database db = Provider.GetDb(Index); if (db == null) { if (!silent) { MessageBox.Show((Index + 1) + ". kutu için veritabanı ayarları geçersiz.", "Çınar CMS Desktop Editor"); } return; } foreach (DataRow dr in db.GetDataTable("select Id, Name as Title from Author").Rows) { editAuthor.Items.Add(new Item(dr)); } }
private void loadCategories(bool silent) { editCategoryId.Items.Clear(); Database.Database db = Provider.GetDb(Index); if (db == null) { if (!silent) { MessageBox.Show((Index + 1) + ". kutu için veritabanı ayarları geçersiz.", "Çınar CMS Desktop Editor"); } return; } foreach (DataRow dr in db.GetDataTable("select Id, Title from Content where ClassName='Category' order by Title").Rows) { editCategoryId.Items.Add(new Item(dr)); } }
/// <summary> /// Set up of db file and checking workspace files. /// </summary> public async Task SetUp() { string dbFile; do { // ask for database filename and see if it's valid Console.Write("Enter the name of the exported database file " + "(it must be placed on the same place as this .exe file, " + "leave as empty if the exported db filename is Backup_pages.db): "); dbFile = Console.ReadLine(); DbFile = string.IsNullOrWhiteSpace(dbFile) ? DbFile : dbFile; // check if database schema contains the images table and expected columns // see DbLayout.cs for how it layouts a database schema // see Database.cs line 39 for expected column names and data-types Console.Write($"Checking if {DbFile} is a valid database... "); if (!await new Database.Database(DbFile).IsDatabaseValid()) { continue; } } while (!File.Exists(DbFile) || !DbFile.EndsWith(".db")); Console.WriteLine("Ok."); var database = new Database.Database(DbFile); // setup workspace files. Adds an 'images' folder, and a 'log.txt' text file // Grabs all images from the db for preparation with other methods Console.Write("Checking workspace files... "); Directory.CreateDirectory("images"); using (var sw = File.AppendText("log.txt")) { await sw.WriteLineAsync($"Log started at: {DateTime.Now.ToString()}" + sw.NewLine + "----------------------------------------------------------------------" + sw.NewLine); } DbImages = await database.GetDbImagesFromDb(); Console.WriteLine($"Workspace files has been created. You have {DbImages.Count} images.\n"); }
/* * Method name: CheckCard * Purpose: This is used to check if the card is a Share My Day card and if so to get the type of the card */ public void CheckCard(Intent intent, Context context, Activity activity, Database.Database db) { List <string> cardInformation = GetData(intent); if (cardInformation[0].Equals("ShareMyDayTest")) { if (cardInformation[1] == "8") { QuickMenuComponent quickMenu = new QuickMenuComponent(activity, context); quickMenu.Show(); } else { StoryEvent storyEvent = new StoryEvent { Value = DateTime.Now.ToLongTimeString() + "-Card-" + cardInformation[2], DateTime = DateTime.Now }; var card = new Card { StoryEventId = storyEvent.Id, Type = cardInformation[1], Message = cardInformation[2] }; bool successful = db.InsertEvent(true, storyEvent, card, null, null) != 0; if (successful) { string message = cardInformation[2] + " has been recorded"; Toast.MakeText(context, message, ToastLength.Short).Show(); } } } else { AlertBoxComponent invalidNfcAlertBox = new AlertBoxComponent(context); invalidNfcAlertBox.Setup("Invalid Card", "The scanned card is not compatible with Share My Day. Please try a different card."); invalidNfcAlertBox.Show(); } }
static void Main(string[] args) { const int SW_SHOWMINIMIZED = 2; var handle = GetConsoleWindow(); ShowWindow(handle, SW_SHOWMINIMIZED); // Hide or not the screen Database.Database db = new Database.Database(); db.initTables(); Database.Model.Settings _settings_ = db.settingsManager.get(db.connectionString, 1); int SW_HIDE_SHOW = _settings_.showWindow; // SW_HIDE = 0 // SW_SHOW = 5 if (SW_HIDE_SHOW == 5) { // Show ShowWindow(handle, 9); ShowWindow(handle, SW_HIDE_SHOW); int Height = Console.LargestWindowHeight - 20; int Width = Console.LargestWindowWidth - 20; Console.SetWindowSize(Width, Height); Console.SetWindowPosition(0, 0); } else if (SW_HIDE_SHOW == 0) { // Hide Console.SetWindowSize(1, 1); Console.SetWindowPosition(0, 0); ShowWindow(handle, SW_HIDE_SHOW); } // Some biolerplate to react to close window event, CTRL-C, kill, etc _handler += new EventHandler(Handler); SetConsoleCtrlHandler(_handler, true); //start your multi threaded program here Program p = new Program(); p.Start(); }
protected void Page_Load(object sender, EventArgs e) { //Categorie categorie = db.SelectCategorie(1); //tbxNaam.Text = categorie.CategorieNaam; //LoadAlleCategorien(); FillBezorgtijd(); if (!Page.IsPostBack) { db = new Database.Database(); LoadAlleCategorien(); } else { db = new Database.Database(); } }
private async void AddClientButton_OnClick(object sender, RoutedEventArgs e) { var client = new Client(); var dialog = new ClientDialog { DataContext = client }; var result = await DialogHost.Show(dialog, "RootDialog"); if ((bool)result && client.FirstName.Length > 0) { client.LastModification = DateTime.Now; Database.Database db = new Database.Database(); db.Clients.InsertOnSubmit(client); db.SubmitChanges(); UpdateDataContexts(); } }
private async void AddProductButton_OnClick(object sender, RoutedEventArgs e) { var product = new Product(); var dialog = new ProductDialog { DataContext = product }; var result = await DialogHost.Show(dialog, "RootDialog"); if ((bool)result && product.Name.Length > 0) { product.LastModification = DateTime.Now; Database.Database db = new Database.Database(); db.Products.InsertOnSubmit(product); db.SubmitChanges(); UpdateDataContexts(); } }
private async void AddOrderButton_OnClick(object sender, RoutedEventArgs e) { var order = new Order { Color = 0xFFFFFF, Status = OrderStatus.Ready, IsOnSiteWithdraw = true, WithdrawDate = DateTime.Now }; var dialog = new OrderDialog { DataContext = order }; var result = await DialogHost.Show(dialog, "RootDialog"); if ((bool)result) { order.LastModification = DateTime.Now; order.WithdrawDate = dialog.GetDateTime(); Database.Database db = new Database.Database(); try { // TODO null exception foreach (var oe in dialog.ListOrderElements) { db.OrdersElements.InsertOnSubmit(oe); } db.Orders.InsertOnSubmit(order); db.SubmitChanges(); } catch (Exception exception) { Debug.WriteLine(exception); } UpdateDataContexts(); } }
private void UpdateDataContexts() { try { Database.Database db = new Database.Database(); string search = ClientSearchTextBox.Text; this.ClientsListing.DataContext = (search.Length > 0 ? from client in db.Clients where client.Name.Contains(search) || client.FullAddress.Contains(search) || client.Phone.Contains(search) || client.Email.Contains(search) select client : db.Clients); } catch (Exception e) { MessageBox.Show(e.Message); } }
public static void Run() { string arabicStart = @"<font size=""5"" face=""Arabic Typesetting"">"; string turkishStart = @"<font face=""Verdana"" size=""2"">"; Database.Database db = new Database.Database(DatabaseProvider.MySQL, "localhost", "quran", "root", "bk", 30); DataTable dt = db.GetDataTable("select sura, aya from quran_text order by 1,2"); foreach (DataRow dr in dt.Rows) { string url = string.Format("http://www.kuranmeali.com/mobil/m-kelime.asp?sure={0}&ayet={1}", dr["sura"], dr["aya"]); Encoding enc = Encoding.UTF8; string res = url.DownloadPage(ref enc); int index = 0, end = -1, orderNo = 0; while (true) { index = res.IndexOf(arabicStart, index); if (index == -1) break; end = res.IndexOf("</font>", index); var arabic = HttpUtility.HtmlDecode(res.Substring(index + arabicStart.Length, end - index - arabicStart.Length).Replace(" : ","")); index = res.IndexOf(turkishStart, end); end = res.IndexOf("</font>", index); var turkish = HttpUtility.HtmlDecode(res.Substring(index + turkishStart.Length, end - index - turkishStart.Length).Replace("\\","'")); turkish = turkish.Replace("ý", "ı").Replace("ð", "ğ").Replace("þ", "ş").Replace("Ý", "I").Replace("Ð", "Ğ").Replace("Þ", "Ş"); db.ExecuteNonQuery("insert into quran_kelime_meal(sura, aya, orderno, arabic, turkish) values({0}, {1}, {2}, {3}, {4})", dr["sura"], dr["aya"], orderNo, arabic, turkish); orderNo++; } Console.WriteLine("{0}, {1}", dr["sura"], dr["aya"]); } }
public MyWorkerProcess() { db = this.GetNewDatabaseInstance(); }
public Administratie() { db = new Database.Database(); }
public void RefreshDatabaseSchema() { Database = new Database.Database(Provider, Host, DbName, UserName, Password, TIMEOUT, null, CreateDatabaseIfNotExist); Cinar.DBTools.Provider.ConnectionsModified = true; }
public override void Initialize() { if (null == this.ExpressionsManager) throw new MissingProviderException("ExpressionsManager"); if (null == this.Agent) throw new MissingProviderException("Agent"); if (null == this.RoutingManager) throw new MissingProviderException("RoutingManager"); string views_config = this.RoutingManager.SettingsRoutes["VIEWS_CONFIG"].Path; if (this.RuntimeAware && null != this.RoutingManager.RuntimeSettingsRoutes["VIEWS_CONFIG"]) views_config = this.RoutingManager.RuntimeSettingsRoutes["VIEWS_CONFIG"].Path; string connections_config = this.RoutingManager.SettingsRoutes["CONNECTIONS_FILE"].Path; if (this.RuntimeAware && null != this.RoutingManager.RuntimeSettingsRoutes["CONNECTIONS_FILE"]) connections_config = this.RoutingManager.RuntimeSettingsRoutes["CONNECTIONS_FILE"].Path; if (String.IsNullOrEmpty(connections_config)) throw new ApplicationException("CONNECTIONS_FILE not found or not set"); Cache cache = HttpRuntime.Cache; lock (SyncRoot) { this.Databases = new Dictionary<string, LWAS.Database.Database>(); if (this.Agent.HasKey(connections_config)) { XDocument dbs = cache["XDocument: " + connections_config] as XDocument; if (null == dbs) { dbs = XDocument.Parse(this.Agent.Read(connections_config)); cache.Insert("XDocument: " + connections_config, dbs, new CacheDependency(connections_config)); } foreach (XElement element in dbs.Element("connections").Elements("connection")) { string key = element.Attribute("key").Value; if (null != element.Attribute("views")) views_config = element.Attribute("views").Value; if (!String.IsNullOrEmpty(views_config)) { LWAS.Database.Database database = cache[views_config] as LWAS.Database.Database; if (null == database) { database = new Database.Database(key, views_config, this.Agent, this.ExpressionsManager); // do not cache reference to current page! database.ViewsManager.ExpressionsManager.Page = null; cache.Insert(views_config, database, new CacheDependency(views_config)); } if (!this.Databases.ContainsKey(database.Name)) this.Databases.Add(database.Name, database); // assign proper reference to current page database.ViewsManager.ExpressionsManager.Page = this.Page; } } } else { LWAS.Database.Database database = new Database.Database(views_config, views_config, this.Agent, this.ExpressionsManager); this.Databases.Add(database.Name, database); } } // this is buggy this.CurrentDatabase = this.Databases.First().Value; base.Initialize(); }
private async void ClientEditBtn_OnClick(object sender, RoutedEventArgs e) { var client = ((FrameworkElement)sender).DataContext as Client; if (client == null) return; Database.Database db = new Database.Database(); client = (from c in db.Clients where c.Id == client.Id select c).Single(); var dialog = new ClientDialog { DataContext = client }; var result = await DialogHost.Show(dialog, "RootDialog"); if ((bool)result && client.FirstName.Length > 0) { client.LastModification = DateTime.Now; db.SubmitChanges(); } // TODO delete UpdateDataContexts(); }
public static void Run() { // Eğer bu veritabanı serverda yoksa, otomatik create edilir. Database.Database db = new Database.Database("Server=172.16.5.41;Initial Catalog=ServiceAPI;User Id=usr_service_api;Password=srv2013;", DatabaseProvider.SQLServer); //WFAracTalep aracTalep = new WFAracTalep { // Adres = "adres", // Saat = "saat", // State = WFS_AracTalep.New //}; //aracTalep.Save(); /* Table table = db.CreateTableMetadataForType(typeof(Ogrenci)); Console.WriteLine(db.GetTableDDL(table)); */ Ogrenci ogr = new Ogrenci(); ogr.Ad = "Mehmet"; ogr.TcKimlikNo = "987632454"; ogr.Para = 120.55m; db.Save(ogr); Ogrenci ogr2 = db.Read<Ogrenci>(ogr.Id); /* Veli v = new Veli(); v.Ad = "Bülent"; v.TcKimlikNo = "756867"; db.Save(v); List<Ogrenci> list = db.ReadList<Ogrenci>("select *, '2. Dönem' as Donem, 2012 as Yil from student"); */ }
/// <summary> /// Constructor. /// </summary> public SyncFolderSyncronizer(Config.SyncConfig.SyncFolder SyncFolderInfo) : base(SyncFolderInfo) { // Database is the user's AppData/Roaming database = new Database.Database(SyncFolderInfo); foreach (Config.IgnoredFolder ignoredFolder in SyncFolderInfo.IgnoredFolders) { Logger.Info("The folder \"" + ignoredFolder + "\" will be ignored"); } }
public void Welcome() { DialogResult dr; Database.Database db = new Database.Database(); if (!GlobalHelper.appSettings.IsAppConfigExists()) { dr = MessageBox.Show( "Looks like it's your first time to use Multi Remote Desktop Client .Net!\r\n\r\nThe application created a default password for you called \"pass\".\r\nDo you like to update your password now?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question ); if (dr == DialogResult.Yes) { // call our toolbar_Configuration event method. this.toolbar_Configuration_Click(this.toolbar_Configuration, null); } // create our new database schema and default datas db.ResetDatabase(); } db.Delete(false); db = null; }
private async void OrderEditBtn_OnClick(object sender, RoutedEventArgs e) { var order = ((FrameworkElement)sender).DataContext as Order; if (order == null) return; Database.Database db = new Database.Database(); order = (from c in db.Orders where c.Id == order.Id select c).Single(); // TODO try/catch var dialog = new OrderDialog { DataContext = order }; var result = await DialogHost.Show(dialog, "RootDialog"); if ((bool)result) { order.LastModification = DateTime.Now; db.SubmitChanges(); } // TODO delete UpdateDataContexts(); }
private async void ProductEditBtn_OnClick(object sender, RoutedEventArgs e) { var product = ((FrameworkElement)sender).DataContext as Product; if (product == null) return; Database.Database db = new Database.Database(); product = (from p in db.Products where p.Id == product.Id select p).Single(); var dialog = new ProductDialog { DataContext = product }; var result = await DialogHost.Show(dialog, "RootDialog"); if ((bool) result && product.Name.Length > 0) { product.LastModification = DateTime.Now; db.SubmitChanges(); } // TODO delete UpdateDataContexts(); }
public static void Init() { ConcurrentDictionary<uint, ushort[]> dimensions = new ConcurrentDictionary<uint, ushort[]>(); string[] dimensionData = System.IO.File.ReadAllLines("C:/db/mapdimensions.dat"); foreach (string md in dimensionData) { string[] mdd = md.Split(' '); ushort Width = ushort.Parse(mdd[1]); ushort Height = ushort.Parse(mdd[2]); ushort[] dim = new ushort[2] { Width, Height }; dimensions.TryAdd(uint.Parse(mdd[0]), dim); } Database.Database DB = new Database.Database("C:/db/maps.s3db"); System.Data.DataTable DT = DB.GetDataTable("SELECT `UniqueID`, `Type` FROM `maptypes`"); for (int i = 0; i < DT.Rows.Count; i++) { System.Data.DataRow dr = DT.Rows[i]; Mapping.Map M = new Map(); M.UniqueID = Convert.ToUInt32(dr.ItemArray[0]); M.Type = Convert.ToUInt32(dr.ItemArray[1]); if (!M.LoadDMap()) { ushort[] dims; if (dimensions.TryGetValue(M.Type, out dims)) { M.Width = dims[0]; M.Height = dims[1]; } else { M.Width = 1300; M.Height = 1300; } M.Coords = new byte[M.Height, M.Width]; for (short ix = 0; ix < M.Height; ix++) for (short iy = 0; iy < M.Width; iy++) M.Coords[ix, iy] = (byte)Enums.MapPointType.Empty; } Kernel.Maps.TryAdd(M.UniqueID, M); } DB.Dispose(); dimensions.Clear(); }
/// <summary> /// Constructor for Repo (at every launch of CmisSync) /// </summary> public SynchronizedFolder(RepoInfo repoInfo, RepoBase repoCmis, IActivityListener activityListener) { this.activityListener = activityListener; if (null == repoInfo || null == repoCmis) { throw new ArgumentNullException("repoInfo"); } this.repo = repoCmis; this.repoinfo = repoInfo; suspended = this.repoinfo.IsSuspended; // Database is the user's AppData/Roaming database = new Database.Database(repoinfo.CmisDatabase); // Get path on remote repository. remoteFolderPath = repoInfo.RemotePath; if (Logger.IsInfoEnabled) { foreach (string ignoredFolder in repoInfo.getIgnoredPaths()) { Logger.Info("The folder \"" + ignoredFolder + "\" will be ignored"); } } syncWorker = new BackgroundWorker(); syncWorker.WorkerSupportsCancellation = true; syncWorker.DoWork += new DoWorkEventHandler( delegate(Object o, DoWorkEventArgs args) { bool syncFull = (bool)args.Argument; try { Sync(syncFull); } catch (OperationCanceledException e) { Logger.Info(e.Message); } catch (CmisPermissionDeniedException e) { repo.OnSyncError(new PermissionDeniedException("Authentication failed.", e)); } catch (CmisMissingSyncFolderException e) { repo.OnSyncError(new MissingSyncFolderException("Missing sync folder.", e)); } catch (Exception e) { repo.OnSyncError(new BaseException(e)); } finally { SyncComplete(syncFull); } } ); }