Example #1
0
        /// <summary>
        /// Updates an input DataObject with a Database and Schema extension (two key/value pairs) based on its connection properties (TeamConnection object).
        /// </summary>
        /// <param name="dataObject"></param>
        /// <param name="teamConnection"></param>
        /// <param name="jsonExportSetting"></param>
        /// <returns></returns>
        public static DataObject SetDataObjectSchemaExtension(DataObject dataObject, TeamConnection teamConnection, JsonExportSetting jsonExportSetting)
        {
            if (jsonExportSetting.GenerateSchemaAsExtension == "True" && dataObject.dataObjectConnection != null)
            {
                List <Extension> extensions = new List <Extension>();

                var extension = new Extension
                {
                    key         = "schema",
                    value       = teamConnection.DatabaseServer.SchemaName,
                    description = "schema name"
                };

                extensions.Add(extension);

                if (dataObject.dataObjectConnection.extensions is null)
                {
                    dataObject.dataObjectConnection.extensions = extensions;
                }
                else
                {
                    dataObject.dataObjectConnection.extensions.AddRange(extensions);
                }
            }

            return(dataObject);
        }
        /**
         * @description retrieves the games from the database
         * @method GetGames
         * @return {void}
         */
        protected void GetGames()
        {
            // connect to the entity framework5

            using (TeamConnection db = new TeamConnection())
            {
                //query the Students table using EF and LINQ
                var games = (from g in db.Games
                             join t1 in db.Teams on g.HomeTeamId equals t1.TeamId
                             join t2 in db.Teams on g.AwayTeamId equals t2.TeamId
                             select new
                {
                    Home = t1.TeamName,
                    Away = t2.TeamName,
                    Points = g.AwayPoints + g.HomePoints,
                    Spectators = g.Spectators,
                    GameDate = g.GameDate,
                    GameId = g.GameId
                });

                //bind the result to the gridview
                GamesGridView.DataSource = games.ToList();
                GamesGridView.DataBind();
            }
        }
Example #3
0
        /// <summary>
        /// MEthod that gets all teams
        /// </summary>
        /// <returns></returns>
        public List <Team> getAllTeams()
        {
            List <Team> _lstTeam = TeamConnection.readAllTeams();

            foreach (Team _oTeamItem in _lstTeam)
            {
                this.returnWithoutSpaces(_oTeamItem);
            }
            return(_lstTeam);
        }
Example #4
0
        /// <summary>
        /// Method that updates a team with
        /// </summary>
        /// <param name="pCode"></param>
        /// <param name="sTeam_name"></param>
        /// <returns>Return true if it deleted, or false if it not updated</returns>
        public bool updateTeam(String pCode, String sTeam_name)
        {
            Team _newTeam = new Team
            {
                code = pCode,
                name = sTeam_name
            };

            return(TeamConnection.updateTeam(_newTeam));
        }
Example #5
0
        /// <summary>
        /// Method that creates a Team
        /// </summary>
        /// <param name="code">The code team</param>
        /// <param name="name">The name team</param>
        /// <returns>Returns object Team</returns>
        public bool createTeam(String code, String name)
        {
            Team newTeam = new Team
            {
                code = code,
                name = name
            };

            return(TeamConnection.createTeam(newTeam));
        }
Example #6
0
        public void DeleteConnection(object sender, EventArgs e)
        {
            if (_localConnection.ConnectionKey != "New")
            {
                // Remove the entry from the configuration file
                if (!File.Exists(_connectionFileName))
                {
                    File.Create(_connectionFileName).Close();
                }

                // Check if the value already exists in the file
                var jsonKeyLookup = new TeamConnection();

                TeamConnection[] jsonArray = JsonConvert.DeserializeObject <TeamConnection[]>(
                    File.ReadAllText(_connectionFileName));

                // If the Json file already contains values (non-empty) then perform a key lookup.
                if (jsonArray != null)
                {
                    jsonKeyLookup = jsonArray.FirstOrDefault(obj =>
                                                             obj.ConnectionInternalId == _localConnection.ConnectionInternalId);
                }

                // If nothing yet exists in the file, the key lookup is NULL or "" then the record in question does not exist in the Json file.
                // No action needed in this case.
                if (jsonArray == null || jsonKeyLookup == null || jsonKeyLookup.ConnectionKey == "")
                {
                    // Do nothing.
                }
                else
                {
                    // Remove the Json segment.
                    var list         = jsonArray.ToList();
                    var itemToRemove =
                        list.Single(r => r.ConnectionInternalId == _localConnection.ConnectionInternalId);
                    list.Remove(itemToRemove);
                    jsonArray = list.ToArray();

                    UpdateRichTextBoxInformation(
                        $"The connection {_localConnection.ConnectionKey} was removed from {_connectionFileName}.\r\n");

                    // Remove the connection from the global dictionary
                    FormBase.TeamConfiguration.ConnectionDictionary.Remove(_localConnection.ConnectionInternalId);
                }

                // Save the updated file to disk.
                string output = JsonConvert.SerializeObject(jsonArray, Formatting.Indented);
                File.WriteAllText(_connectionFileName, output);
            }

            // The name of the tab page is passed back to the original control (the tab control).
            OnDeleteConnection(this, new MyConnectionProfileEventArgs(_localConnection));
        }
Example #7
0
 /**
  * @description Retrieves the list of teams from the database
  * @method GetTeams
  * @return {void}
  */
 protected void GetTeams()
 {
     using (TeamConnection db = new TeamConnection())
     {
         var teamQuery = (from allTeams in db.Teams
                          select allTeams.TeamName);
         HomeTeamDropDownList.DataSource = teamQuery.ToList();
         HomeTeamDropDownList.DataBind();
         AwayTeamDropDownList.DataSource = teamQuery.ToList();
         AwayTeamDropDownList.DataBind();
     }
 }
Example #8
0
        /// <summary>
        /// Add a Data Object Connection based on the TeamConnection details.
        /// </summary>
        /// <param name="dataObject"></param>
        /// <param name="teamConnection"></param>
        /// <param name="jsonExportSetting"></param>
        /// <returns></returns>
        public static DataObject SetDataObjectConnection(DataObject dataObject, TeamConnection teamConnection, JsonExportSetting jsonExportSetting)
        {
            if (jsonExportSetting.GenerateDataObjectConnection == "True")
            {
                // Add dataObjectConnection, including connection string (to Data Object).
                var localDataConnection = new DataConnection();
                localDataConnection.dataConnectionString = teamConnection.ConnectionKey;

                dataObject.dataObjectConnection = localDataConnection;
            }

            return(dataObject);
        }
Example #9
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            // Use EF to connect to the server
            using (TeamConnection db = new TeamConnection())
            {
                // use the Student model to create a new student object and
                // save a new record
                team newTeam = new team();

                int TeamID = 0;

                if (Request.QueryString.Count > 0) // our URL has a StudentID in it
                {
                    // get the id from the URL
                    TeamID = Convert.ToInt32(Request.QueryString["team_id"]);

                    // get the current student from EF DB
                    newTeam = (from teams in db.teams
                               where teams.team_id == TeamID
                               select teams).FirstOrDefault();
                }

                // add form data to the new student record
                newTeam.team_wins            = Convert.ToInt32(WinsTextBox.Text);
                newTeam.team_losses          = Convert.ToInt32(LossesTextBox.Text);
                newTeam.team_rank            = Convert.ToInt32(RankTextBox.Text);
                newTeam.team_number_of_games = Convert.ToInt32(NumberofGamesTextBox.Text);

                // use LINQ to ADO.NET to add / insert new student into the database

                if (TeamID == 0)
                {
                    db.teams.Add(newTeam);
                }


                // save our changes - also updates and inserts
                try {
                    db.SaveChanges();
                }
                catch (Exception err)
                {
                    Console.WriteLine(err);
                }

                // Redirect back to the updated students page
                Response.Redirect("~/Default.aspx");
            }
        }
Example #10
0
        /**
         * @description gets all the teams from the database
         * @method GetTeams
         * @return {void}
         */
        protected void GetTeams()
        {
            // connect to the entity framework

            using (TeamConnection db = new TeamConnection())
            {
                //query the Students table using EF and LINQ
                var teams = (from allTeams in db.Teams
                             select allTeams);

                //bind the result to the gridview
                TeamsGridView.DataSource = teams.ToList();
                TeamsGridView.DataBind();
            }
        }
        /**
         * @description Event Handler for deleteing a game
         * @method GamesGridView_RowDeleting
         * @param {object} sender
         * @param {EventArgs} e
         * @return {void}
         */
        protected void GamesGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int selectedRow = e.RowIndex;

            int GameId = Convert.ToInt32(GamesGridView.DataKeys[selectedRow].Values["GameId"]);

            using (TeamConnection db = new TeamConnection())
            {
                Game deleteGame = (from game in db.Games
                                   where game.GameId == GameId
                                   select game).FirstOrDefault();
                db.Games.Remove(deleteGame);
                db.SaveChanges();
                this.GetGames();
            }
        }
        /**
         * @description selects a team from the database for updating purposes
         * @method GetTeam
         * @return {void}
         */
        protected void GetTeam()
        {
            int teamID = Convert.ToInt32(Request.QueryString["TeamId"]);

            using (TeamConnection db = new TeamConnection())
            {
                Team updateTeam = (from team in db.Teams
                                   where team.TeamId == teamID
                                   select team).FirstOrDefault();

                if (updateTeam != null)
                {
                    TeamNameTextBox.Text = updateTeam.TeamName;
                }
            }
        }
Example #13
0
        /**
         * @description Event Handler deleting a team from the database
         * @method TeamsGridView_RowDeleting
         * @param {object} sender
         * @param {EventArgs} e
         * @return {void}
         */
        protected void TeamsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int selectedRow = e.RowIndex;

            int TeamId = Convert.ToInt32(TeamsGridView.DataKeys[selectedRow].Values["TeamId"]);

            using (TeamConnection db = new TeamConnection())
            {
                Team deleteTeam = (from team in db.Teams
                                   where team.TeamId == TeamId
                                   select team).FirstOrDefault();

                db.Teams.Remove(deleteTeam);
                db.SaveChanges();
                this.GetTeams();
            }
        }
Example #14
0
        /// <summary>
        /// Create Data Object in TEAM.
        /// </summary>
        /// <param name="dataObjectName"></param>
        /// <param name="teamConnection"></param>
        /// <param name="jsonExportSetting"></param>
        /// <returns></returns>
        public static DataObject CreateDataObject(string dataObjectName, TeamConnection teamConnection, JsonExportSetting jsonExportSetting)
        {
            DataObject localDataObject = new DataObject();

            localDataObject.name = dataObjectName;

            // Data Object Connection
            localDataObject = SetDataObjectConnection(localDataObject, teamConnection, jsonExportSetting);

            // Source and target connection information as extensions
            localDataObject = SetDataObjectDatabaseExtension(localDataObject, teamConnection, jsonExportSetting);
            localDataObject = SetDataObjectSchemaExtension(localDataObject, teamConnection, jsonExportSetting);

            // Add classifications
            localDataObject = SetDataObjectTypeClassification(localDataObject, jsonExportSetting);

            return(localDataObject);
        }
Example #15
0
        /// <summary>
        /// Create the special-type metadata Data Object.
        /// </summary>
        /// <param name="metaDataConnection"></param>
        /// <param name="jsonExportSetting"></param>
        /// <returns></returns>
        public static DataObject CreateMetadataDataObject(TeamConnection metaDataConnection, JsonExportSetting jsonExportSetting)
        {
            DataObject localDataObject = new DataObject();

            if (jsonExportSetting.AddMetadataAsRelatedDataObject == "True")
            {
                localDataObject = CreateDataObject("Metadata", metaDataConnection, jsonExportSetting);

                // Override classification
                if (jsonExportSetting.GenerateTypeAsClassification == "True")
                {
                    localDataObject.dataObjectClassification[0].classification = "Metadata";
                }
            }


            return(localDataObject);
        }
Example #16
0
        /**
         * @description Event Handler for save button press, saves the team into the database if all required fields are filed in
         * @method SaveButton_Click
         * @param {object} sender
         * @param {EventArgs} e
         * @return {void}
         */
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            //use EF to connect to the server
            using (TeamConnection db = new TeamConnection())
            {
                //use the Student model to create a new student object and
                //save a new record
                Game newGame = new Game();

                string home = HomeTeamDropDownList.Text;
                string away = AwayTeamDropDownList.Text;
                System.Diagnostics.Debug.WriteLine(HomeTeamDropDownList.Text);
                System.Diagnostics.Debug.WriteLine(home);
                System.Diagnostics.Debug.WriteLine(home.Equals("Balls & Dolls"));

                var homeTeamId = (from teams in db.Teams
                                  where teams.TeamName == home
                                  select teams).FirstOrDefault().TeamId;

                var awayTeamId = (from teams in db.Teams
                                  where teams.TeamName == away
                                  select teams).FirstOrDefault().TeamId;

                System.Diagnostics.Debug.WriteLine(homeTeamId); System.Diagnostics.Debug.WriteLine(homeTeamId); System.Diagnostics.Debug.WriteLine(homeTeamId); System.Diagnostics.Debug.WriteLine(homeTeamId);
                //add data to the new Game record
                newGame.HomeTeamId = Convert.ToInt32(homeTeamId);
                newGame.AwayTeamId = Convert.ToInt32(awayTeamId);
                newGame.HomePoints = Convert.ToInt32(HomePointsTextBox.Text);
                newGame.AwayPoints = Convert.ToInt32(AwayPointsTextBox.Text);
                newGame.Spectators = Convert.ToInt32(SpectatorsTextBox.Text);
                newGame.GameDate   = Convert.ToDateTime(GameDateTextBox.Text);

                //use LINQ to ADO.net to add / insert my new Game into the DB
                db.Games.Add(newGame);

                //save our changes
                db.SaveChanges();

                //redirect back to the updated Games page
                Response.Redirect("~/DodgeBall/Games.aspx");
            }
        }
Example #17
0
        /**
         * <summary>
         * This method gets the student data from the DB
         * </summary>
         *
         * @method GetStudents
         * @returns {void}
         */
        protected void GetTeams()
        {
            // connect to EF
            using (TeamConnection db = new TeamConnection())
            {
                string SortString = Session["SortColumn"].ToString() + " " + Session["SortDirection"].ToString();


                // query the Teams Table using EF and LINQ
                var Teams = (from allTeams in db.teams
                             where allTeams.team_id == 5
                             select allTeams);

                var Teams2 = (from allTeams in db.teams
                              where allTeams.team_id == 6
                              select allTeams);

                // bind the result to the GridView
                GridView1.DataSource = Teams.AsQueryable().ToList();
                GridView1.DataBind();
                GridView2.DataSource = Teams.AsQueryable().ToList();
                GridView2.DataBind();
                GridView3.DataSource = Teams.AsQueryable().ToList();
                GridView3.DataBind();
                GridView4.DataSource = Teams.AsQueryable().ToList();
                GridView4.DataBind();

                GridView5.DataSource = Teams2.AsQueryable().ToList();
                GridView5.DataBind();
                GridView6.DataSource = Teams2.AsQueryable().ToList();
                GridView6.DataBind();
                GridView7.DataSource = Teams2.AsQueryable().ToList();
                GridView7.DataBind();
                GridView8.DataSource = Teams2.AsQueryable().ToList();
                GridView8.DataBind();

                // query the Students Table using EF and LINQ
                var Students = (from allStudents in db.teams
                                select allStudents);
            }
        }
Example #18
0
        public static List <DataObject> SetLineageRelatedDataObjectList(DataTable dataObjectMappingDataTable, string targetDataObjectName, JsonExportSetting jsonExportSetting)
        {
            List <DataObject> dataObjectList = new List <DataObject>();

            if (jsonExportSetting.AddUpstreamDataObjectsAsRelatedDataObject == "True")
            {
                // Find the corresponding row in the Data Object Mapping grid
                DataRow[] DataObjectMappings = dataObjectMappingDataTable.Select("[" + TableMappingMetadataColumns.SourceTable + "] = '" + targetDataObjectName + "'");

                foreach (DataRow DataObjectMapping in DataObjectMappings)
                {
                    var localDataObjectName = DataObjectMapping[TableMappingMetadataColumns.TargetTable.ToString()].ToString();
                    var localDataObjectConnectionInternalId = DataObjectMapping[TableMappingMetadataColumns.TargetConnection.ToString()].ToString();

                    TeamConnection localConnection = FormBase.GetTeamConnectionByConnectionId(localDataObjectConnectionInternalId);

                    // Set the name and further settings.
                    dataObjectList.Add(CreateDataObject(localDataObjectName, localConnection, jsonExportSetting));
                }
            }

            return(dataObjectList);
        }
Example #19
0
        protected void GetTeams()
        {
            // populate teh form with existing data from the database
            int TeamID = Convert.ToInt32(Request.QueryString["team_id"]);

            // connect to the EF DB
            using (TeamConnection db = new TeamConnection())
            {
                // populate a student object instance with the StudentID from the URL Parameter
                team updatedTeam = (from teams in db.teams
                                    where teams.team_id == TeamID
                                    select teams).FirstOrDefault();

                // map the student properties to the form controls
                if (updatedTeam != null)
                {
                    WinsTextBox.Text          = updatedTeam.team_wins.ToString();
                    LossesTextBox.Text        = updatedTeam.team_losses.ToString();
                    RankTextBox.Text          = updatedTeam.team_rank.ToString();
                    NumberofGamesTextBox.Text = updatedTeam.team_number_of_games.ToString();
                }
            }
        }
        /**
         * @description Event Handler for save button click
         * @method SaveButton_Click
         * @param {object} sender
         * @param {EventArgs} e
         * @return {void}
         */
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            //connect to the server
            using (TeamConnection db = new TeamConnection())
            {
                Team newTeam = new Team();

                int teamID = 0;

                if (Request.QueryString.Count > 0)
                {
                    teamID = Convert.ToInt32(Request.QueryString["teamID"]);

                    newTeam = (from team in db.Teams
                               where team.TeamId == teamID
                               select team).FirstOrDefault();
                }

                //add data to the new student record
                newTeam.TeamName = TeamNameTextBox.Text;



                if (teamID == 0)
                {
                    //use LINQ and ADO.NET to add or insert newStudent into the Database
                    db.Teams.Add(newTeam);
                }


                //save changes
                db.SaveChanges();

                //redirect back to the updated students page
                Response.Redirect("~/DodgeBall/Teams.aspx");
            }
        }
Example #21
0
        /// <summary>
        /// This method ensures that a table object exists in the physical model against the catalog.
        /// </summary>
        /// <param name="fullyQualifiedValidationObject"></param>
        /// <param name="teamConnection"></param>
        /// <returns></returns>
        internal static string ValidateObjectExistencePhysical(KeyValuePair <string, string> fullyQualifiedValidationObject, TeamConnection teamConnection)
        {
            var conn = new SqlConnection {
                ConnectionString = teamConnection.CreateSqlServerConnectionString(false)
            };

            conn.Open();

            var localTable  = fullyQualifiedValidationObject.Value.Replace("[", "").Replace("]", "");
            var localSchema = fullyQualifiedValidationObject.Key.Replace("[", "").Replace("]", "");

            // Execute the check
            var cmd = new SqlCommand(
                "SELECT CASE WHEN EXISTS ((SELECT * " +
                "FROM sys.objects a " +
                "JOIN sys.schemas b on a.schema_id = b.schema_id " +
                "WHERE a.[name] = '" + localTable + "' and b.[name]= '" + localSchema + "')) THEN 1 ELSE 0 END", conn);


            var    exists = (int)cmd.ExecuteScalar() == 1;
            string returnExistenceEvaluation = exists.ToString();

            conn.Close();

            // return the result of the test;
            return(returnExistenceEvaluation);
        }
Example #22
0
        /// <summary>
        /// Validate the Business Key definition against the snapshot of the physical model (the physical model data grid), taking the source object and business key definition as input parameters, together with a connection string to validate against.
        /// </summary>
        /// <param name="validationObject"></param>
        /// <param name="businessKeyDefinition"></param>
        /// <param name="teamConnection"></param>
        /// <param name="inputDataTable"></param>
        /// <returns></returns>
        internal static Dictionary <Tuple <string, string>, bool> ValidateSourceBusinessKeyExistenceVirtual(string validationObject, string businessKeyDefinition, TeamConnection teamConnection, DataTable inputDataTable)
        {
            // First, the Business Keys for each table need to be identified information. This can be the combination of Business keys separated by a comma.
            // Every business key needs to be iterated over to validate if the attribute exists in that table.
            List <string> businessKeys = businessKeyDefinition.Split(',').ToList();

            Dictionary <Tuple <string, string>, bool> result = new Dictionary <Tuple <string, string>, bool>();

            foreach (string businessKey in businessKeys)
            {
                var trimBusinessKey = businessKey.Trim();

                // Handle concatenate and composite
                List <string> subKeys = new List <string>();

                if (trimBusinessKey.StartsWith("CONCATENATE"))
                {
                    var localBusinessKey = trimBusinessKey.Replace("CONCATENATE(", "").Replace(")", "");

                    subKeys = localBusinessKey.Split(';').ToList();
                }
                else if (trimBusinessKey.StartsWith("COMPOSITE"))
                {
                    var localBusinessKey = trimBusinessKey.Replace("COMPOSITE(", "").Replace(")", "");

                    subKeys = localBusinessKey.Split(';').ToList();
                }
                else
                {
                    subKeys.Add(trimBusinessKey);
                }

                foreach (string businessKeyPart in subKeys)
                {
                    // Handle hard-coded business key values
                    if (businessKeyPart.StartsWith("'") && businessKeyPart.EndsWith("'"))
                    {
                        // Do nothing
                    }
                    else
                    {
                        var objectDetails = MetadataHandling.GetFullyQualifiedDataObjectName(validationObject, teamConnection).FirstOrDefault();

                        bool returnExistenceEvaluation = false;

                        DataRow[] foundAuthors = inputDataTable.Select($"" + PhysicalModelMappingMetadataColumns.TableName + " = '" + objectDetails.Value + "' AND " + PhysicalModelMappingMetadataColumns.SchemaName + " = '" + objectDetails.Key + "' AND " + PhysicalModelMappingMetadataColumns.ColumnName + " = '" + businessKeyPart.Trim() + "'");
                        if (foundAuthors.Length != 0)
                        {
                            returnExistenceEvaluation = true;
                        }

                        result.Add(Tuple.Create(validationObject, businessKeyPart.Trim()), returnExistenceEvaluation);
                    }
                }
            }

            // Return the result of the test;
            return(result);
        }
Example #23
0
        /// <summary>
        /// Validate the Business Key definition against the physical model, taking the source object and business key definition as input parameters, together with a connection string to validate against.
        /// </summary>
        /// <param name="validationObject"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        internal static Dictionary <Tuple <string, string>, bool> ValidateSourceBusinessKeyExistencePhysical(string validationObject, string businessKeyDefinition, TeamConnection teamConnection)
        {
            // First, the Business Keys for each table need to be identified information. This can be the combination of Business keys separated by a comma.
            // Every business key needs to be iterated over to validate if the attribute exists in that table.
            List <string> businessKeys = businessKeyDefinition.Split(',').ToList();


            // Get the table the component belongs to if available
            var fullyQualifiedValidationObject = MetadataHandling.GetFullyQualifiedDataObjectName(validationObject, teamConnection).FirstOrDefault();
            var localTable  = fullyQualifiedValidationObject.Value.Replace("[", "").Replace("]", "");
            var localSchema = fullyQualifiedValidationObject.Key.Replace("[", "").Replace("]", "");

            // Now iterate over each table, as identified by the business key.
            var conn = new SqlConnection {
                ConnectionString = teamConnection.CreateSqlServerConnectionString(false)
            };

            conn.Open();

            Dictionary <Tuple <string, string>, bool> result = new Dictionary <Tuple <string, string>, bool>();

            foreach (string businessKey in businessKeys)
            {
                var trimBusinessKey = businessKey.Trim();

                // Handle concatenate and composite
                List <string> subKeys = new List <string>();

                if (trimBusinessKey.StartsWith("CONCATENATE"))
                {
                    var localBusinessKey = trimBusinessKey.Replace("CONCATENATE(", "").Replace(")", "");

                    subKeys = localBusinessKey.Split(';').ToList();
                }
                else if (trimBusinessKey.StartsWith("COMPOSITE"))
                {
                    var localBusinessKey = trimBusinessKey.Replace("COMPOSITE(", "").Replace(")", "");

                    subKeys = localBusinessKey.Split(';').ToList();
                }
                else
                {
                    subKeys.Add(trimBusinessKey);
                }

                foreach (string businessKeyPart in subKeys)
                {
                    // Handle hard-coded business key values
                    if (businessKeyPart.Trim().StartsWith("'") && businessKeyPart.Trim().EndsWith("'"))
                    {
                        // Do nothing
                    }
                    else
                    {
                        // Query the data dictionary to validate existence
                        var cmd = new SqlCommand("SELECT CASE WHEN EXISTS (" +
                                                 "(" +
                                                 "SELECT * FROM sys.columns a " +
                                                 "JOIN sys.objects b ON a.object_id = b.object_id " +
                                                 "JOIN sys.schemas c on b.schema_id = c.schema_id " +
                                                 "WHERE OBJECT_NAME(a.[object_id]) = '" + localTable + "' AND c.[name] = '" + localSchema + "' AND a.[name] = '" + businessKeyPart.Trim() + "'" +
                                                 ")" +
                                                 ") THEN 1 ELSE 0 END", conn);

                        var exists = (int)cmd.ExecuteScalar() == 1;
                        result.Add(Tuple.Create(validationObject, businessKeyPart.Trim()), exists);
                    }
                }
            }
            conn.Close();
            // Return the result of the test;
            return(result);
        }
Example #24
0
        /// <summary>
        /// Check if an attribute exists in the metadata.
        /// </summary>
        /// <param name="validationObject"></param>
        /// <param name="validationAttribute"></param>
        /// <param name="teamConnection"></param>
        /// <param name="inputDataTable"></param>
        /// <returns></returns>
        internal static string ValidateAttributeExistenceVirtual(string validationObject, string validationAttribute, TeamConnection teamConnection, DataTable inputDataTable)
        {
            string returnExistenceEvaluation = "False";

            if (validationAttribute != "NULL")
            {
                var objectDetails = MetadataHandling.GetFullyQualifiedDataObjectName(validationObject, teamConnection).FirstOrDefault();

                DataRow[] foundRows = inputDataTable.Select("" + PhysicalModelMappingMetadataColumns.TableName + " = '" + objectDetails.Value + "' AND " + PhysicalModelMappingMetadataColumns.SchemaName + "='" + objectDetails.Key + "' AND " + PhysicalModelMappingMetadataColumns.ColumnName + " = '" + validationAttribute + "'");

                if (foundRows.Length > 0)
                {
                    returnExistenceEvaluation = "True";
                }
            }
            else
            {
                returnExistenceEvaluation = "True";
            }

            // return the result of the test;
            return(returnExistenceEvaluation);
        }
Example #25
0
        /// <summary>
        /// Check if an object / table exists in the metadata.
        /// </summary>
        /// <param name="validationObject"></param>
        /// <param name="teamConnection"></param>
        /// <param name="inputDataTable"></param>
        /// <returns></returns>
        internal static string ValidateObjectExistenceVirtual(string validationObject, TeamConnection teamConnection, DataTable inputDataTable)
        {
            string returnExistenceEvaluation = "False";

            var objectDetails = MetadataHandling.GetFullyQualifiedDataObjectName(validationObject, teamConnection).FirstOrDefault();

            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.HashKey].ColumnName              = PhysicalModelMappingMetadataColumns.HashKey.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.VersionId].ColumnName            = PhysicalModelMappingMetadataColumns.VersionId.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.DatabaseName].ColumnName         = PhysicalModelMappingMetadataColumns.DatabaseName.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.SchemaName].ColumnName           = PhysicalModelMappingMetadataColumns.SchemaName.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.TableName].ColumnName            = PhysicalModelMappingMetadataColumns.TableName.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.ColumnName].ColumnName           = PhysicalModelMappingMetadataColumns.ColumnName.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.DataType].ColumnName             = PhysicalModelMappingMetadataColumns.DataType.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.CharacterLength].ColumnName      = PhysicalModelMappingMetadataColumns.CharacterLength.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.NumericPrecision].ColumnName     = PhysicalModelMappingMetadataColumns.NumericPrecision.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.NumericScale].ColumnName         = PhysicalModelMappingMetadataColumns.NumericScale.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.OrdinalPosition].ColumnName      = PhysicalModelMappingMetadataColumns.OrdinalPosition.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.PrimaryKeyIndicator].ColumnName  = PhysicalModelMappingMetadataColumns.PrimaryKeyIndicator.ToString();
            inputDataTable.Columns[(int)PhysicalModelMappingMetadataColumns.MultiActiveIndicator].ColumnName = PhysicalModelMappingMetadataColumns.MultiActiveIndicator.ToString();

            DataRow[] foundRows = inputDataTable.Select("" + PhysicalModelMappingMetadataColumns.TableName + " = '" + objectDetails.Value + "' AND " + PhysicalModelMappingMetadataColumns.SchemaName + " = '" + objectDetails.Key + "'");

            //bool existenceCheck = inputDataTable.AsEnumerable().Any(row => columns.Any(col => row[col].ToString() == objectName));

            if (foundRows.Length > 0)
            {
                returnExistenceEvaluation = "True";
            }

            // return the result of the test;
            return(returnExistenceEvaluation);
        }
Example #26
0
        internal static List <Tuple <string, string, bool> > BasicDataVaultValidation(string dataObjectName, TeamConnection teamConnection, MetadataHandling.TableTypes tableType)
        {
            // Initialise the return type
            List <Tuple <string, string, bool> > returnList = new List <Tuple <string, string, bool> >();

            // Define the list to validate, this is different for each validation type.
            List <string> validationAttributeList = new List <string>();

            switch (tableType)
            {
            case MetadataHandling.TableTypes.CoreBusinessConcept:
                validationAttributeList.Add(FormBase.TeamConfiguration.LoadDateTimeAttribute);
                break;

            case MetadataHandling.TableTypes.Context:

                if (FormBase.TeamConfiguration.EnableAlternativeSatelliteLoadDateTimeAttribute == "True")
                {
                    validationAttributeList.Add(FormBase.TeamConfiguration.AlternativeSatelliteLoadDateTimeAttribute);
                }
                else
                {
                    validationAttributeList.Add(FormBase.TeamConfiguration.LoadDateTimeAttribute);
                }

                validationAttributeList.Add(FormBase.TeamConfiguration.RecordChecksumAttribute);
                break;

            case MetadataHandling.TableTypes.NaturalBusinessRelationship:
                validationAttributeList.Add(FormBase.TeamConfiguration.LoadDateTimeAttribute);
                break;
            }

            // Now check if the attribute exists in the table
            foreach (string validationAttribute in validationAttributeList)
            {
                var fullyQualifiedValidationObject = MetadataHandling.GetFullyQualifiedDataObjectName(dataObjectName, teamConnection).FirstOrDefault();
                var localTable  = fullyQualifiedValidationObject.Value.Replace("[", "").Replace("]", "");
                var localSchema = fullyQualifiedValidationObject.Key.Replace("[", "").Replace("]", "");

                if (GlobalParameters.EnvironmentMode == EnvironmentModes.PhysicalMode)
                {
                    var conn = new SqlConnection
                    {
                        ConnectionString = teamConnection.CreateSqlServerConnectionString(false)
                    };
                    conn.Open();

                    // Execute the check
                    var cmd = new SqlCommand(
                        "SELECT CASE WHEN EXISTS ((SELECT * FROM INFORMATION_SCHEMA.COLUMNS " +
                        "WHERE " +
                        "[TABLE_NAME] = '" + localTable + "' AND " +
                        "[TABLE_SCHEMA] = '" + localSchema + "' AND " +
                        "[COLUMN_NAME] = '" + validationAttribute + "')) THEN 1 ELSE 0 END", conn);

                    var exists = (int)cmd.ExecuteScalar() == 1;

                    returnList.Add(new Tuple <string, string, bool>(localSchema + '.' + localTable, validationAttribute, exists));

                    conn.Close();
                }
            }

            // return the result of the test;
            return(returnList);
        }
Example #27
0
        /// <summary>
        /// This method ensures that an attribute object exists in the physical model against the catalog.
        /// </summary>
        /// <param name="validationObject"></param>
        /// <param name="validationAttribute"></param>
        /// <param name="teamConnection"></param>
        /// <returns></returns>
        internal static string ValidateAttributeExistencePhysical(string validationObject, string validationAttribute, TeamConnection teamConnection)
        {
            var returnExistenceEvaluation = "False";

            // Temporary fix to allow 'transformations', in this case hard-coded NULL values to be loaded.
            if (validationAttribute != "NULL")
            {
                var fullyQualifiedValidationObject = MetadataHandling.GetFullyQualifiedDataObjectName(validationObject, teamConnection).FirstOrDefault();
                var localTable  = fullyQualifiedValidationObject.Value.Replace("[", "").Replace("]", "");
                var localSchema = fullyQualifiedValidationObject.Key.Replace("[", "").Replace("]", "");

                var conn = new SqlConnection {
                    ConnectionString = teamConnection.CreateSqlServerConnectionString(false)
                };
                conn.Open();

                // Execute the check
                var cmd = new SqlCommand(
                    "SELECT CASE WHEN EXISTS ((SELECT * FROM INFORMATION_SCHEMA.COLUMNS " +
                    "WHERE " +
                    "[TABLE_NAME] = '" + localTable + "' AND " +
                    "[TABLE_SCHEMA] = '" + localSchema + "' AND " +
                    "[COLUMN_NAME] = '" + validationAttribute + "')) THEN 1 ELSE 0 END", conn);

                var exists = (int)cmd.ExecuteScalar() == 1;
                returnExistenceEvaluation = exists.ToString();

                conn.Close();
            }
            else
            {
                // Set True if NULL
                returnExistenceEvaluation = "True";
            }

            // return the result of the test;
            return(returnExistenceEvaluation);
        }
Example #28
0
        public void SaveConnection(object sender, EventArgs e)
        {
            if (_localConnection.ConnectionKey != "New")
            {
                // Save the connection to global memory (the shared variables across the application).
                // If the connection key (also the dictionary key) already exists, then update the values.
                // If the key does not exist then insert a new row in the connection dictionary.

                if (FormBase.TeamConfiguration.ConnectionDictionary.ContainsKey(_localConnection.ConnectionInternalId))
                {
                    FormBase.TeamConfiguration.ConnectionDictionary[_localConnection.ConnectionInternalId] = _localConnection;
                }
                else
                {
                    FormBase.TeamConfiguration.ConnectionDictionary.Add(_localConnection.ConnectionInternalId, _localConnection);
                }

                // Update the connection on disk

                if (!File.Exists(_connectionFileName))
                {
                    File.Create(_connectionFileName).Close();
                }

                // Check if the value already exists in the file.
                var jsonKeyLookup = new TeamConnection();

                TeamConnection[] jsonArray = JsonConvert.DeserializeObject <TeamConnection[]>(File.ReadAllText(_connectionFileName));

                // If the Json file already contains values (non-empty) then perform a key lookup.
                if (jsonArray != null)
                {
                    jsonKeyLookup = jsonArray.FirstOrDefault(obj => obj.ConnectionInternalId == _localConnection.ConnectionInternalId);
                }

                // If nothing yet exists in the file, the key lookup is NULL or "" then the record in question does not exist in the Json file and should be added.
                if (jsonArray == null || jsonKeyLookup == null || jsonKeyLookup.ConnectionKey == "")
                {
                    //  There was no key in the file for this connection, so it's new.
                    var list = new List <TeamConnection>();
                    if (jsonArray != null)
                    {
                        list = jsonArray.ToList();
                    }
                    list.Add(_localConnection);
                    jsonArray = list.ToArray();
                }
                else
                {
                    // Update the values in an existing JSON segment
                    jsonKeyLookup.ConnectionInternalId = _localConnection.ConnectionInternalId;
                    jsonKeyLookup.ConnectionName       = _localConnection.ConnectionName;
                    jsonKeyLookup.ConnectionKey        = _localConnection.ConnectionKey;
                    jsonKeyLookup.ConnectionType       = GetSelectedConnectionTypesRadioButtonFromForm();
                    jsonKeyLookup.ConnectionNotes      = _localConnection.ConnectionNotes;
                    jsonKeyLookup.DatabaseServer       = _localConnection.DatabaseServer;
                    jsonKeyLookup.FileConnection       = _localConnection.FileConnection;
                }

                try
                {
                    // Save the updated file to disk.
                    TeamUtility.CreateFileBackup(_connectionFileName);
                    string output = JsonConvert.SerializeObject(jsonArray, Formatting.Indented);
                    File.WriteAllText(_connectionFileName, output);

                    UpdateRichTextBoxInformation(
                        $"The connection {_localConnection.ConnectionKey} was saved to {_connectionFileName}. A backup was made in the Backups directory also.\r\n");
                }
                catch (Exception ex)
                {
                    GlobalParameters.TeamEventLog.Add(Event.CreateNewEvent(EventTypes.Error, $"An error occurred: {ex}"));
                }

                // The name of the tab page is passed back to the original control (the tab control).
                OnSaveConnection(this, new MyStringEventArgs(this.Name));
            }
            else
            {
                UpdateRichTextBoxInformation("Please update the connection information before saving. The 'new' profile is not meant to be saved.\r\n");
            }
        }
Example #29
0
        /// <summary>
        /// Constructor to instantiate a new Custom Tab Page.
        /// </summary>
        public CustomTabPageConnection(object input)
        {
            _localConnection = (TeamConnection)input;

            // Workaround to handle older config files that do not have this object yet.
            if (_localConnection.FileConnection == null)
            {
                TeamFileConnection connectionFile = new TeamFileConnection();
                connectionFile.FilePath         = @"<File Path>";
                connectionFile.FileName         = @"<File Name>";
                _localConnection.FileConnection = connectionFile;
            }

            //var inputNiceName = Regex.Replace(connectionName, "(\\B[A-Z])", " $1");

            #region Main Tab Page controls

            ToolTip toolTipConnections = new ToolTip();
            toolTipConnections.AutoPopDelay = 3000;

            // Base properties of the custom tab page
            Name                    = $"{_localConnection.ConnectionKey}";
            Text                    = _localConnection.ConnectionName;
            BackColor               = Color.Transparent;
            BorderStyle             = BorderStyle.None;
            UseVisualStyleBackColor = true;
            Size                    = new Size(1330, 601);
            AutoSizeMode            = AutoSizeMode.GrowOnly;
            AutoSize                = true;

            // Add Panel to facilitate docking
            var localPanel = new Panel();
            Controls.Add(localPanel);
            localPanel.Dock     = DockStyle.Fill;
            localPanel.AutoSize = true;
            localPanel.TabStop  = false;

            #region Database connection controls
            // Add ConnectionString TextBox
            _textBoxConnectionString = new TextBox();
            localPanel.Controls.Add(_textBoxConnectionString);
            _textBoxConnectionString.Anchor      = (AnchorStyles.Top | AnchorStyles.Left);
            _textBoxConnectionString.Location    = new Point(6, 212);
            _textBoxConnectionString.Size        = new Size(850, 21);
            _textBoxConnectionString.BorderStyle = BorderStyle.None;
            _textBoxConnectionString.BackColor   = Color.White;
            _textBoxConnectionString.Name        = $"textBoxConnectionString";
            _textBoxConnectionString.ReadOnly    = true;
            _textBoxConnectionString.TabStop     = false;

            // Add GroupBox for Database content
            _groupBoxDatabase = new GroupBox();
            localPanel.Controls.Add(_groupBoxDatabase);
            _groupBoxDatabase.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            _groupBoxDatabase.Location = new Point(6, 6);
            _groupBoxDatabase.Size     = new Size(502, 124);
            _groupBoxDatabase.Name     = $"groupBoxDatabaseName";
            _groupBoxDatabase.Text     = $"Database";
            _groupBoxDatabase.TabStop  = false;

            // Add Database Label
            var labelDatabase = new Label();
            _groupBoxDatabase.Controls.Add(labelDatabase);
            labelDatabase.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            labelDatabase.Location = new Point(6, 19);
            labelDatabase.Size     = new Size(160, 13);
            labelDatabase.Name     = $"labelDatabaseName";
            labelDatabase.Text     = $"Database name";
            labelDatabase.TabStop  = false;

            // Add Server Label
            var labelServer = new Label();
            _groupBoxDatabase.Controls.Add(labelServer);
            labelServer.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            labelServer.Location = new Point(6, 44);
            labelServer.Size     = new Size(160, 13);
            labelServer.Name     = $"labelDatabaseServerName";
            labelServer.Text     = $"Database server name";
            labelServer.TabStop  = false;

            // Add Port Label
            var labelPortNumber = new Label();
            _groupBoxDatabase.Controls.Add(labelPortNumber);
            labelPortNumber.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            labelPortNumber.Location = new Point(6, 69);
            labelPortNumber.Size     = new Size(160, 13);
            labelPortNumber.Name     = $"labelPortNumber";
            labelPortNumber.Text     = $"Database server port number";
            labelPortNumber.TabStop  = false;

            // Add Schema Label
            var labelSchema = new Label();
            _groupBoxDatabase.Controls.Add(labelSchema);
            labelSchema.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            labelSchema.Location = new Point(6, 94);
            labelSchema.Size     = new Size(160, 13);
            labelSchema.Name     = $"labelSchema";
            labelSchema.Text     = $"Schema";
            labelSchema.TabStop  = false;

            // Add Database TextBox
            _textBoxDatabase = new TextBox();
            _groupBoxDatabase.Controls.Add(_textBoxDatabase);
            _textBoxDatabase.Anchor       = (AnchorStyles.Top | AnchorStyles.Left);
            _textBoxDatabase.Location     = new Point(172, 16);
            _textBoxDatabase.Size         = new Size(317, 20);
            _textBoxDatabase.Name         = $"textBoxDatabaseName";
            _textBoxDatabase.Text         = _localConnection.DatabaseServer.DatabaseName;
            _textBoxDatabase.TextChanged += new EventHandler(UpdateConnectionString);
            _textBoxDatabase.TabIndex     = 1;

            // Add Server TextBox
            _textBoxServer = new TextBox();
            _groupBoxDatabase.Controls.Add(_textBoxServer);
            _textBoxServer.Anchor       = (AnchorStyles.Top | AnchorStyles.Left);
            _textBoxServer.Location     = new Point(172, 41);
            _textBoxServer.Size         = new Size(317, 20);
            _textBoxServer.Name         = $"textBoxServerName";
            _textBoxServer.Text         = _localConnection.DatabaseServer.ServerName;
            _textBoxServer.TextChanged += new EventHandler(UpdateConnectionString);
            _textBoxServer.TabIndex     = 2;

            // Add Port Number TextBox
            _textBoxPortNumber = new TextBox();
            _groupBoxDatabase.Controls.Add(_textBoxPortNumber);
            _textBoxPortNumber.Anchor       = (AnchorStyles.Top | AnchorStyles.Left);
            _textBoxPortNumber.Location     = new Point(172, 69);
            _textBoxPortNumber.Size         = new Size(317, 20);
            _textBoxPortNumber.Name         = $"textBoxPortNumber";
            _textBoxPortNumber.Text         = _localConnection.DatabaseServer.PortNumber;
            _textBoxPortNumber.TextChanged += new EventHandler(UpdateConnectionString);
            _textBoxPortNumber.TabIndex     = 3;
            toolTipConnections.SetToolTip(this._textBoxPortNumber, "Optional port number that can be used to connect to the database server.");

            // Add Schema TextBox
            _textBoxSchema = new TextBox();
            _groupBoxDatabase.Controls.Add(_textBoxSchema);
            _textBoxSchema.Anchor       = (AnchorStyles.Top | AnchorStyles.Left);
            _textBoxSchema.Location     = new Point(172, 94);
            _textBoxSchema.Size         = new Size(317, 20);
            _textBoxSchema.Name         = $"textBoxSchemaName";
            _textBoxSchema.Text         = _localConnection.DatabaseServer.SchemaName;
            _textBoxSchema.TextChanged += new EventHandler(UpdateConnectionString);
            _textBoxSchema.TabIndex     = 4;

            // Add GroupBox for Authentication content
            _groupBoxAuthentication = new GroupBox();
            localPanel.Controls.Add(_groupBoxAuthentication);
            _groupBoxAuthentication.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            _groupBoxAuthentication.Location = new Point(6, 136);
            _groupBoxAuthentication.Size     = new Size(140, 70);
            _groupBoxAuthentication.Name     = $"groupBoxAuthentication";
            _groupBoxAuthentication.Text     = $"Authentication";
            _groupBoxAuthentication.TabStop  = false;

            // Add RadioButton for Integrated Security
            _radioButtonIntegratedSecurity = new RadioButton();
            _groupBoxAuthentication.Controls.Add(_radioButtonIntegratedSecurity);
            _radioButtonIntegratedSecurity.Anchor          = (AnchorStyles.Top | AnchorStyles.Left);
            _radioButtonIntegratedSecurity.Location        = new Point(6, 19);
            _radioButtonIntegratedSecurity.Size            = new Size(106, 17);
            _radioButtonIntegratedSecurity.Name            = $"radioButtonIntegratedSecurity";
            _radioButtonIntegratedSecurity.Text            = $@"Integrated (SSPI)";
            _radioButtonIntegratedSecurity.Checked         = _localConnection.DatabaseServer.IntegratedSecuritySelectionEvaluation();
            _radioButtonIntegratedSecurity.CheckedChanged += (RadioButtonIntegratedSecurityCheckedChanged);
            _radioButtonIntegratedSecurity.TabIndex        = 5;

            // Add RadioButton for Named User
            _radioButtonNamedUserSecurity = new RadioButton();
            _groupBoxAuthentication.Controls.Add(_radioButtonNamedUserSecurity);
            _radioButtonNamedUserSecurity.Anchor          = (AnchorStyles.Top | AnchorStyles.Left);
            _radioButtonNamedUserSecurity.Location        = new Point(6, 42);
            _radioButtonNamedUserSecurity.Size            = new Size(84, 17);
            _radioButtonNamedUserSecurity.Name            = $"radioButtonNamedUserSecurity";
            _radioButtonNamedUserSecurity.Text            = $@"Named User details";
            _radioButtonNamedUserSecurity.Checked         = _localConnection.DatabaseServer.NamedUserSecuritySelectionEvaluation();
            _radioButtonNamedUserSecurity.CheckedChanged += (RadioButtonNamedUserCheckedChanged);
            _radioButtonNamedUserSecurity.TabIndex        = 6;

            // Add GroupBox for Named User content
            _groupBoxNamedUser = new GroupBox();
            localPanel.Controls.Add(_groupBoxNamedUser);
            _groupBoxNamedUser.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            _groupBoxNamedUser.Location = new Point(152, 136);
            _groupBoxNamedUser.Size     = new Size(356, 70);
            _groupBoxNamedUser.Name     = $"groupBoxNamedUser";
            _groupBoxNamedUser.Text     = $"Named User details";
            _groupBoxNamedUser.TabStop  = false;

            // Add Username Label
            var labelUserName = new Label();
            _groupBoxNamedUser.Controls.Add(labelUserName);
            labelUserName.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            labelUserName.Location = new Point(6, 19);
            labelUserName.Size     = new Size(55, 13);
            labelUserName.Name     = $"labelUserName";
            labelUserName.Text     = $"Username";
            labelUserName.TabStop  = false;

            // Add Password Label
            var labelPassword = new Label();
            _groupBoxNamedUser.Controls.Add(labelPassword);
            labelPassword.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            labelPassword.Location = new Point(6, 44);
            labelPassword.Size     = new Size(53, 13);
            labelPassword.Name     = $"labelPassword";
            labelPassword.Text     = $"Password";
            labelPassword.TabStop  = false;

            // Add Username TextBox
            _textboxUserName = new TextBox();
            _groupBoxNamedUser.Controls.Add(_textboxUserName);
            _textboxUserName.Anchor       = (AnchorStyles.Top | AnchorStyles.Left);
            _textboxUserName.Location     = new Point(67, 16);
            _textboxUserName.Size         = new Size(276, 20);
            _textboxUserName.Name         = $"textboxUserName";
            _textboxUserName.Text         = _localConnection.DatabaseServer.NamedUserName;
            _textboxUserName.TextChanged += UpdateConnectionString;
            _textboxUserName.TabIndex     = 7;

            // Add Password TextBox
            _textBoxPassword = new MaskedTextBox();
            _groupBoxNamedUser.Controls.Add(_textBoxPassword);
            _textBoxPassword.Anchor       = (AnchorStyles.Top | AnchorStyles.Left);
            _textBoxPassword.Location     = new Point(67, 41);
            _textBoxPassword.Size         = new Size(276, 20);
            _textBoxPassword.PasswordChar = '*';
            _textBoxPassword.Name         = $"textboxUserName";
            _textBoxPassword.Text         = _localConnection.DatabaseServer.NamedUserPassword;
            _textBoxPassword.TextChanged += new EventHandler(UpdateConnectionStringWithPassword);
            _textBoxPassword.TabIndex     = 8;
            #endregion


            // Add GroupBox for File Connection content
            _groupBoxFileConnection = new GroupBox();
            localPanel.Controls.Add(_groupBoxFileConnection);
            _groupBoxFileConnection.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            _groupBoxFileConnection.Location = new Point(6, 6);
            _groupBoxFileConnection.Size     = new Size(502, 124);
            _groupBoxFileConnection.Name     = $"groupBoxFileConnection";
            _groupBoxFileConnection.Text     = $"File";
            _groupBoxFileConnection.TabStop  = false;

            // Add File Path Label
            _labelFilePath = new Label();
            _groupBoxFileConnection.Controls.Add(_labelFilePath);
            _labelFilePath.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            _labelFilePath.Location = new Point(6, 19);
            _labelFilePath.Size     = new Size(100, 13);
            _labelFilePath.Name     = $"labelFilePath";
            _labelFilePath.Text     = $"File path";
            _labelFilePath.TabStop  = false;

            // Add File Name Label
            _labelFileName = new Label();
            _groupBoxFileConnection.Controls.Add(_labelFileName);
            _labelFileName.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            _labelFileName.Location = new Point(6, 44);
            _labelFileName.Size     = new Size(100, 13);
            _labelFileName.Name     = $"labelFileName";
            _labelFileName.Text     = $"File name";
            _labelFileName.TabStop  = false;

            // Add File Path TextBox
            _textBoxFilePath = new TextBox();
            _groupBoxFileConnection.Controls.Add(_textBoxFilePath);
            _textBoxFilePath.Anchor       = (AnchorStyles.Top | AnchorStyles.Left);
            _textBoxFilePath.Location     = new Point(122, 16);
            _textBoxFilePath.Size         = new Size(367, 20);
            _textBoxFilePath.Name         = $"textBoxFilePath";
            _textBoxFilePath.Text         = _localConnection.FileConnection.FilePath;
            _textBoxFilePath.TextChanged += (UpdateConnectionFilePath);
            _textBoxFilePath.TabIndex     = 1;

            // Add File Name TextBox
            _textBoxFileName = new TextBox();
            _groupBoxFileConnection.Controls.Add(_textBoxFileName);
            _textBoxFileName.Anchor       = (AnchorStyles.Top | AnchorStyles.Left);
            _textBoxFileName.Location     = new Point(122, 41);
            _textBoxFileName.Size         = new Size(367, 20);
            _textBoxFileName.Name         = $"textBoxFileName";
            _textBoxFileName.Text         = _localConnection.FileConnection.FileName;
            _textBoxFileName.TextChanged += (UpdateConnectionFileName);
            _textBoxFileName.TabIndex     = 2;

            #region Connection generic controls
            // Add GroupBox for Connection content
            var groupBoxConnection = new GroupBox();
            localPanel.Controls.Add(groupBoxConnection);
            groupBoxConnection.Anchor   = (AnchorStyles.Top | AnchorStyles.Left);
            groupBoxConnection.Location = new Point(516, 6);
            groupBoxConnection.Size     = new Size(502, 200);
            groupBoxConnection.Name     = $"groupBoxConnection";
            groupBoxConnection.Text     = $"Connection";
            groupBoxConnection.TabStop  = false;

            // Add Connection Key Label
            var labelConnectionKey = new Label();
            groupBoxConnection.Controls.Add(labelConnectionKey);
            //labelConnectionKey.Anchor = (AnchorStyles.Top | AnchorStyles.Right);
            labelConnectionKey.Location = new Point(6, 19);
            labelConnectionKey.Size     = new Size(160, 13);
            labelConnectionKey.Name     = $"labelConnectionKey";
            labelConnectionKey.Text     = $"Connection key";
            //labelConnectionKey.TextChanged += new EventHandler(ManageKeyNameChange);
            labelConnectionKey.TabStop = false;

            // Add Connection Name Label
            var labelConnectionName = new Label();
            groupBoxConnection.Controls.Add(labelConnectionName);
            //labelConnectionName.Anchor = (AnchorStyles.Top | AnchorStyles.Right);
            labelConnectionName.Location = new Point(6, 44);
            labelConnectionName.Size     = new Size(160, 13);
            labelConnectionName.Name     = $"labelConnectionName";
            labelConnectionName.Text     = $"Connection name";
            labelConnectionName.TabStop  = false;

            // Add Connection Type Label
            var labelConnectionType = new Label();
            groupBoxConnection.Controls.Add(labelConnectionType);
            labelConnectionType.Location = new Point(6, 69);
            labelConnectionType.Size     = new Size(160, 13);
            labelConnectionType.Name     = $"labelConnectionType";
            labelConnectionType.Text     = $"Connection type";
            labelConnectionType.TabStop  = false;

            // Add Connection Notes Label
            var labelConnectionNotes = new Label();
            groupBoxConnection.Controls.Add(labelConnectionNotes);
            labelConnectionNotes.Location = new Point(6, 119);
            labelConnectionNotes.Size     = new Size(160, 13);
            labelConnectionNotes.Name     = $"labelConnectionNotes";
            labelConnectionNotes.Text     = $"Connection notes";
            labelConnectionNotes.TabStop  = false;

            // Add Connection Key TextBox
            _textBoxConnectionKey = new TextBox();
            groupBoxConnection.Controls.Add(_textBoxConnectionKey);
            _textBoxConnectionKey.Location     = new Point(172, 16);
            _textBoxConnectionKey.Size         = new Size(317, 20);
            _textBoxConnectionKey.Name         = $"textBoxServerName";
            _textBoxConnectionKey.Text         = _localConnection.ConnectionKey;
            _textBoxConnectionKey.TextChanged += (UpdateConnectionKey);
            _textBoxConnectionKey.TabIndex     = 50;
            toolTipConnections.SetToolTip(this._textBoxConnectionKey, "The Connection Key is a short and easily recognisable reference for the connection that can be used within TEAM.");


            // Add Connection Name TextBox
            _textBoxConnectionName = new TextBox();
            groupBoxConnection.Controls.Add(_textBoxConnectionName);
            _textBoxConnectionName.Location     = new Point(172, 41);
            _textBoxConnectionName.Size         = new Size(317, 20);
            _textBoxConnectionName.Name         = $"textBoxConnectionName";
            _textBoxConnectionName.Text         = _localConnection.ConnectionName;
            _textBoxConnectionName.TextChanged += (UpdateConnectionName);
            _textBoxConnectionName.TabIndex     = 51;

            // Add Connection Type Radiobutton for Database
            _radioButtonDatabase = new RadioButton();
            groupBoxConnection.Controls.Add(_radioButtonDatabase);
            _radioButtonDatabase.Location = new Point(172, 66);
            //_textBoxConnectionName.Size = new Size(317, 20);
            _radioButtonDatabase.Name            = $"radioButtonDatabase";
            _radioButtonDatabase.Text            = ConnectionTypes.Database.ToString();
            _radioButtonDatabase.CheckedChanged += (UpdateConnectionTypeControls);
            _radioButtonDatabase.TabIndex        = 52;

            // Add Connection Type Radiobutton for File
            _radioButtonFile = new RadioButton();
            groupBoxConnection.Controls.Add(_radioButtonFile);
            _radioButtonFile.Location = new Point(172, 88);
            //_textBoxConnectionName.Size = new Size(317, 20);
            _radioButtonFile.Name            = $"radioButtonFile";
            _radioButtonFile.Text            = ConnectionTypes.File.ToString();
            _radioButtonFile.CheckedChanged += (UpdateConnectionTypeControls);
            _radioButtonFile.TabIndex        = 53;

            SetConnectionTypesRadioButton();

            // Add Connection Notes Panel
            var panelConnectionNotes = new Panel();
            groupBoxConnection.Controls.Add(panelConnectionNotes);
            panelConnectionNotes.Location    = new Point(172, 119);
            panelConnectionNotes.Size        = new Size(317, 71);
            panelConnectionNotes.Name        = $"panelConnectionNotes";
            panelConnectionNotes.BorderStyle = BorderStyle.FixedSingle;

            // Add Connection Notes RichTextBox
            _richTextBoxConnectionNotes          = new RichTextBox();
            _richTextBoxConnectionNotes.TabIndex = 54;
            panelConnectionNotes.Controls.Add(_richTextBoxConnectionNotes);
            _richTextBoxConnectionNotes.Name         = $"richTextBoxConnectionNotes";
            _richTextBoxConnectionNotes.BorderStyle  = BorderStyle.None;
            _richTextBoxConnectionNotes.Dock         = DockStyle.Fill;
            _richTextBoxConnectionNotes.Text         = _localConnection.ConnectionNotes;
            _richTextBoxConnectionNotes.TextChanged += (UpdateConnectionNotes);
            toolTipConnections.SetToolTip(this._richTextBoxConnectionNotes, "Free format notes to provide additional information about the connection.");
            #endregion



            // Add Save Button
            Button saveButton = new Button();
            localPanel.Controls.Add(saveButton);
            saveButton.Anchor   = (AnchorStyles.Bottom | AnchorStyles.Left);
            saveButton.Location = new Point(6, 555);
            saveButton.Size     = new Size(120, 40);
            saveButton.Name     = $"saveButton";
            saveButton.Text     = $"Save Connection";
            saveButton.Click   += (SaveConnection);
            saveButton.TabIndex = 60;

            // Add Delete Button
            Button deleteButton = new Button();
            localPanel.Controls.Add(deleteButton);
            deleteButton.Anchor   = (AnchorStyles.Bottom | AnchorStyles.Left);
            deleteButton.Location = new Point(132, 555);
            deleteButton.Size     = new Size(120, 40);
            deleteButton.Name     = $"deleteButton";
            deleteButton.Text     = $"Delete Connection";
            deleteButton.Click   += (DeleteConnection);
            deleteButton.TabIndex = 70;

            // Add test Button
            Button testButton = new Button();
            localPanel.Controls.Add(testButton);
            testButton.Anchor   = (AnchorStyles.Bottom | AnchorStyles.Left);
            testButton.Location = new Point(258, 555);
            testButton.Size     = new Size(120, 40);
            testButton.Name     = $"testButton";
            testButton.Text     = $"Test Connection";
            testButton.Click   += (TestConnection);
            testButton.TabIndex = 80;



            #endregion

            #region Constructor Methods

            // Prevention of double hitting of some event handlers
            this.StartUpIndicator = false;

            // Retrieve the values from memory
            bool localSSPI  = _localConnection.DatabaseServer.IntegratedSecuritySelectionEvaluation();
            bool localNamed = _localConnection.DatabaseServer.NamedUserSecuritySelectionEvaluation();

            // Display the connection string results
            _textBoxConnectionString.Text = _localConnection.CreateSqlServerConnectionString(true);

            if (_radioButtonIntegratedSecurity.Checked)
            {
                _groupBoxNamedUser.Visible = false;
            }

            #endregion
        }
Example #30
0
        /// <summary>
        /// Check if the last tab rectangle contains the mouse clicked point, then insert a tab before the last tab.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControlConnections_MouseDown(object sender, MouseEventArgs e)
        {
            var lastIndex = tabControlConnections.TabCount - 1;

            if (tabControlConnections.GetTabRect(lastIndex).Contains(e.Location))
            {
                //tabControlConnections.TabPages.Insert(lastIndex, "New Tab");
                TeamConnection connectionProfile = new TeamConnection();
                connectionProfile.ConnectionInternalId = Utility.CreateMd5(new[] { Utility.GetRandomString(100) }, " % $@");
                connectionProfile.ConnectionName       = "New connection";
                connectionProfile.ConnectionKey        = "New";
                connectionProfile.ConnectionType       = ConnectionTypes.Database;

                TeamDatabaseConnection connectionDatabase = new TeamDatabaseConnection();
                connectionDatabase.SchemaName         = "<Schema Name>";
                connectionDatabase.ServerName         = "<Server Name>";
                connectionDatabase.DatabaseName       = "<Database Name>";
                connectionDatabase.NamedUserName      = "******";
                connectionDatabase.NamedUserPassword  = "******";
                connectionDatabase.authenticationType = ServerAuthenticationTypes.NamedUser;

                TeamFileConnection connectionFile = new TeamFileConnection();
                connectionFile.FilePath = @"<File Path>";
                connectionFile.FileName = @"<File Name>";

                connectionProfile.DatabaseServer = connectionDatabase;
                connectionProfile.FileConnection = connectionFile;


                //localCustomTabPage.OnChangeMainText += UpdateMainInformationTextBox;
                //localCustomTabPage.OnClearMainText += (ClearMainInformationTextBox);

                bool newTabExists = false;
                foreach (TabPage customTabPage in tabControlConnections.TabPages)
                {
                    if (customTabPage.Name == "New")
                    {
                        newTabExists = true;
                    }
                    else
                    {
                        // Do nothing
                    }
                }

                if (newTabExists == false)
                {
                    // Create a new tab page using the connection profile (a TeamConnection class object) as input.
                    CustomTabPageConnection localCustomTabPage = new CustomTabPageConnection(connectionProfile);
                    localCustomTabPage.OnDeleteConnection += DeleteConnection;
                    localCustomTabPage.OnChangeMainText   += UpdateMainInformationTextBox;
                    localCustomTabPage.OnSaveConnection   += SaveConnection;
                    tabControlConnections.TabPages.Insert(lastIndex, localCustomTabPage);
                    tabControlConnections.SelectedIndex = lastIndex;

                    GlobalParameters.TeamEventLog.Add(Event.CreateNewEvent(EventTypes.Information, $"A new connection was created."));
                }
                else
                {
                    richTextBoxInformation.AppendText("There is already a 'new connection' tab open. Please close or save this first.\r\n");
                }
            }
        }