Prep Document PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document appears to be a set of notes or a cheat sheet for a computer science course, possibly CPSC 275. It covers topics like database creation with .NET, object-oriented programming (OOP) and C# programming concepts. It contains code examples and links to resources.
Full Transcript
🕯️ PREP Created @November 27, 2024 12:04 PM Class CPSC 275 Reviewed Resources https://quizlet.com/977387918/final-syntax-flash-cards/?i=4ym8m8&x=1jqt Create database, add tables in.NET Framework apps - Visual Studio (Windows...
🕯️ PREP Created @November 27, 2024 12:04 PM Class CPSC 275 Reviewed Resources https://quizlet.com/977387918/final-syntax-flash-cards/?i=4ym8m8&x=1jqt Create database, add tables in.NET Framework apps - Visual Studio (Windows) Create a database with tables and foreign keys in a.NET Framework application by using Table Designer in Visual Studio. https://learn.microsoft.com/en-us/visualstudio/data-tools/create-a-sql-database-by-u sing-a-designer?view=vs-2022 Polymorphism - C# Learn about polymorphism, a key concept in object-oriented programming languages like C#, which describes the relationship between base and derived classes. https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-orien ted/polymorphism OOP for Dummies What is OOP? https://trujillo9616.medium.com/oop-for-dummies-3e6007c8e7f4 Cheat Sheet //Add a page header MS Excel ws.PageSetup.CenterHeader = "Player Report"; // Centered header text workbook.SaveAs(Path.Combine(Application.StartupPath, "Report.xlsx")); / for (int i = 0; i < dataGridView.Columns.Count; i++) { worksheet1.Cells[1, i + 1] = dataGridView.Columns[i].HeaderText; } -------------------------------------------------------------------------- //Add Header MS Word PREP 1 foreach (Word.Section section in document.Sections) { // Access the header range Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wd headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wd } // Add Footer MS Word foreach (Word.Section section in document.Sections) { // Access the footer range Word.Range footerRange = section.Footers[Word.WdHeaderFooterIndex.wd footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldPage); / } string savePath = Path.Combine(System.Windows.Forms.Application.Startup document.SaveAs2(savePath); //Save --------------------------------------------------------------------------- //WRITING TO A TXT FILE IN C# string fileName = "Report.txt"; string dirPath = Application.StartupPath; string finalPath = Path.Combine(dirPath, fileName); StreamWriter sw = new StreamWriter(finalPath,true); foreach (var player in playerForm.players) { sw.WriteLine("ID: " + player.Id); sw.WriteLine("First Name: " + player.FirstName); } } sw.Close(); --------------------------------------------------------------------------- //READING A TXT FILE IN C# string fileName = "Report.txt"; string directoryPath = Application.StartupPath; private void ReadTextFile(){ string filepath = Path.Combine(directoryPath, fileName); StreamReader sr = new StreamReader(filepath); richTextBox.Text = sr.ReadToEnd(); sr.Close(); } --------------------------------------------------------------------------- //Connnection String string connectionString = @"server=(localdb)\MSSQLLocalDB;database=Dominica private void btnAddStudent_Click(object sender, EventArgs e){ AddStudentForm addStudentForm = new AddStudentForm(); if (addStudentForm.ShowDialog() == DialogResult.OK) PREP 2 { Student student = new Student(addStudentForm.ID, addStudent addStudentForm.LastName, addStudentForm.Major); AddStudentToDb(student); } } --------------------------------------------------------------------------- import pandas as pd # Import the pandas library for data manipulation and analysis #Load the CSV file into a data frame df = pd.read_csv('employees.csv') #print the dataframe print(df) #print first 10 rows of df print(df.head(10)) #print last 10 rows print(df.tail(10)) #print column names print(df.columns) #print rows 0 to 8, select only "First Name," "Salary,", and "Team" columns print(df[['First Name', 'Salary', 'Team']][0:9]) #print the data in row 1, column 3 print(df.iloc[1,3]) #Filter rows where "Team" column has value "Engineering" df_filtered = df.loc[df['Team'] == 'Engineering'] print(df_filtered) # Print a statistical summary of the DataFrame's numeric columns print(df.describe()) df.to_csv('modified.csv') # Save the modified DataFrame to a new CSV file na 'modified.csv' --------------------------------------------------------------------------- import numpy as np arr = np.array([1, 2, 3]) arr = np.array([1, 2, 3, 4, 5]) print(arr) # Access the first element (1) print(arr[1:3]) # Access elements from index 1 to 2 (2, 3) arr = np.array([1, 2, 3, 4, 5, 6]) # Reshape to a 2x3 array reshaped_arr = arr.reshape(2, 3) Exam II using Excel = Microsoft.Office.Interop.Excel; //Reference PREP 3 namespace ReportGenerator { public partial class Form1 : Form { List cars = new List(); Car car1 = new Car { Make = "Honda", Model = "Civic", Year = 2016, C Car car2 = new Car { Make = "Toyota", Model = "Prius", Year = 2014, Car car3 = new Car { Make = "Lexus", Model = "ES350", Year = 2012, C Car car4 = new Car { Make = "Acura", Model = "MDX", Year = 2018, Col Car car5 = new Car { Make = "BMW", Model = "330", Year = 2019, Colo Car car6 = new Car { Make = "Audi", Model = "A4", Year = 2008, Colo Car car7 = new Car { Make = "Mercedes-Benz", Model = "S550", Year = Car car8 = new Car { Make = "Nissan", Model = "Altima", Year = 2021 Car car9 = new Car { Make = "Mazda", Model = "CX-50", Year = 2022, C Car car10 = new Car { Make = "Hyundai", Model = "SantaFe", Year = 20 public Form1() { InitializeComponent(); cars.Add(car1); cars.Add(car2); cars.Add(car3); cars.Add(car4); cars.Add(car5); cars.Add(car6); cars.Add(car7); cars.Add(car8); cars.Add(car9); cars.Add(car10); dgvReport.DataSource = cars; } private void btnGenerateReport_Click(object sender, EventArgs e) //T { Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Add(); Excel.Worksheet worksheet = workbook.Sheets; worksheet.Name = "Car Report"; // Auto-fit columns worksheet.Columns.AutoFit(); // Make Excel visible excelApp.Visible = true; PREP 4 // Export headers for (int i = 0; i < dgvReport.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dgvReport.Columns[i].HeaderText worksheet.Cells[1, i + 1].Font.Bold = true; //Setting to Bol } // Export data for (int i = 0; i < dgvReport.Rows.Count; i++) //Loop for the { //DataGridViewRow row = dvgReport.Rows[i]; for (int j = 0; j < dgvReport.Columns.Count; j++) //Loop fo { var cellValue = dgvReport.Rows[i].Cells[j].Value; worksheet.Cells[i + 2, j + 1] = cellValue; worksheet.Range["A5:F5"].Font.Color = Color.Red; worksheet.Range["A4:F4"].Font.Color = Color.Gray; worksheet.Range["A6:F6"].Font.Color = Color.Yellow; worksheet.Range["A7:F7"].Font.Color = Color.Green; worksheet.Range["A8:F8"].Font.Color = Color.Brown; worksheet.Range["A9:F9"].Font.Color = Color.Gray; worksheet.Range["A10:F10"].Font.Color = Color.Green; worksheet.Range["A11:F11"].Font.Color = Color.Gray; } } } } } Exam2.docx MUST KNOW: Make a basic windows form application Instructions.docx PREP 5 Answer namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // GPA variables double gpa1 = 0.00; double gpa2 = 0.00; double gpa3 = 0.00; double gpa4 = 0.00; // SubmitButton click handler private void btnSubmit_Click(object sender, EventArgs e) { string fname = FirstNameBox.Text; string lname = LastNameBox.Text; string grade1 = tbxCourse1.Text; string grade2 = tbxCourse2.Text; string grade3 = tbxCourse3.Text; string grade4 = tbxCourse4.Text; // Convert grades to GPA, passing the users input as a paramete gpa1 = ConvertGradeToGpa(grade1); //calling the switch method gpa2 = ConvertGradeToGpa(grade2); gpa3 = ConvertGradeToGpa(grade3); gpa4 = ConvertGradeToGpa(grade4); // Calculate final GPA double totalCredits = 3 + 3 + 4 + 4; // Total credit hours double totalGradePoints = (gpa1 * 3) + (gpa2 * 3) + (gpa3 * 4) + double finalGPA = totalGradePoints / totalCredits; //Calculatio //Displaying the result lblSubmit.Text = "Hello " + fname + " " + lname + ", your GPA af } // Method to convert grade to GPA private double ConvertGradeToGpa(string grade) //Conversion of the PREP 6 { grade = grade.ToUpper(); //converts to uppercase so that the use switch (grade) { case "A": return 4.00; case "A-": return 3.67; case "B+": return 3.33; case "B": return 3.00; case "B-": return 2.67; case "C+": return 2.33; case "C": return 2.00; case "C-": return 1.67; case "F": return 0.00; default: return 0.00; } } } Make a basic C# to MS Word application Answer using Word = Microsoft.Office.Interop.Word; //Reference using Microsoft.Office.Interop.Word; //Reference private void CreateWordDocument() { Word.Application wordApp = new Word.Application(); //Opens Word Word.Document document = wordApp.Documents.Add(); //Opens Document //wordApp.Visible = true; PREP 7 //Implement this so that the user can save on its own, other wise itll Word.Paragraph para = document.Content.Paragraphs.Add(); //Adding a new para.Range.Text = "Title of Document"; //Changing text para.Range.Font.Size = 16; //Changing Font Size para.Range.Font.Bold = 1; //Changing Boldness para.Range.Font.Name = "Times New Roman"; //Changing Font para.Range.Font.Color = WdColor.wdColorDarkBlue; //Changing Color para.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //Al para.Range.InsertParagraphAfter();//Adding a paragraph space at the end string savePath = Path.Combine(System.Windows.Forms.Application.Startup document.SaveAs2(savePath); //Save document.Close(); //Close Document wordapp.Quit(); //Close Word } Make a basic C# to MS Excel application Answer using Excel = Microsoft.Office.Interop.Excel; //Reference //Or using Microsoft.Office.Interop.Excel; private void CreateExcelDocument() { Excel.Application excelApp = new Excel.Application(); //Open Excel Excel.Workbook workbook = excelApp.Workbooks.Add(); //Open Book //excelApp.Visible = true; //Implement this so that the user can save on its own, other wise itll sav Excel.Worksheet ws = workbook.Worksheets; //New Sheet ws.Cells[1, 1] = "Nombre"; //ws.Cells[row, column]: Fills specific cells in the worksheet with data. ws.Cells[1, 2] = "Posición"; ws.Cells[2, 1] = "Pedri"; ws.Cells[2, 2] = "Mediocampista"; //Formatting the font size ws.Range["A1", "B1"].Font.Size = 17; //Formatting font color ws.Range["A1:B1"].Font.Color = Color.Red; PREP 8 ws.Cells[1, 1] = "Row 1, Column 1"; ws.Cells[1, 2] = "Row 1, Column 2"; ws.Cells[1, 3] = "Row 1, Column 3"; workbook.SaveAs(Path.Combine(Application.StartupPath, "Report.xlsx")); //S workbook.Close(); //Close Book excelApp.Quit(); //Close Excel } What Happens in the Sheet: This code is filling in data in the first two rows and two columns: A (Column 1) B (Column 2) Nombre Posición Pedri Mediocampista Breakdown: ws.Cells[1, 1] = "Nombre"; Fills the cell at row 1, column 1 (A1) with the text "Nombre". ws.Cells[1, 2] = "Posición"; Fills the cell at row 1, column 2 (B1) with the text "Posición". ws.Cells[2, 1] = "Pedri"; Fills the cell at row 2, column 1 (A2) with the text "Pedri". ws.Cells[2, 2] = "Mediocampista"; Fills the cell at row 2, column 2 (B2) with the text "Mediocampista". PREP 9 Connect to a SQL Data Base Answer //Connnection String string connectionString = @"server=(localdb)\MSSQLLocalDB;database=Dominica //Add to DataBase public void AddStudentToDb(Student student)//Pass Parameters PREP 10 { using(SqlConnection connection = new SqlConnection(connectionString)) connection.Open();//Open the connection string insertionQueryStatement = "INSERT INTO dbo.Student(Id, Fir using(SqlCommand command = new SqlCommand(insertionQueryStateme //Implement a SQLCOMMAND statment //Pass in the connection plus the, statment as a parameter command.AddWithValue("@Id", student.Id);//Add command.AddWithValue("@FirstName", student.FirstName); command.AddWithValue("@LastName", student.LastName); command.AddWithValue("@Major", student.Major); command.ExecuteNonQuery();//Excecute NON-Query Statement } } MessageBox.Show("Successfully saved!");//Message Box } -------------------------------------------------------------------------- private void btnAddStudent_Click(object sender, EventArgs e) { AddStudentForm addStudentForm = new AddStudentForm(); if (addStudentForm.ShowDialog() == DialogResult.OK) { Student student = new Student(addStudentForm.ID, addStudent addStudentForm.LastName, addStudentForm.Major); AddStudentToDb(student); } } How do you create a new Database in VS? Answer Here are simple instructions to create a new SQL Server database in Visual Studio: 1. Open Visual Studio. 2. Open Server Explorer: Go to View > Server Explorer. 3. Connect to SQL Server: Right-click Data Connections in Server Explorer. Choose Add Connection. PREP 11 Select Microsoft SQL Server and click OK. Enter server details (e.g., (localdb)\MSSQLLocalDB for local SQL Server) and click Connect. 4. Create a New Database: Right-click Databases under the server in Server Explorer. Select New Database. Enter a name for your database and click OK. How do you create a SQL Table in VS? Answer 1. Database (Click) 2. Table (Right-Click) → Create New Table (Click) 3. Enter the same Information that you are inputting from the user 4. Update (Click the Arrow) Display SQL Data Base Table to DGV Answer PREP 12 //View from DataBase private void btnViewStudents_Click(object sender, EventArgs e) { using(SqlConnection connection = new SqlConnection(connectionString))//O { connection.Open(); //OPEN A CONNECTION SqlDataAdapter sql = new SqlDataAdapter("SELECT * FROM dbo.Student", c DataTable data = new DataTable();//OPEN A DATATABLE OBJECT sql.Fill(data);//FILL DataGridView.DataSource = data;//UPDATE THE DISPLAY } } Understand python syntax Answer import math import tkinter as tk window = tk.Tk() #tk.E = East (right), tk.W = West (left), tk.N = North (top), tk.S = South #TITLE OF THE UI lblTitle = tk.Label( text = "Projectile Estimator", #Changes text bg = "white", #background color fg = "black", #text color height = 2, #Changes height font = ("Arial", 14, "bold"), #Changes font / boldness ) lblTitle.grid(column = 0, row = 0, columnspan = 3, stick = tk.W + tk.E) #LABELS lblVelocity = tk.Label(text = "Velocity (m/s): ") lblVelocity.grid(column = 0, row = 1, stick = tk.E) #INPUT FIELDS txtVelocity = tk.Entry() txtVelocity.grid(column = 1, row = 1, stick = tk.W) #CALCULATE BUTTON btnCalculate = tk.Button(text = "Calculate Distance", command = calculate) # PREP 13 btnCalculate.grid(column = 0, row = 3, columnspan = 2, stick = tk.W + tk.E) #Calculate Distance Method def calculate(): velocity = float(txtVelocity.get()) #gets the velocity input angle = float(txtAngle.get()) #gets the angle input angle_in_radians = angle * (math.pi / 180) #converts into radians distance = (velocity ** 2) * math.sin(2 * angle_in_radians) / 9.8 #form lblTotal["text"] = f"Distance traveled: {distance}" #updating label --------------------------------------------------------------------------- import pandas as pd # Import the pandas library for data manipulation and a #Load the CSV file into a data frame df = pd.read_csv('employees.csv') #print the dataframe print(df) #print first 10 rows of df print(df.head(10)) #print last 10 rows print(df.tail(10)) #print column names print(df.columns) #print rows 0 to 8, select only "First Name," "Salary,", and "Team" columns print(df[['First Name', 'Salary', 'Team']][0:9]) #print the data in row 1, column 3 print(df.iloc[1,3]) #Filter rows where "Team" column has value "Engineering" df_filtered = df.loc[df['Team'] == 'Engineering'] print(df_filtered) # Print a statistical summary of the DataFrame's numeric columns print(df.describe()) df.to_csv('modified.csv') # Save the modified DataFrame to a new CSV file na 'modified.csv' --------------------------------------------------------------------------- import numpy as np arr = np.array([1, 2, 3]) arr = np.array([1, 2, 3, 4, 5]) print(arr) # Access the first element (1) print(arr[1:3]) # Access elements from index 1 to 2 (2, 3) arr = np.array([1, 2, 3, 4, 5, 6]) # Reshape to a 2x3 array reshaped_arr = arr.reshape(2, 3) PREP 14 Understand GitHub Answer Here are the steps to connect Visual Studio to GitHub: 1. Install Git: Download and install Git from git-scm.com. 2. Sign in to GitHub in Visual Studio: Open Visual Studio. Go to Tools > Options > Source Control > Git Global Settings. Sign in to your GitHub account. 3. Clone a Repository: Go to File > Clone Repository. Choose GitHub and sign in if prompted. Select a repository or enter the URL, and click Clone. 4. Create a New Repository: Go to File > Add to Source Control. Choose Git, then go to Team Explorer > Sync > Publish to GitHub. 5. Commit and Push Changes: In Team Explorer, go to Changes, write a commit message, and click Commit All. Click Sync and then Push to send changes to GitHub. 6. Pull Changes: In Team Explorer, go to Sync, then click Pull to fetch the latest changes from GitHub. That's it! You'll now be connected to GitHub in Visual Studio. 1. git pull What it does: Downloads changes from a remote repository (e.g., on GitHub or GitLab) and integrates them into your current branch. Details: It’s essentially a combination of two commands: 1. git fetch (to download changes) 2. git merge (to merge the downloaded changes into your branch) Use case: You want to update your local branch with the latest changes from a remote branch. PREP 15 2. git push What it does: Uploads your committed changes from your local repository to a remote repository. Details: You need to have permissions to push to the remote repository. It pushes changes from your current branch to the corresponding branch on the remote repository. Use case: After committing your changes locally, you use git push to share them with others or back them up. 3. git fetch What it does: Downloads changes (commits, branches, and tags) from a remote repository without merging them into your local branch. Details: It updates your local copy of the remote repository’s state (the origin ), which you can view using commands like git status or git log. Use case: You want to see what changes are available on the remote without affecting your current branch. 4. git commit What it does: Creates a new commit in your local repository, recording changes you’ve staged. Details: A commit is like a snapshot of your code at a specific point in time. You must provide a meaningful message describing the changes. Use case: You’ve made some changes and staged them with git add. Now, you want to save these changes locally in your Git history. Git Terminal Commands git - - version →Checks the version that of git that exists git checkout ExternalData_Test → checks out the TestBranch git diff ExternalData_Test master PREP 16 → shows the difference between the two branches git add ExternalData/Form1.cs → stages the file Form1.cs located in the ExternalData directory git commit -m → This creates a commit with the message "Add new feature to process user input". git checkout master → checks out the master branch git merge ExternalData_Test → merges the test branch with the master branch PREP 17