예제 #1
0
        public void OpenOrCreate(DatabaseDescriptor databaseDescriptor)
        {

            String databasePath = new DatabaseUtils().GetDatabasePath(databaseDescriptor);

            if (!FileUtils.DoesFolderExists(databasePath, FileUtils.LOCAL_FOLDER))
            {
                try
                {
                    FileUtils.CreateFolder(databasePath, FileUtils.LOCAL_FOLDER);
                }
                catch (System.Exception exception)
                {
                    Log.Log.Error(typeof(DatabaseImpl).FullName, "OpenOrCreate", "Exception caught while creating database directories, DATABASE-PATH: " + databasePath + ", DATABASE-DESCRIPTOR: " + databaseDescriptor.GetDatabaseName() + ", " + exception.Message);
                    throw new DeploymentException(typeof(DatabaseImpl).FullName, "OpenOrCreate", "Exception caught while creating database directories, DATABASE-PATH: " + databasePath + ", DATABASE-DESCRIPTOR: " + databaseDescriptor.GetDatabaseName() + ", " + exception.Message);
                }
            }

            String databaseName = databaseDescriptor.GetDatabaseName();
            if (databaseName == null || databaseName.Length <= 0)
            {
                Log.Log.Error(typeof(DatabaseImpl).FullName, "OpenOrCreate", "DATABASE-NAME IS MANDATORY FIELD - DATABASE-DESCRIPTOR: " + databaseDescriptor.GetDatabaseName());
                throw new DatabaseException(typeof(DatabaseImpl).FullName, "OpenOrCreate", "DATABASE-NAME IS MANDATORY FIELD - DATABASE-DESCRIPTOR: " + databaseDescriptor.GetDatabaseName());
            }

            if (!databaseName.EndsWith(".db"))
            {
                databaseName = databaseName + ".db";
            }

            try
            {

                #if XAMARIN
                    String databaseURI = Path.Combine (databasePath, databaseName);
                    sqliteDatabase = new SQLiteConnection(databaseURI);
                #elif WINDOWS
                    sqliteDatabase = new SQLiteConnection(databasePath + databaseName);
                #endif
            }
            catch (SQLiteException sqliteException)
            {
                Log.Log.Error(typeof(DatabaseImpl).FullName, "OpenOrCreate", "SQLiteException caught while opening database, " + sqliteException.Message);
                throw new DatabaseException(typeof(DatabaseImpl).FullName, "OpenOrCreate", "SQLiteException caught while opening database, " + sqliteException.Message);
            }
        }
예제 #2
0
 public bool TablesExist()
 {
     return
         (DatabaseUtils.DatabaseExists(PublicConnectionString, Timeouts.PublicDatabase) &&
          DatabaseUtils.TableExists(PublicConnectionString, Timeouts.PublicDatabase, "TIMETABLE_CONFIG", "MISC"));
 }
        /// <summary>
        /// Check the XML Package Given for Replace or Insert Apply
        /// </summary>
        /// <param name="xml">FileInfo for XML Package</param>
        /// <param name="replace">Enforce Replace Mode</param>
        /// <returns>True if success, False if any errors</returns>
        private bool CheckXMLPackageAndApply(FileInfo xml, bool replace)
        {
            var packageName = string.Format("{0}{1}{2}", xml.Directory.Name, Path.DirectorySeparatorChar, xml.Name);

            if (log.IsInfoEnabled)
            {
                log.InfoFormat("Auto Loading XML File {0} into Database (Mode:{1})", packageName, replace ? "Replace" : "Insert");
            }

            var result = true;

            try
            {
                // Load the XML File
                var xmlTable = LoaderUnloaderXML.LoadXMLTableFromFile(xml);
                if (xmlTable.Length > 0)
                {
                    // Guess Object Type
                    var xmlType      = xmlTable.First().GetType();
                    var tableHandler = new DataTableHandler(xmlType);

                    // Find unique Fields
                    var uniqueMember = DatabaseUtils.GetUniqueMembers(xmlType);

                    // Get all object "Method" Through Reflection
                    var classMethod     = GameServer.Database.GetType().GetMethod("SelectAllObjects", Type.EmptyTypes);
                    var genericMethod   = classMethod.MakeGenericMethod(xmlType);
                    var existingObjects = ((IEnumerable)genericMethod.Invoke(GameServer.Database, new object[] { })).Cast <DataObject>().ToArray();

                    // Store Object to Alter
                    var toDelete = new ConcurrentBag <DataObject>();
                    var toAdd    = new ConcurrentBag <DataObject>();

                    // Check if an Object already exists
                    xmlTable.AsParallel().ForAll(obj => {
                        // Check if Exists Compare Unique and Non-Generated Primary Keys
                        var exists = existingObjects
                                     .FirstOrDefault(entry => uniqueMember
                                                     .Any(constraint => constraint
                                                          .All(bind => bind.ValueType == typeof(string)
                                                                                  ? bind.GetValue(entry).ToString().Equals(bind.GetValue(obj).ToString(), StringComparison.OrdinalIgnoreCase)
                                                                                  : bind.GetValue(entry) == bind.GetValue(obj))));

                        if (exists != null)
                        {
                            if (replace)
                            {
                                // Delete First
                                toDelete.Add(exists);
                                toAdd.Add(obj);
                            }

                            // Silently ignore duplicate inserts only...
                        }
                        else
                        {
                            toAdd.Add(obj);
                        }
                    });

                    // Delete First
                    foreach (var obj in toDelete)
                    {
                        obj.AllowDelete = true;
                    }

                    GameServer.Database.DeleteObject(toDelete);

                    // Then Insert
                    var previousAllowAdd = toAdd.Select(obj => obj.AllowAdd).ToArray();
                    foreach (var obj in toAdd)
                    {
                        obj.AllowAdd = true;
                    }

                    GameServer.Database.AddObject(toAdd);

                    // Reset Allow Add Flag
                    var current = 0;
                    foreach (var obj in toAdd)
                    {
                        obj.AllowAdd = previousAllowAdd[current];
                        current++;
                    }
                }
                else
                {
                    if (log.IsWarnEnabled)
                    {
                        log.WarnFormat("XML Package {0} Found Empty, may be a parsing Error...", packageName);
                    }

                    result = false;
                }
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                {
                    log.ErrorFormat("Error While Loading XML Package {0} into Database (Mode:{1}) - {2}", packageName, replace ? "Replace" : "Insert", e);
                }

                result = false;
            }

            return(result);
        }
 protected override void PrepareCommand(IDbCommand cmd)
 {
     cmd.CommandText =
         $"select * from {DatabaseUtils.GetQualifiedTableName(FederationSchema.FederationSchemaName, _tableName)}";
 }
 private bool CanChangeTargetDatabase(RestoreDatabaseTaskDataObject restoreDataObject)
 {
     return(DatabaseUtils.IsSystemDatabaseConnection(restoreDataObject.Server.ConnectionContext.DatabaseName));
 }
예제 #6
0
        public string GetStlWhereString(int siteId, string group, string groupNot, string tags, bool isImageExists, bool isImage, bool isVideoExists, bool isVideo, bool isFileExists, bool isFile, bool isTopExists, bool isTop, bool isRecommendExists, bool isRecommend, bool isHotExists, bool isHot, bool isColorExists, bool isColor, string where)
        {
            var whereBuilder = new StringBuilder();

            whereBuilder.Append($" AND SiteId = {siteId} ");

            if (isImageExists)
            {
                whereBuilder.Append(isImage
                    ? $" AND {nameof(Content.ImageUrl)} <> '' "
                    : $" AND {nameof(Content.ImageUrl)} = '' ");
            }

            if (isVideoExists)
            {
                whereBuilder.Append(isVideo
                    ? $" AND {nameof(Content.VideoUrl)} <> '' "
                    : $" AND {nameof(Content.VideoUrl)} = '' ");
            }

            if (isFileExists)
            {
                whereBuilder.Append(isFile
                    ? $" AND {nameof(Content.FileUrl)} <> '' "
                    : $" AND {nameof(Content.FileUrl)} = '' ");
            }

            if (isTopExists)
            {
                whereBuilder.Append($" AND {nameof(Content.Top)} = {StringUtils.ToLower(isTop.ToString())} ");
            }

            if (isRecommendExists)
            {
                whereBuilder.Append($" AND {nameof(Content.Recommend)} = {StringUtils.ToLower(isRecommend.ToString())} ");
            }

            if (isHotExists)
            {
                whereBuilder.Append($" AND {nameof(Content.Hot)} = {StringUtils.ToLower(isHot.ToString())} ");
            }

            if (isColorExists)
            {
                whereBuilder.Append($" AND {nameof(Content.Color)} = {StringUtils.ToLower(isColor.ToString())} ");
            }

            var database = _settingsManager.Database;

            if (!string.IsNullOrEmpty(group))
            {
                group = group.Trim().Trim(',');
                var groups = ListUtils.GetStringList(group);
                if (groups.Count > 0)
                {
                    whereBuilder.Append(" AND (");
                    foreach (var theGroup in groups)
                    {
                        var trimGroup = theGroup.Trim();

                        whereBuilder.Append(
                            $" ({nameof(Content.GroupNames)} = '{Utilities.FilterSql(trimGroup)}' OR {DatabaseUtils.GetInStr(database, nameof(Content.GroupNames), trimGroup + ",")} OR {DatabaseUtils.GetInStr(database, nameof(Content.GroupNames), "," + trimGroup + ",")} OR {DatabaseUtils.GetInStr(database, nameof(Content.GroupNames), "," + trimGroup)}) OR ");
                    }
                    whereBuilder.Length -= 3;
                    whereBuilder.Append(") ");
                }
            }

            if (!string.IsNullOrEmpty(groupNot))
            {
                groupNot = groupNot.Trim().Trim(',');
                var groupNots = ListUtils.GetStringList(groupNot);
                if (groupNots.Count > 0)
                {
                    whereBuilder.Append(" AND (");
                    foreach (var theGroupNot in groupNots)
                    {
                        var trimGroup = theGroupNot.Trim();
                        //whereBuilder.Append(
                        //    $" ({ContentAttribute.GroupNameCollection} <> '{trimGroup}' AND CHARINDEX('{trimGroup},',{ContentAttribute.GroupNameCollection}) = 0 AND CHARINDEX(',{trimGroup},',{ContentAttribute.GroupNameCollection}) = 0 AND CHARINDEX(',{trimGroup}',{ContentAttribute.GroupNameCollection}) = 0) AND ");

                        whereBuilder.Append(
                            $" ({nameof(Content.GroupNames)} <> '{trimGroup}' AND {DatabaseUtils.GetNotInStr(database, nameof(Content.GroupNames), trimGroup + ",")} AND {DatabaseUtils.GetNotInStr(database, nameof(Content.GroupNames), "," + trimGroup + ",")} AND {DatabaseUtils.GetNotInStr(database, nameof(Content.GroupNames), "," + trimGroup)}) AND ");
                    }
                    whereBuilder.Length -= 4;
                    whereBuilder.Append(") ");
                }
            }

            if (!string.IsNullOrEmpty(tags))
            {
                tags = tags.Trim().Trim(',');
                var tagNames = ListUtils.GetStringList(tags);
                if (tagNames.Count > 0)
                {
                    whereBuilder.Append(" AND (");
                    foreach (var tagName in tagNames)
                    {
                        whereBuilder.Append(
                            $" ({nameof(Content.TagNames)} = '{Utilities.FilterSql(tagName)}' OR {DatabaseUtils.GetInStr(database, nameof(Content.TagNames), tagName + ",")} OR {DatabaseUtils.GetInStr(database, nameof(Content.TagNames), "," + tagName + ",")} OR {DatabaseUtils.GetInStr(database, nameof(Content.TagNames), "," + tagName)}) OR ");
                    }
                    whereBuilder.Length -= 3;
                    whereBuilder.Append(") ");
                }
            }

            if (!string.IsNullOrEmpty(where))
            {
                whereBuilder.Append($" AND ({where}) ");
            }

            return(whereBuilder.ToString());
        }
        public async Task Test01_LoadModSelectionListTest()
        {
            PackageSelectionList selectionList = null;

            Logging.Info("Creating a ModSelectionList Window");

            //create the window and run it on its own thread and dispatcher
            //this can avoid problems with the unit test dispatcher not running the window the way it should
            //it's still an STA thread so WPF can use it as a UI thread
            //https://www.c-sharpcorner.com/uploadfile/suchit_84/creating-wpf-windows-on-dedicated-threads/
            Thread thread = new Thread(() =>
            {
                selectionList = new PackageSelectionList(modpackSettings, commandLineSettings, databaseManager)
                {
                    ApplyColorSettings = false, //not cross-thread safe
                    ApplyScaling       = false,
                    ApplyToolTips      = true,
                    AutoInstallMode    = false,
                    LocalizeWindow     = true,
                    OriginalHeight     = 720.0,
                    OriginalWidth      = 1280.0,

                    //WotClientVersionFromMainWindow is for UI display only
                    WotClientVersionFromMainWindow = "TESTING",

                    //WoTDirectoryFromMainWindow is for UI display only
                    WoTDirectoryFromMainWindow = "TESTING",

                    //DatabaseVersionFromMainWindow is for UI display and when saving a selection
                    DatabaseVersionFromMainWindow = "TESTING"
                };

                selectionList.Closed     += (sender, e) => selectionList.Dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
                selectionList.WindowState = WindowState.Normal;
                selectionList.Show();

                //start the windows message pump
                Dispatcher.Run();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();

            //wait for selection list to finish loading
            while (selectionList == null)
            {
                await Task.Delay(100);
            }

            while (!selectionList.LoadingUI)
            {
                await Task.Delay(100);
            }

            while (selectionList.LoadingUI)
            {
                await Task.Delay(1000);
            }

            selectionList.OnSelectionListReturn += (sender, e) => args = e;

            Logging.Info("Selecting 100 components");
            selectionList.Dispatcher.Invoke(() =>
            {
                List <SelectablePackage> flatListRandomSelection = DatabaseUtils.GetFlatSelectablePackageList(selectionList.ParsedCategoryList);
                flatListRandomSelection = flatListRandomSelection.FindAll(package => package.Enabled);
                Random random           = new Random();
                for (int i = 0; i < 100; i++)
                {
                    int selectIndex           = random.Next(0, flatListRandomSelection.Count);
                    SelectablePackage package = flatListRandomSelection[selectIndex];
                    Logging.Info("Index {0} selects package {1}", selectIndex, package.PackageName);
                    package.Checked = true;
                }

                //click the continue button
                List <FrameworkElement> elements = UiUtils.GetAllWindowComponentsLogical(selectionList, false);
                FrameworkElement buttonElement   = elements.Find(element => element.Tag != null && element.Tag.Equals("ContinueButton"));
                Button clearSelectionsButton     = buttonElement as Button;
                clearSelectionsButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            });

            //run some base tests on the return args
            Assert.IsTrue(args.ContinueInstallation);
            Assert.IsTrue(args.GlobalDependencies.Count > 0);
            Assert.IsTrue(args.Dependencies.Count > 0);
            Assert.IsTrue(args.ParsedCategoryList.Count > 0);

            //below this message is copy-modify-paste from the MainWindow's install and OnBeginInstall methods. Some of this should be moved into some sort of re-usable implementation. TODO
            //setup for install
            string wotExeFilepath   = RegistryUtils.AutoFindWoTDirectoryFirst();
            string wotExeFolderpath = Path.GetDirectoryName(wotExeFilepath);

            //get version folders to install as
            string versionXml       = Path.Combine(wotExeFolderpath, ApplicationConstants.WoTVersionXml);
            string versionTemp      = XmlUtils.GetXmlStringFromXPath(versionXml, ApplicationConstants.WoTVersionXmlXpath);
            string WoTClientVersion = versionTemp.Split('#')[0].Trim().Substring(2).Trim();

            Logging.Info("Detected client version: {0}", WoTClientVersion);

            //build macro hash for install
            MacroUtils.BuildFilepathMacroList(WoTClientVersion, databaseManager.WoTOnlineFolderVersion, wotExeFolderpath);

            //perform dependency calculations
            List <DatabasePackage>   flatList              = DatabaseUtils.GetFlatList(null, null, selectionList.ParsedCategoryList);
            List <SelectablePackage> flatListSelect        = DatabaseUtils.GetFlatSelectablePackageList(selectionList.ParsedCategoryList);
            List <Dependency>        dependneciesToInstall = new List <Dependency>(DatabaseUtils.CalculateDependencies(selectionList.Dependencies, selectionList.ParsedCategoryList, false, false));

            //create install list
            List <DatabasePackage> packagesToInstall = new List <DatabasePackage>();

            packagesToInstall.AddRange(selectionList.GlobalDependencies.FindAll(globalDep => globalDep.Enabled && !string.IsNullOrWhiteSpace(globalDep.ZipFile)));
            packagesToInstall.AddRange(dependneciesToInstall.FindAll(dep => dep.Enabled && !string.IsNullOrWhiteSpace(dep.ZipFile)));
            List <SelectablePackage> selectablePackagesToInstall = flatListSelect.FindAll(fl => fl.Enabled && fl.Checked && !string.IsNullOrWhiteSpace(fl.ZipFile));

            packagesToInstall.AddRange(selectablePackagesToInstall);
            List <SelectablePackage> userModsToInstall = args.UserMods.FindAll(mod => mod.Checked);

            //while we're at it let's make a list of packages that need to be downloaded
            List <DatabasePackage> packagesToDownload = packagesToInstall.FindAll(pack => pack.DownloadFlag);

            //and check if we need to actually install anything
            if (selectablePackagesToInstall.Count == 0 && userModsToInstall.Count == 0)
            {
                Assert.Fail("No packages to install");
            }

            //perform list install order calculations
            List <DatabasePackage>[] orderedPackagesToInstall = DatabaseUtils.CreateOrderedInstallList(packagesToInstall);

            //first, if we have downloads to do, then start processing them
            CancellationToken nullToken;

            if (packagesToDownload.Count > 0)
            {
                DownloadManager downloadManager = new DownloadManager()
                {
                    CancellationToken    = nullToken,
                    RetryCount           = 3,
                    DownloadLocationBase = ApplicationConstants.RelhaxDownloadsFolderPath,
                    UrlBase = ApplicationConstants.DownloadMirrors[selectionList.ModpackSettings.DownloadMirror].Replace("{onlineFolder}", databaseManager.WoTOnlineFolderVersion)
                };

                Logging.Info("Download while install = false and packages to download, processing downloads with await");
                Progress <RelhaxDownloadProgress> downloadProgress = new Progress <RelhaxDownloadProgress>();
                downloadManager.Progress = downloadProgress;
                await downloadManager.DownloadPackagesAsync(packagesToDownload);

                downloadManager.Dispose();
            }
            else
            {
                Logging.Info("No packages to download, continue");
            }

            InstallEngine installEngine = new InstallEngine(selectionList.ModpackSettings, selectionList.CommandLineSettings)
            {
                FlatListSelectablePackages = flatListSelect,
                OrderedPackagesToInstall   = orderedPackagesToInstall,
                PackagesToInstall          = packagesToInstall,
                ParsedCategoryList         = args.ParsedCategoryList,
                Dependencies              = args.Dependencies,
                GlobalDependencies        = args.GlobalDependencies,
                UserPackagesToInstall     = userModsToInstall,
                CancellationToken         = nullToken,
                DownloadingPackages       = (packagesToDownload.Count > 0),
                DisableTriggersForInstall = true,
                DatabaseVersion           = "TESTING",
                WoTDirectory              = wotExeFolderpath,
                WoTClientVersion          = WoTClientVersion
            };

            Progress <RelhaxInstallerProgress> progress = new Progress <RelhaxInstallerProgress>();
            RelhaxInstallFinishedEventArgs     results  = await installEngine.RunInstallationAsync(progress);

            Logging.Debug("Installation has finished");
            Assert.IsTrue(results.ExitCode == InstallerExitCodes.Success);
            installEngine.Dispose();
            installEngine = null;
        }
예제 #8
0
 public MyTable(string tableName)
 {
     this.TableName = tableName;
     this.Fields    = DatabaseUtils.GetListField(tableName);
 }
예제 #9
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     DatabaseUtils.init();
 }
예제 #10
0
 public IReadOnlyList <DatabaseColumnDefinition> GetSchemaForTable(string tableName)
 {
     return(DatabaseUtils.GetSchemaForTable(_connectionString, tableName, _timeoutSecs));
 }
예제 #11
0
 public IReadOnlyList <string> GetTables()
 {
     return(DatabaseUtils.GetTablesInSchema(_connectionString, _timeoutSecs));
 }
예제 #12
0
 public bool DatabaseExists()
 {
     return(DatabaseUtils.DatabaseExists(_connectionString, _timeoutSecs));
 }
예제 #13
0
 public SourceTimetable(string connectionString, int timeoutSecs)
 {
     _connectionString      = connectionString;
     _connectionDescription = DatabaseUtils.GetConnectionDescription(connectionString);
     _timeoutSecs           = timeoutSecs;
 }
        private string GetDatabaseConfigQuery()
        {
            string disco     = DatabaseUtils.Table <Disco>();
            string venda     = DatabaseUtils.Table <Venda>();
            string itemVenda = DatabaseUtils.Table <ItemVenda>();

            #region Cria banco de dados

            string queryCreateDatabase = $@"
                CREATE TABLE {disco} (
                    `id` integer NOT NULL,
                    `nome` integer NOT NULL,
                    `genero` varchar(255) NOT NULL,
                    `preco` double NOT NULL,
                    PRIMARY KEY (`id`)
                );

                CREATE TABLE {venda} (
                    `id` integer NOT NULL,
                    `data` date NOT NULL,
                    PRIMARY KEY (`id`)
                );

                CREATE TABLE {itemVenda} (
                    `id` integer NOT NULL,
                    `discoId` integer NOT NULL,
                    `vendaId` integer NOT NULL,
                    `valor` double NOT NULL,
                    `cashback` double NOT NULL,
                    PRIMARY KEY (`Id`),
                    FOREIGN KEY (`discoId`) REFERENCES `{disco}` (`id`),
                    FOREIGN KEY (`vendaId`) REFERENCES `{venda}` (`id`)
                );
            ";

            #endregion

            #region Inseri dados

            string queryInsertData = $@"
                INSERT INTO {disco} values (1, 'Thriller', 'Pop', 10.0);
                INSERT INTO {disco} values (2, 'Thriller', 'Pop', 10.0);
                INSERT INTO {disco} values (3, 'Thriller', 'Pop', 10.0);
                INSERT INTO {disco} values (4, 'Thriller', 'Pop', 10.0);
                INSERT INTO {disco} values (5, 'Thriller', 'Pop', 10.0);
                INSERT INTO {disco} values (6, 'Thriller', 'Pop', 10.0);
                INSERT INTO {disco} values (7, 'Thriller', 'Pop', 10.0);
                INSERT INTO {disco} values (8, 'Thriller', 'Pop', 10.0);
                INSERT INTO {disco} values (9, 'The Beatles', 'Rock', 10.0);
                INSERT INTO {disco} values (10, 'Red Hot Chili Peppers', 'Rock', 10.0);
                INSERT INTO {disco} values (11, 'Pink Floyd', 'Rock', 10.0);
                INSERT INTO {disco} values (12, 'Metallica', 'Rock', 10.0);

                INSERT INTO {venda} values (1, '2019-04-16');
                INSERT INTO {venda} values (2, '2019-04-17');
                INSERT INTO {venda} values (3, '2019-04-18');

                INSERT INTO {itemVenda} values (1, 1, 1, 10.0, 0.25);
                INSERT INTO {itemVenda} values (2, 2, 1, 10.0, 0.25);
                INSERT INTO {itemVenda} values (3, 3, 2, 10.0, 0.25);
                INSERT INTO {itemVenda} values (4, 4, 2, 10.0, 0.25);
                INSERT INTO {itemVenda} values (5, 5, 3, 10.0, 0.25);
                INSERT INTO {itemVenda} values (6, 6, 3, 10.0, 0.25);
            ";

            #endregion

            return(queryCreateDatabase + queryInsertData);
        }
예제 #15
0
        //Create Project
        public void ProjectUpdate()
        {
            try
            {
                if (project.Text.Equals("") || projectDesc.Text.Equals("") || projectDeadline.Text.Equals(""))
                {
                    Toast.MakeText(this, "Fill in all fields!", ToastLength.Long).Show();
                    return;
                }
                else
                {
                    if (DateTime.Parse(projectDeadline.Text) <= DateTime.Parse(projectStart.Text))
                    {
                        Toast.MakeText(this, "Project deadline should be greater than project start date!", ToastLength.Long).Show();
                        return;
                    }
                    if (DateTime.Parse(projectDeadline.Text) <= DateTime.Today)
                    {
                        Toast.MakeText(this, "Project deadline should be greater than current date!", ToastLength.Long).Show();
                        return;
                    }
                    else
                    {
                        DBHelper dbh = new DBHelper();

                        string  mproject         = DatabaseUtils.SqlEscapeString(project.Text);
                        string  mprojectDesc     = DatabaseUtils.SqlEscapeString(projectDesc.Text);
                        string  mprojectStart    = projectStart.Text;
                        string  mprojectDeadline = projectDeadline.Text;
                        decimal mprojectBudget   = Convert.ToDecimal(projectBudget.Text);
                        int     stat             = projectStatus.SelectedItemPosition;
                        string  mprojectStatus   = "Pending";

                        if (stat == 0)
                        {
                            mprojectStatus = "Pending";
                        }
                        if (stat == 1)
                        {
                            mprojectStatus = "Postponed";
                        }
                        if (stat == 2)
                        {
                            mprojectStatus = "Completed";
                        }

                        string result = dbh.UpdateProject(selProjectId, mproject, mprojectDesc, mprojectStart, mprojectDeadline, mprojectBudget, mprojectStatus);

                        if (result.Equals("ok"))
                        {
                            Toast.MakeText(this, "Project updated!", ToastLength.Short).Show();
                            Finish();
                        }
                        else
                        {
                            Toast.MakeText(this, result, ToastLength.Short).Show();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show();
            }
        }
        private void TracksCvs_Filter(object sender, FilterEventArgs e)
        {
            KeyValuePair <string, TrackViewModel> vm = (KeyValuePair <string, TrackViewModel>)e.Item;

            e.Accepted = DatabaseUtils.FilterTracks(vm.Value.Track, this.searchService.SearchText);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (!_needBake || !GhDrawingContext.LinkedDocument.IsActive)
            {
                return;
            }

            /*Extract input parameters*/
            IGH_GeometricGoo geometry = null;

            if (!DA.GetData("Geometry", ref geometry))
            {
                return;
            }

            var elementType = Bricscad.Bim.BimTypeElement.BimGenericBuildingElt;

            Types.ElementType type = null;
            if (DA.GetData("ElementType", ref type))
            {
                elementType = type.Value;
            }

            Bricscad.Bim.BIMSpatialLocation spatialLocation = null;
            Types.SpatialLocation           location        = null;
            if (DA.GetData("SpatialLocation", ref location))
            {
                spatialLocation = location.Value;
            }

            var objIds = BakeGhGeometry(geometry);

            if (objIds == null)
            {
                return;
            }

            Bricscad.Bim.BIMProfile bimProfile = null;
            Types.Profile           profile    = null;
            if (DA.GetData("Profile", ref profile))
            {
                var dummy = new Bricscad.Bim.BIMProfile(profile.Value);
                if (dummy.SaveProfile(GhDrawingContext.LinkedDocument.Database) == Bricscad.Bim.BimResStatus.Ok)
                {
                    bimProfile = dummy;
                }
            }

            var createdProfileId = _OdDb.ObjectId.Null;

            _OdDb.ObjectEventHandler objAppended = (s, e) => createdProfileId = e.DBObject.ObjectId;
            GhDrawingContext.LinkedDocument.Database.ObjectAppended += objAppended;
            var curvesToDelete = new _OdDb.ObjectIdCollection();

            for (int i = 0; i < objIds.Count; ++i)
            {
                var id = objIds[i];
                spatialLocation?.AssignToEntity(id);
                Bricscad.Bim.BIMClassification.ClassifyAs(id, elementType);
                bimProfile?.ApplyProfileTo(id, 0, true);
                //replace curve with created solid profile
                if (DatabaseUtils.IsCurve(id) && !createdProfileId.IsNull)
                {
                    curvesToDelete.Add(id);
                    objIds[i]        = createdProfileId;
                    createdProfileId = _OdDb.ObjectId.Null;
                }
            }
            DatabaseUtils.EraseObjects(curvesToDelete);
            GhDrawingContext.LinkedDocument.Database.ObjectAppended -= objAppended;
            var res = new List <Types.BcEntity>();

            foreach (_OdDb.ObjectId objId in objIds)
            {
                DA.SetData("BuildingElement",
                           new Types.BcEntity(new _OdDb.FullSubentityPath(new _OdDb.ObjectId[] { objId }, new _OdDb.SubentityId()), GhDrawingContext.LinkedDocument.Name));
            }
        }
예제 #18
0
        public void CreateParameterList_IsNotNulls_Test()
        {
            var paramList = DatabaseUtils.CreateParameterList <TestDbParameter>(null);

            paramList.Count.Should().Be(0);
        }
 public void SetupTestFixture()
 {
     DatabaseUtils.RestoreDatabase("AdventureWorks", "AdventureWorks", Constants.Server);
     SqlConnection.ClearAllPools();
 }
예제 #20
0
 public AlunoMODEL()
 {
     dbUtils = new DatabaseUtils();
 }
예제 #21
0
    public ActionResult SubmitQuestionReference(string saveType, bool isNew) //isNew (reference)
    {
        if (String.IsNullOrEmpty((string)Session["userId"]))
        {
            return(RedirectToAction("Login", "Account"));
        }
        try
        {
            int answerID = (int)Session["selectedAnswer"];
            if (!saveType.Equals("Cancel"))
            {
                QuestionReference newReference = new QuestionReference();
                newReference.prevQuestionReference        = Convert.ToInt32(Request["newQuestionReference.prevQuestionReference"]);
                newReference.questionReference            = Convert.ToInt32(Request["newQuestionReference.questionReference"]);
                newReference.questionReferenceProbability = Convert.ToInt32(Request["newQuestionReference.questionReferenceProbability"]);

                ((EditScenarioModel)Session["editScenario"]).currentQuestionReferencesInAnswer = new List <int>();

                if (((EditScenarioModel)Session["editScenario"]).newAnswer.questionReferences == null)
                {
                    ((EditScenarioModel)Session["editScenario"]).newAnswer.questionReferences = new List <QuestionReference>();
                }

                foreach (QuestionReference reference in ((EditScenarioModel)Session["editScenario"]).newAnswer.questionReferences)
                {
                    ((EditScenarioModel)Session["editScenario"]).currentQuestionReferencesInAnswer.Add(reference.questionReference);
                }

                if (isNew)
                {
                    if (((EditScenarioModel)Session["editScenario"]).currentQuestionReferencesInAnswer.Contains(newReference.questionReference))
                    {
                        Console.Out.WriteLine("DIRTY ADD");
                        ((EditScenarioModel)Session["editScenario"]).errorMsg = "That question is already referenced by this answer. Please select a different question.";
                        return(View("_PartialAddAnswerReferences", ((EditScenarioModel)Session["editScenario"])));
                    }
                    else
                    {
                        Console.Out.WriteLine("CLEAN ADD");
                        ((EditScenarioModel)Session["editScenario"]).errorMsg = "";
                        DatabaseUtils.addAnswerReference(answerID, newReference);
                    }
                }
                else
                {
                    ((EditScenarioModel)Session["editScenario"]).newAnswer.questionReferences[((EditScenarioModel)Session["editScenario"]).editReferenceId].questionReference            = newReference.questionReference;
                    ((EditScenarioModel)Session["editScenario"]).newAnswer.questionReferences[((EditScenarioModel)Session["editScenario"]).editReferenceId].questionReferenceProbability = newReference.questionReferenceProbability;
                    int count = 0;
                    foreach (QuestionReference qr in ((EditScenarioModel)Session["editScenario"]).newAnswer.questionReferences)
                    {
                        if (qr.questionReference.Equals(newReference.questionReference))
                        {
                            count++;
                        }
                    }
                    if (count > 1)
                    {
                        Console.Out.WriteLine("DIRTY UPDATE");
                        ((EditScenarioModel)Session["editScenario"]).errorMsg = "An answer already references that question";
                        return(View("_PartialEditAnswerReferences", ((EditScenarioModel)Session["editScenario"])));
                    }
                    else
                    {
                        Console.Out.WriteLine("CLEAN UPDATE");
                        ((EditScenarioModel)Session["editScenario"]).errorMsg = "";
                        DatabaseUtils.editAnswerReference(answerID, newReference);
                    }
                }
                Session["currentScenario"] = DatabaseUtils.getScenario(((EditScenarioModel)Session["editScenario"]).ScenarioId);
                //sets the ((EditScenarioModel)Session["editScenario"])
            }
            getEditQuestionsAndAnswers(((Scenario)Session["currentScenario"]));
            CheckForError();
            return(EditAnswer(answerID));
        }
        catch (Exception ex)
        {
            Singleton.errorCode = "SENCON24";
            Singleton.writeErrorToFile(Singleton.errorCode, ex.Message, ex.StackTrace);
            throw ex;
        }
    }
예제 #22
0
        public string GetStlWhereString(int siteId, string group, string groupNot, string tags, bool isTopExists, bool isTop, string where)
        {
            var whereStringBuilder = new StringBuilder();

            if (isTopExists)
            {
                whereStringBuilder.Append($" AND IsTop = '{isTop}' ");
            }

            var database = Database;

            if (!string.IsNullOrEmpty(group))
            {
                group = group.Trim().Trim(',');
                var groupArr = group.Split(',');
                if (groupArr.Length > 0)
                {
                    whereStringBuilder.Append(" AND (");
                    foreach (var theGroup in groupArr)
                    {
                        var trimGroup = theGroup.Trim();

                        whereStringBuilder.Append(
                            $" ({nameof(Content.GroupNames)} = '{Utilities.FilterSql(trimGroup)}' OR {DatabaseUtils.GetInStr(database, nameof(Content.GroupNames), trimGroup + ",")} OR {DatabaseUtils.GetInStr(database, nameof(Content.GroupNames), "," + trimGroup + ",")} OR {DatabaseUtils.GetInStr(database, nameof(Content.GroupNames), "," + trimGroup)}) OR ");
                    }
                    if (groupArr.Length > 0)
                    {
                        whereStringBuilder.Length -= 3;
                    }
                    whereStringBuilder.Append(") ");
                }
            }

            if (!string.IsNullOrEmpty(groupNot))
            {
                groupNot = groupNot.Trim().Trim(',');
                var groupNotArr = groupNot.Split(',');
                if (groupNotArr.Length > 0)
                {
                    whereStringBuilder.Append(" AND (");
                    foreach (var theGroupNot in groupNotArr)
                    {
                        //whereStringBuilder.Append(
                        //    $" ({ContentAttribute.GroupNameCollection} <> '{theGroupNot.Trim()}' AND CHARINDEX('{theGroupNot.Trim()},',{ContentAttribute.GroupNameCollection}) = 0 AND CHARINDEX(',{theGroupNot.Trim()},',{ContentAttribute.GroupNameCollection}) = 0 AND CHARINDEX(',{theGroupNot.Trim()}',{ContentAttribute.GroupNameCollection}) = 0) AND ");

                        whereStringBuilder.Append(
                            $" ({nameof(Content.GroupNames)} <> '{theGroupNot.Trim()}' AND {DatabaseUtils.GetNotInStr(database, nameof(Content.GroupNames), theGroupNot.Trim() + ",")} AND {DatabaseUtils.GetNotInStr(database, nameof(Content.GroupNames), "," + theGroupNot.Trim() + ",")} AND {DatabaseUtils.GetNotInStr(database, nameof(Content.GroupNames), "," + theGroupNot.Trim())}) AND ");
                    }
                    if (groupNotArr.Length > 0)
                    {
                        whereStringBuilder.Length -= 4;
                    }
                    whereStringBuilder.Append(") ");
                }
            }

            if (!string.IsNullOrEmpty(tags))
            {
                tags = tags.Trim().Trim(',');
                var tagNames = ListUtils.GetStringList(tags);
                if (tagNames.Count > 0)
                {
                    whereStringBuilder.Append(" AND (");
                    foreach (var tagName in tagNames)
                    {
                        whereStringBuilder.Append(
                            $" ({nameof(Content.TagNames)} = '{Utilities.FilterSql(tagName)}' OR {DatabaseUtils.GetInStr(database, nameof(Content.TagNames), tagName + ",")} OR {DatabaseUtils.GetInStr(database, nameof(Content.TagNames), "," + tagName + ",")} OR {DatabaseUtils.GetInStr(database, nameof(Content.TagNames), "," + tagName)}) OR ");
                    }
                    whereStringBuilder.Length -= 3;
                    whereStringBuilder.Append(") ");
                }
            }

            if (!string.IsNullOrEmpty(where))
            {
                whereStringBuilder.Append($" AND ({where}) ");
            }

            return(whereStringBuilder.ToString());
        }
예제 #23
0
 public IActionResult Clean()
 {
     DatabaseUtils.ClearDB(m_Context);
     return(RedirectToAction("Index"));
 }
 public ConsolidationMapGetDataOperation(string adminConnectionString, string tableName)
     : base(DatabaseUtils.CreateConnectionStringSettings(adminConnectionString))
 {
     _tableName = tableName;
 }
예제 #25
0
 public IActionResult AddWords()
 {
     DatabaseUtils.PopulateWithTestData(m_Context);
     return(RedirectToAction("Index"));
 }
예제 #26
0
파일: Program.cs 프로젝트: piltatnik/MFtp
        private static void WriteMessages(decimal slCost)
        {
            DateTime calcDate    = DateTime.Now.Date.AddSeconds(-1);
            string   clientsPath = Path.Combine(_settings.Report.Path,
                                                $"01_client_transport_{calcDate.ToString("ddMMyyyy_HHmmss")}.xml");
            string walletsPath = Path.Combine(_settings.Report.Path,
                                              $"02_wallet_transport_{calcDate.ToString("ddMMyyyy_HHmmss")}.xml");
            string opHistPath = Path.Combine(_settings.Report.Path,
                                             $"03_ophist_transport_{calcDate.ToString("ddMMyyyy_HHmmss")}.xml");

            WriteLog(
                $"Вызываем расчет сообщений на дату {calcDate.ToString("dd.MM.yyyy HH:mm:ss")}. Проезд по серии SL стоит: {slCost}");
            OracleTransaction tran = _connection.BeginTransaction();

            try
            {
                OracleParameter pDate = new OracleParameter()
                {
                    ParameterName = "pDate",
                    OracleDbType  = OracleDbType.Date,
                    Value         = calcDate
                };
                DatabaseUtils.CallProcedure(_connection, "pkg$xftp_messages.createmessages",
                                            new OracleParameter[]
                {
                    pDate,
                    new OracleParameter()
                    {
                        ParameterName = "pSLTravelCost", OracleDbType = OracleDbType.Decimal, Value = slCost
                    }
                });

                OracleParameter pXml = new OracleParameter()
                {
                    ParameterName = "pXml",
                    OracleDbType  = OracleDbType.Clob,
                    Direction     = ParameterDirection.Output
                };

                DatabaseUtils.CallProcedure(_connection, "pkg$xftp_messages.getClients",
                                            new OracleParameter[] { pDate, pXml });
                WriteXml(clientsPath, pXml.Value);

                DatabaseUtils.CallProcedure(_connection, "pkg$xftp_messages.getWallets",
                                            new OracleParameter[] { pDate, pXml });
                WriteXml(walletsPath, pXml.Value);

                DatabaseUtils.CallProcedure(_connection, "pkg$xftp_messages.getOperationHistory",
                                            new OracleParameter[] { pDate, pXml });
                WriteXml(opHistPath, pXml.Value);

                WriteFtp(_settings.Ftp.Path, _settings.Ftp.Login, _settings.Ftp.Password, clientsPath);
                WriteFtp(_settings.Ftp.Path, _settings.Ftp.Login, _settings.Ftp.Password, walletsPath);
                WriteFtp(_settings.Ftp.Path, _settings.Ftp.Login, _settings.Ftp.Password, opHistPath);
                tran.Commit();
            }
            catch (Exception e)
            {
                tran.Rollback();
                throw new Exception($"При формировании сообщения произошла ошибка:\r\n{e.Message}");
            }
        }
예제 #27
0
 public IActionResult Delete()
 {
     DatabaseUtils.DeleteDB(m_Context);
     return(RedirectToAction("Index"));
 }
예제 #28
0
 public void TruncateIfForcedRebuild()
 {
     if (_configuration.ForceRebuild)
     {
         _log.DebugFormat("'Force rebuild' option is set so dropping tables in {0}", DatabaseUtils.GetConnectionDescription(PublicConnectionString));
         DatabaseUtils.DropTablesInDatabase(PublicConnectionString, Timeouts.PublicDatabase);
     }
 }
예제 #29
0
        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            var vm = DataContext as DatabaseTreeVM;

            vm.DbTables = new ObservableCollection <DbTable>(DatabaseUtils.FromDB(vm.DBName));
        }
 public DiscoRepository(IDatabaseConfig config)
 {
     _action     = config.DbAction;
     _tableDisco = DatabaseUtils.Table <Disco>();
 }
예제 #31
0
 // Also deletes migration history if used on main db
 public void DeteteDB()
 {
     DatabaseUtils.DeleteDB(DatabaseContext);
 }