diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..da064ab --- /dev/null +++ b/.gitignore @@ -0,0 +1,253 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +ProC#6.pdf diff --git a/Appendix_A/AutoLotDAL2/AutoLotDAL2.csproj b/Appendix_A/AutoLotDAL2/AutoLotDAL2.csproj new file mode 100644 index 0000000..6864119 --- /dev/null +++ b/Appendix_A/AutoLotDAL2/AutoLotDAL2.csproj @@ -0,0 +1,57 @@ + + + + + Debug + AnyCPU + {0447CD8F-EE61-425D-A04F-F56468C8890A} + Library + Properties + AutoLotDAL2 + AutoLotDAL2 + v4.6 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL2/AutoLotDAL2.sln b/Appendix_A/AutoLotDAL2/AutoLotDAL2.sln new file mode 100644 index 0000000..86e2ffc --- /dev/null +++ b/Appendix_A/AutoLotDAL2/AutoLotDAL2.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL2", "AutoLotDAL2.csproj", "{0447CD8F-EE61-425D-A04F-F56468C8890A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0447CD8F-EE61-425D-A04F-F56468C8890A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0447CD8F-EE61-425D-A04F-F56468C8890A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0447CD8F-EE61-425D-A04F-F56468C8890A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0447CD8F-EE61-425D-A04F-F56468C8890A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/AutoLotDAL2/ConnectedLayer/InventoryDAL.cs b/Appendix_A/AutoLotDAL2/ConnectedLayer/InventoryDAL.cs new file mode 100644 index 0000000..88379e2 --- /dev/null +++ b/Appendix_A/AutoLotDAL2/ConnectedLayer/InventoryDAL.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using AutoLotDAL2.Models; + +namespace AutoLotDAL2.ConnectedLayer +{ + public class InventoryDAL + { + // This member will be used by all methods. + private SqlConnection _sqlConnection = null; + public void OpenConnection(string connectionString) + { + _sqlConnection = new SqlConnection { ConnectionString = connectionString }; + _sqlConnection.Open(); + } + + public void CloseConnection() + { + _sqlConnection.Close(); + } + //public void InsertAuto(string color, string make, string petName) + //{ + // // Format and execute SQL statement. + // string sql = "Insert Into Inventory" + + // $"(Make, Color, PetName) Values ('{make}', '{color}', '{petName}')"; + + // // Execute using our connection. + // using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + // { + // command.ExecuteNonQuery(); + // } + //} + public void InsertAuto(NewCar car) + { + // Format and execute SQL statement. + string sql = "Insert Into Inventory (Make, Color, PetName) Values" + + $"('{car.Make}', '{car.Color}', '{car.PetName}')"; + + // Execute using our connection. + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + command.ExecuteNonQuery(); + } + } + public void InsertAuto(string color, string make, string petName) + { + // Note the "placeholders" in the SQL query. + string sql = "Insert Into Inventory" + + "(Make, Color, PetName) Values" + + "(@Make, @Color, @PetName)"; + + // This command will have internal parameters. + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + // Fill params collection. + SqlParameter parameter = new SqlParameter + { + ParameterName = "@Make", + Value = make, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + parameter = new SqlParameter + { + ParameterName = "@Color", + Value = color, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + parameter = new SqlParameter + { + ParameterName = "@PetName", + Value = petName, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + command.ExecuteNonQuery(); + } + } + + public void DeleteCar(int id) + { + // Get ID of car to delete, then do so. + string sql = $"Delete from Inventory where CarID = '{id}'"; + using (SqlCommand cmd = new SqlCommand(sql, _sqlConnection)) + { + try + { + cmd.ExecuteNonQuery(); + } + catch (SqlException ex) + { + Exception error = new Exception("Sorry! That car is on order!", ex); + throw error; + } + } + } + public void UpdateCarPetName(int id, string newPetName) + { + // Get ID of car to modify and new pet name. + string sql = $"Update Inventory Set PetName = '{newPetName}' Where CarID = '{id}'"; + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + command.ExecuteNonQuery(); + } + } + public List GetAllInventoryAsList() + { + // This will hold the records. + List inv = new List(); + + // Prep command object. + string sql = "Select * From Inventory"; + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + SqlDataReader dataReader = command.ExecuteReader(); + while (dataReader.Read()) + { + inv.Add(new NewCar + { + CarID = (int)dataReader["CarID"], + Color = (string)dataReader["Color"], + Make = (string)dataReader["Make"], + PetName = (string)dataReader["PetName"] + }); + } + dataReader.Close(); + } + return inv; + } + public DataTable GetAllInventoryAsDataTable() + { + // This will hold the records. + DataTable dataTable = new DataTable(); + + // Prep command object. + string sql = "Select * From Inventory"; + using (SqlCommand cmd = new SqlCommand(sql, _sqlConnection)) + { + SqlDataReader dataReader = cmd.ExecuteReader(); + // Fill the DataTable with data from the reader and clean up. + dataTable.Load(dataReader); + dataReader.Close(); + } + return dataTable; + } + public string LookUpPetName(int carID) + { + string carPetName; + + // Establish name of stored proc. + using (SqlCommand command = new SqlCommand("GetPetName", _sqlConnection)) + { + command.CommandType = CommandType.StoredProcedure; + + // Input param. + SqlParameter param = new SqlParameter + { + ParameterName = "@carID", + SqlDbType = SqlDbType.Int, + Value = carID, + Direction = ParameterDirection.Input + }; + command.Parameters.Add(param); + + // Output param. + param = new SqlParameter + { + ParameterName = "@petName", + SqlDbType = SqlDbType.Char, + Size = 10, + Direction = ParameterDirection.Output + }; + command.Parameters.Add(param); + + // Execute the stored proc. + command.ExecuteNonQuery(); + + // Return output param. + carPetName = (string)command.Parameters["@petName"].Value; + } + return carPetName; + } + public void ProcessCreditRisk(bool throwEx, int custID) + { + // First, look up current name based on customer ID. + string fName; + string lName; + var cmdSelect = + new SqlCommand($"Select * from Customers where CustID = {custID}", + _sqlConnection); + using (var dataReader = cmdSelect.ExecuteReader()) + { + if (dataReader.HasRows) + { + dataReader.Read(); + fName = (string)dataReader["FirstName"]; + lName = (string)dataReader["LastName"]; + } + else + { + return; + } + } + + // Create command objects that represent each step of the operation. + var cmdRemove = + new SqlCommand($"Delete from Customers where CustID = {custID}", + _sqlConnection); + + var cmdInsert = + new SqlCommand("Insert Into CreditRisks" + + $"(FirstName, LastName) Values('{fName}', '{lName}')", + _sqlConnection); + + // We will get this from the connection object. + SqlTransaction tx = null; + try + { + tx = _sqlConnection.BeginTransaction(); + + // Enlist the commands into this transaction. + cmdInsert.Transaction = tx; + cmdRemove.Transaction = tx; + + // Execute the commands. + cmdInsert.ExecuteNonQuery(); + cmdRemove.ExecuteNonQuery(); + + // Simulate error. + if (throwEx) + { + throw new Exception("Sorry! Database error! Tx failed..."); + } + + // Commit it! + tx.Commit(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + // Any error will roll back transaction. + tx?.Rollback(); + } + } + } +} diff --git a/Appendix_A/AutoLotDAL2/DisconnectedLayer/InventoryDALDC.cs b/Appendix_A/AutoLotDAL2/DisconnectedLayer/InventoryDALDC.cs new file mode 100644 index 0000000..b131f45 --- /dev/null +++ b/Appendix_A/AutoLotDAL2/DisconnectedLayer/InventoryDALDC.cs @@ -0,0 +1,45 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutoLotDAL2.DisconnectedLayer +{ + public class InventoryDALDC + { + // Field data. + private string _connectionString; + private SqlDataAdapter _adapter = null; + + public InventoryDALDC(string connectionString) + { + _connectionString = connectionString; + + // Configure the SqlDataAdapter. + ConfigureAdapter(out _adapter); + } + private void ConfigureAdapter(out SqlDataAdapter adapter) + { + // Create the adapter and set up the SelectCommand. + adapter = new SqlDataAdapter("Select * From Inventory", _connectionString); + + // Obtain the remaining command objects dynamically at runtime + // using the SqlCommandBuilder. + var builder = new SqlCommandBuilder(adapter); + } + public DataTable GetAllInventory() + { + DataTable inv = new DataTable("Inventory"); + _adapter.Fill(inv); + return inv; + } + + public void UpdateInventory(DataTable modifiedTable) + { + _adapter.Update(modifiedTable); + } + } +} diff --git a/Appendix_A/AutoLotDAL2/Models/NewCar.cs b/Appendix_A/AutoLotDAL2/Models/NewCar.cs new file mode 100644 index 0000000..5b638b6 --- /dev/null +++ b/Appendix_A/AutoLotDAL2/Models/NewCar.cs @@ -0,0 +1,10 @@ +namespace AutoLotDAL2.Models +{ + public class NewCar + { + public int CarID { get; set; } + public string Color { get; set; } + public string Make { get; set; } + public string PetName { get; set; } + } +} \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL2/Properties/AssemblyInfo.cs b/Appendix_A/AutoLotDAL2/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3c53419 --- /dev/null +++ b/Appendix_A/AutoLotDAL2/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDAL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDAL")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0447cd8f-ee61-425d-a04f-f56468c8890a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("2.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/AutoLotDAL3/AutoLotDAL3.csproj b/Appendix_A/AutoLotDAL3/AutoLotDAL3.csproj new file mode 100644 index 0000000..8e6800e --- /dev/null +++ b/Appendix_A/AutoLotDAL3/AutoLotDAL3.csproj @@ -0,0 +1,85 @@ + + + + + Debug + AnyCPU + {732CCD23-B8E3-479E-845D-D082490F58D9} + Library + Properties + AutoLotDAL3 + AutoLotDAL3 + v4.6 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + True + True + AutoLotDataSet.xsd + + + + + + True + True + Settings.settings + + + + + + + AutoLotDataSet.xsd + + + Designer + MSDataSetGenerator + AutoLotDataSet.Designer.cs + + + AutoLotDataSet.xsd + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/AutoLotDAL3.sln b/Appendix_A/AutoLotDAL3/AutoLotDAL3.sln new file mode 100644 index 0000000..c3e0487 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/AutoLotDAL3.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL3", "AutoLotDAL3.csproj", "{732CCD23-B8E3-479E-845D-D082490F58D9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {732CCD23-B8E3-479E-845D-D082490F58D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/AutoLotDAL3/ConnectedLayer/InventoryDAL.cs b/Appendix_A/AutoLotDAL3/ConnectedLayer/InventoryDAL.cs new file mode 100644 index 0000000..e9d19bf --- /dev/null +++ b/Appendix_A/AutoLotDAL3/ConnectedLayer/InventoryDAL.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using AutoLotDAL3.Models; + +namespace AutoLotDAL3.ConnectedLayer +{ + public class InventoryDAL + { + // This member will be used by all methods. + private SqlConnection _sqlConnection = null; + public void OpenConnection(string connectionString) + { + _sqlConnection = new SqlConnection { ConnectionString = connectionString }; + _sqlConnection.Open(); + } + + public void CloseConnection() + { + _sqlConnection.Close(); + } + //public void InsertAuto(string color, string make, string petName) + //{ + // // Format and execute SQL statement. + // string sql = "Insert Into Inventory" + + // $"(Make, Color, PetName) Values ('{make}', '{color}', '{petName}')"; + + // // Execute using our connection. + // using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + // { + // command.ExecuteNonQuery(); + // } + //} + public void InsertAuto(NewCar car) + { + // Format and execute SQL statement. + string sql = "Insert Into Inventory (Make, Color, PetName) Values" + + $"('{car.Make}', '{car.Color}', '{car.PetName}')"; + + // Execute using our connection. + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + command.ExecuteNonQuery(); + } + } + public void InsertAuto(string color, string make, string petName) + { + // Note the "placeholders" in the SQL query. + string sql = "Insert Into Inventory" + + "(Make, Color, PetName) Values" + + "(@Make, @Color, @PetName)"; + + // This command will have internal parameters. + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + // Fill params collection. + SqlParameter parameter = new SqlParameter + { + ParameterName = "@Make", + Value = make, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + parameter = new SqlParameter + { + ParameterName = "@Color", + Value = color, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + parameter = new SqlParameter + { + ParameterName = "@PetName", + Value = petName, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + command.ExecuteNonQuery(); + } + } + + public void DeleteCar(int id) + { + // Get ID of car to delete, then do so. + string sql = $"Delete from Inventory where CarID = '{id}'"; + using (SqlCommand cmd = new SqlCommand(sql, _sqlConnection)) + { + try + { + cmd.ExecuteNonQuery(); + } + catch (SqlException ex) + { + Exception error = new Exception("Sorry! That car is on order!", ex); + throw error; + } + } + } + public void UpdateCarPetName(int id, string newPetName) + { + // Get ID of car to modify and new pet name. + string sql = $"Update Inventory Set PetName = '{newPetName}' Where CarID = '{id}'"; + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + command.ExecuteNonQuery(); + } + } + public List GetAllInventoryAsList() + { + // This will hold the records. + List inv = new List(); + + // Prep command object. + string sql = "Select * From Inventory"; + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + SqlDataReader dataReader = command.ExecuteReader(); + while (dataReader.Read()) + { + inv.Add(new NewCar + { + CarID = (int)dataReader["CarID"], + Color = (string)dataReader["Color"], + Make = (string)dataReader["Make"], + PetName = (string)dataReader["PetName"] + }); + } + dataReader.Close(); + } + return inv; + } + public DataTable GetAllInventoryAsDataTable() + { + // This will hold the records. + DataTable dataTable = new DataTable(); + + // Prep command object. + string sql = "Select * From Inventory"; + using (SqlCommand cmd = new SqlCommand(sql, _sqlConnection)) + { + SqlDataReader dataReader = cmd.ExecuteReader(); + // Fill the DataTable with data from the reader and clean up. + dataTable.Load(dataReader); + dataReader.Close(); + } + return dataTable; + } + public string LookUpPetName(int carID) + { + string carPetName; + + // Establish name of stored proc. + using (SqlCommand command = new SqlCommand("GetPetName", _sqlConnection)) + { + command.CommandType = CommandType.StoredProcedure; + + // Input param. + SqlParameter param = new SqlParameter + { + ParameterName = "@carID", + SqlDbType = SqlDbType.Int, + Value = carID, + Direction = ParameterDirection.Input + }; + command.Parameters.Add(param); + + // Output param. + param = new SqlParameter + { + ParameterName = "@petName", + SqlDbType = SqlDbType.Char, + Size = 10, + Direction = ParameterDirection.Output + }; + command.Parameters.Add(param); + + // Execute the stored proc. + command.ExecuteNonQuery(); + + // Return output param. + carPetName = (string)command.Parameters["@petName"].Value; + } + return carPetName; + } + public void ProcessCreditRisk(bool throwEx, int custID) + { + // First, look up current name based on customer ID. + string fName; + string lName; + var cmdSelect = + new SqlCommand($"Select * from Customers where CustID = {custID}", + _sqlConnection); + using (var dataReader = cmdSelect.ExecuteReader()) + { + if (dataReader.HasRows) + { + dataReader.Read(); + fName = (string)dataReader["FirstName"]; + lName = (string)dataReader["LastName"]; + } + else + { + return; + } + } + + // Create command objects that represent each step of the operation. + var cmdRemove = + new SqlCommand($"Delete from Customers where CustID = {custID}", + _sqlConnection); + + var cmdInsert = + new SqlCommand("Insert Into CreditRisks" + + $"(FirstName, LastName) Values('{fName}', '{lName}')", + _sqlConnection); + + // We will get this from the connection object. + SqlTransaction tx = null; + try + { + tx = _sqlConnection.BeginTransaction(); + + // Enlist the commands into this transaction. + cmdInsert.Transaction = tx; + cmdRemove.Transaction = tx; + + // Execute the commands. + cmdInsert.ExecuteNonQuery(); + cmdRemove.ExecuteNonQuery(); + + // Simulate error. + if (throwEx) + { + throw new Exception("Sorry! Database error! Tx failed..."); + } + + // Commit it! + tx.Commit(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + // Any error will roll back transaction. + tx?.Rollback(); + } + } + } +} diff --git a/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.Designer.cs b/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.Designer.cs new file mode 100644 index 0000000..08f4964 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.Designer.cs @@ -0,0 +1,3346 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#pragma warning disable 1591 + +namespace AutoLotDAL3.DataSets { + + + /// + ///Represents a strongly typed in-memory cache of data. + /// + [global::System.Serializable()] + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")] + [global::System.Xml.Serialization.XmlRootAttribute("AutoLotDataSet")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")] + public partial class AutoLotDataSet : global::System.Data.DataSet { + + private OrdersDataTable tableOrders; + + private CustomersDataTable tableCustomers; + + private InventoryDataTable tableInventory; + + private global::System.Data.DataRelation relationFK_Orders_Customers; + + private global::System.Data.DataRelation relationFK_Orders_Inventory; + + private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public AutoLotDataSet() { + this.BeginInit(); + this.InitClass(); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + base.Tables.CollectionChanged += schemaChangedHandler; + base.Relations.CollectionChanged += schemaChangedHandler; + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected AutoLotDataSet(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : + base(info, context, false) { + if ((this.IsBinarySerialized(info, context) == true)) { + this.InitVars(false); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + this.Tables.CollectionChanged += schemaChangedHandler1; + this.Relations.CollectionChanged += schemaChangedHandler1; + return; + } + string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); + if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { + global::System.Data.DataSet ds = new global::System.Data.DataSet(); + ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); + if ((ds.Tables["Orders"] != null)) { + base.Tables.Add(new OrdersDataTable(ds.Tables["Orders"])); + } + if ((ds.Tables["Customers"] != null)) { + base.Tables.Add(new CustomersDataTable(ds.Tables["Customers"])); + } + if ((ds.Tables["Inventory"] != null)) { + base.Tables.Add(new InventoryDataTable(ds.Tables["Inventory"])); + } + this.DataSetName = ds.DataSetName; + this.Prefix = ds.Prefix; + this.Namespace = ds.Namespace; + this.Locale = ds.Locale; + this.CaseSensitive = ds.CaseSensitive; + this.EnforceConstraints = ds.EnforceConstraints; + this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); + this.InitVars(); + } + else { + this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); + } + this.GetSerializationData(info, context); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + base.Tables.CollectionChanged += schemaChangedHandler; + this.Relations.CollectionChanged += schemaChangedHandler; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] + public OrdersDataTable Orders { + get { + return this.tableOrders; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] + public CustomersDataTable Customers { + get { + return this.tableCustomers; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] + public InventoryDataTable Inventory { + get { + return this.tableInventory; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.BrowsableAttribute(true)] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)] + public override global::System.Data.SchemaSerializationMode SchemaSerializationMode { + get { + return this._schemaSerializationMode; + } + set { + this._schemaSerializationMode = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] + public new global::System.Data.DataTableCollection Tables { + get { + return base.Tables; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] + public new global::System.Data.DataRelationCollection Relations { + get { + return base.Relations; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void InitializeDerivedDataSet() { + this.BeginInit(); + this.InitClass(); + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public override global::System.Data.DataSet Clone() { + AutoLotDataSet cln = ((AutoLotDataSet)(base.Clone())); + cln.InitVars(); + cln.SchemaSerializationMode = this.SchemaSerializationMode; + return cln; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override bool ShouldSerializeTables() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override bool ShouldSerializeRelations() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) { + if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { + this.Reset(); + global::System.Data.DataSet ds = new global::System.Data.DataSet(); + ds.ReadXml(reader); + if ((ds.Tables["Orders"] != null)) { + base.Tables.Add(new OrdersDataTable(ds.Tables["Orders"])); + } + if ((ds.Tables["Customers"] != null)) { + base.Tables.Add(new CustomersDataTable(ds.Tables["Customers"])); + } + if ((ds.Tables["Inventory"] != null)) { + base.Tables.Add(new InventoryDataTable(ds.Tables["Inventory"])); + } + this.DataSetName = ds.DataSetName; + this.Prefix = ds.Prefix; + this.Namespace = ds.Namespace; + this.Locale = ds.Locale; + this.CaseSensitive = ds.CaseSensitive; + this.EnforceConstraints = ds.EnforceConstraints; + this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); + this.InitVars(); + } + else { + this.ReadXml(reader); + this.InitVars(); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() { + global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream(); + this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null)); + stream.Position = 0; + return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars() { + this.InitVars(true); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars(bool initTable) { + this.tableOrders = ((OrdersDataTable)(base.Tables["Orders"])); + if ((initTable == true)) { + if ((this.tableOrders != null)) { + this.tableOrders.InitVars(); + } + } + this.tableCustomers = ((CustomersDataTable)(base.Tables["Customers"])); + if ((initTable == true)) { + if ((this.tableCustomers != null)) { + this.tableCustomers.InitVars(); + } + } + this.tableInventory = ((InventoryDataTable)(base.Tables["Inventory"])); + if ((initTable == true)) { + if ((this.tableInventory != null)) { + this.tableInventory.InitVars(); + } + } + this.relationFK_Orders_Customers = this.Relations["FK_Orders_Customers"]; + this.relationFK_Orders_Inventory = this.Relations["FK_Orders_Inventory"]; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitClass() { + this.DataSetName = "AutoLotDataSet"; + this.Prefix = ""; + this.Namespace = "http://tempuri.org/AutoLotDataSet.xsd"; + this.EnforceConstraints = true; + this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; + this.tableOrders = new OrdersDataTable(); + base.Tables.Add(this.tableOrders); + this.tableCustomers = new CustomersDataTable(); + base.Tables.Add(this.tableCustomers); + this.tableInventory = new InventoryDataTable(); + base.Tables.Add(this.tableInventory); + this.relationFK_Orders_Customers = new global::System.Data.DataRelation("FK_Orders_Customers", new global::System.Data.DataColumn[] { + this.tableCustomers.CustIdColumn}, new global::System.Data.DataColumn[] { + this.tableOrders.CustIdColumn}, false); + this.Relations.Add(this.relationFK_Orders_Customers); + this.relationFK_Orders_Inventory = new global::System.Data.DataRelation("FK_Orders_Inventory", new global::System.Data.DataColumn[] { + this.tableInventory.CarIdColumn}, new global::System.Data.DataColumn[] { + this.tableOrders.CarIdColumn}, false); + this.Relations.Add(this.relationFK_Orders_Inventory); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private bool ShouldSerializeOrders() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private bool ShouldSerializeCustomers() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private bool ShouldSerializeInventory() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) { + if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) { + this.InitVars(); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { + AutoLotDataSet ds = new AutoLotDataSet(); + global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); + global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); + global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); + any.Namespace = ds.Namespace; + sequence.Items.Add(any); + type.Particle = sequence; + global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); + if (xs.Contains(dsSchema.TargetNamespace)) { + global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); + global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); + try { + global::System.Xml.Schema.XmlSchema schema = null; + dsSchema.Write(s1); + for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { + schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); + s2.SetLength(0); + schema.Write(s2); + if ((s1.Length == s2.Length)) { + s1.Position = 0; + s2.Position = 0; + for (; ((s1.Position != s1.Length) + && (s1.ReadByte() == s2.ReadByte())); ) { + ; + } + if ((s1.Position == s1.Length)) { + return type; + } + } + } + } + finally { + if ((s1 != null)) { + s1.Close(); + } + if ((s2 != null)) { + s2.Close(); + } + } + } + xs.Add(dsSchema); + return type; + } + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public delegate void OrdersRowChangeEventHandler(object sender, OrdersRowChangeEvent e); + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public delegate void CustomersRowChangeEventHandler(object sender, CustomersRowChangeEvent e); + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public delegate void InventoryRowChangeEventHandler(object sender, InventoryRowChangeEvent e); + + /// + ///Represents the strongly named DataTable class. + /// + [global::System.Serializable()] + [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")] + public partial class OrdersDataTable : global::System.Data.TypedTableBase { + + private global::System.Data.DataColumn columnOrderId; + + private global::System.Data.DataColumn columnCustId; + + private global::System.Data.DataColumn columnCarId; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersDataTable() { + this.TableName = "Orders"; + this.BeginInit(); + this.InitClass(); + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal OrdersDataTable(global::System.Data.DataTable table) { + this.TableName = table.TableName; + if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { + this.CaseSensitive = table.CaseSensitive; + } + if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { + this.Locale = table.Locale; + } + if ((table.Namespace != table.DataSet.Namespace)) { + this.Namespace = table.Namespace; + } + this.Prefix = table.Prefix; + this.MinimumCapacity = table.MinimumCapacity; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected OrdersDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : + base(info, context) { + this.InitVars(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn OrderIdColumn { + get { + return this.columnOrderId; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn CustIdColumn { + get { + return this.columnCustId; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn CarIdColumn { + get { + return this.columnCarId; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + public int Count { + get { + return this.Rows.Count; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersRow this[int index] { + get { + return ((OrdersRow)(this.Rows[index])); + } + } + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event OrdersRowChangeEventHandler OrdersRowChanging; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event OrdersRowChangeEventHandler OrdersRowChanged; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event OrdersRowChangeEventHandler OrdersRowDeleting; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event OrdersRowChangeEventHandler OrdersRowDeleted; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void AddOrdersRow(OrdersRow row) { + this.Rows.Add(row); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersRow AddOrdersRow(CustomersRow parentCustomersRowByFK_Orders_Customers, InventoryRow parentInventoryRowByFK_Orders_Inventory) { + OrdersRow rowOrdersRow = ((OrdersRow)(this.NewRow())); + object[] columnValuesArray = new object[] { + null, + null, + null}; + if ((parentCustomersRowByFK_Orders_Customers != null)) { + columnValuesArray[1] = parentCustomersRowByFK_Orders_Customers[0]; + } + if ((parentInventoryRowByFK_Orders_Inventory != null)) { + columnValuesArray[2] = parentInventoryRowByFK_Orders_Inventory[0]; + } + rowOrdersRow.ItemArray = columnValuesArray; + this.Rows.Add(rowOrdersRow); + return rowOrdersRow; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersRow FindByOrderId(int OrderId) { + return ((OrdersRow)(this.Rows.Find(new object[] { + OrderId}))); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public override global::System.Data.DataTable Clone() { + OrdersDataTable cln = ((OrdersDataTable)(base.Clone())); + cln.InitVars(); + return cln; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Data.DataTable CreateInstance() { + return new OrdersDataTable(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars() { + this.columnOrderId = base.Columns["OrderId"]; + this.columnCustId = base.Columns["CustId"]; + this.columnCarId = base.Columns["CarId"]; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitClass() { + this.columnOrderId = new global::System.Data.DataColumn("OrderId", typeof(int), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnOrderId); + this.columnCustId = new global::System.Data.DataColumn("CustId", typeof(int), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnCustId); + this.columnCarId = new global::System.Data.DataColumn("CarId", typeof(int), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnCarId); + this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] { + this.columnOrderId}, true)); + this.columnOrderId.AutoIncrement = true; + this.columnOrderId.AutoIncrementSeed = -1; + this.columnOrderId.AutoIncrementStep = -1; + this.columnOrderId.AllowDBNull = false; + this.columnOrderId.ReadOnly = true; + this.columnOrderId.Unique = true; + this.columnCustId.AllowDBNull = false; + this.columnCarId.AllowDBNull = false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersRow NewOrdersRow() { + return ((OrdersRow)(this.NewRow())); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) { + return new OrdersRow(builder); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Type GetRowType() { + return typeof(OrdersRow); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowChanged(e); + if ((this.OrdersRowChanged != null)) { + this.OrdersRowChanged(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowChanging(e); + if ((this.OrdersRowChanging != null)) { + this.OrdersRowChanging(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowDeleted(e); + if ((this.OrdersRowDeleted != null)) { + this.OrdersRowDeleted(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowDeleting(e); + if ((this.OrdersRowDeleting != null)) { + this.OrdersRowDeleting(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void RemoveOrdersRow(OrdersRow row) { + this.Rows.Remove(row); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { + global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); + global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); + AutoLotDataSet ds = new AutoLotDataSet(); + global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); + any1.Namespace = "http://www.w3.org/2001/XMLSchema"; + any1.MinOccurs = new decimal(0); + any1.MaxOccurs = decimal.MaxValue; + any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; + sequence.Items.Add(any1); + global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); + any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; + any2.MinOccurs = new decimal(1); + any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; + sequence.Items.Add(any2); + global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); + attribute1.Name = "namespace"; + attribute1.FixedValue = ds.Namespace; + type.Attributes.Add(attribute1); + global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); + attribute2.Name = "tableTypeName"; + attribute2.FixedValue = "OrdersDataTable"; + type.Attributes.Add(attribute2); + type.Particle = sequence; + global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); + if (xs.Contains(dsSchema.TargetNamespace)) { + global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); + global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); + try { + global::System.Xml.Schema.XmlSchema schema = null; + dsSchema.Write(s1); + for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { + schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); + s2.SetLength(0); + schema.Write(s2); + if ((s1.Length == s2.Length)) { + s1.Position = 0; + s2.Position = 0; + for (; ((s1.Position != s1.Length) + && (s1.ReadByte() == s2.ReadByte())); ) { + ; + } + if ((s1.Position == s1.Length)) { + return type; + } + } + } + } + finally { + if ((s1 != null)) { + s1.Close(); + } + if ((s2 != null)) { + s2.Close(); + } + } + } + xs.Add(dsSchema); + return type; + } + } + + /// + ///Represents the strongly named DataTable class. + /// + [global::System.Serializable()] + [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")] + public partial class CustomersDataTable : global::System.Data.TypedTableBase { + + private global::System.Data.DataColumn columnCustId; + + private global::System.Data.DataColumn columnFirstName; + + private global::System.Data.DataColumn columnLastName; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersDataTable() { + this.TableName = "Customers"; + this.BeginInit(); + this.InitClass(); + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal CustomersDataTable(global::System.Data.DataTable table) { + this.TableName = table.TableName; + if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { + this.CaseSensitive = table.CaseSensitive; + } + if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { + this.Locale = table.Locale; + } + if ((table.Namespace != table.DataSet.Namespace)) { + this.Namespace = table.Namespace; + } + this.Prefix = table.Prefix; + this.MinimumCapacity = table.MinimumCapacity; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected CustomersDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : + base(info, context) { + this.InitVars(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn CustIdColumn { + get { + return this.columnCustId; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn FirstNameColumn { + get { + return this.columnFirstName; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn LastNameColumn { + get { + return this.columnLastName; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + public int Count { + get { + return this.Rows.Count; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersRow this[int index] { + get { + return ((CustomersRow)(this.Rows[index])); + } + } + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event CustomersRowChangeEventHandler CustomersRowChanging; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event CustomersRowChangeEventHandler CustomersRowChanged; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event CustomersRowChangeEventHandler CustomersRowDeleting; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event CustomersRowChangeEventHandler CustomersRowDeleted; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void AddCustomersRow(CustomersRow row) { + this.Rows.Add(row); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersRow AddCustomersRow(string FirstName, string LastName) { + CustomersRow rowCustomersRow = ((CustomersRow)(this.NewRow())); + object[] columnValuesArray = new object[] { + null, + FirstName, + LastName}; + rowCustomersRow.ItemArray = columnValuesArray; + this.Rows.Add(rowCustomersRow); + return rowCustomersRow; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersRow FindByCustId(int CustId) { + return ((CustomersRow)(this.Rows.Find(new object[] { + CustId}))); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public override global::System.Data.DataTable Clone() { + CustomersDataTable cln = ((CustomersDataTable)(base.Clone())); + cln.InitVars(); + return cln; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Data.DataTable CreateInstance() { + return new CustomersDataTable(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars() { + this.columnCustId = base.Columns["CustId"]; + this.columnFirstName = base.Columns["FirstName"]; + this.columnLastName = base.Columns["LastName"]; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitClass() { + this.columnCustId = new global::System.Data.DataColumn("CustId", typeof(int), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnCustId); + this.columnFirstName = new global::System.Data.DataColumn("FirstName", typeof(string), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnFirstName); + this.columnLastName = new global::System.Data.DataColumn("LastName", typeof(string), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnLastName); + this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] { + this.columnCustId}, true)); + this.columnCustId.AutoIncrement = true; + this.columnCustId.AutoIncrementSeed = -1; + this.columnCustId.AutoIncrementStep = -1; + this.columnCustId.AllowDBNull = false; + this.columnCustId.ReadOnly = true; + this.columnCustId.Unique = true; + this.columnFirstName.MaxLength = 50; + this.columnLastName.MaxLength = 50; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersRow NewCustomersRow() { + return ((CustomersRow)(this.NewRow())); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) { + return new CustomersRow(builder); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Type GetRowType() { + return typeof(CustomersRow); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowChanged(e); + if ((this.CustomersRowChanged != null)) { + this.CustomersRowChanged(this, new CustomersRowChangeEvent(((CustomersRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowChanging(e); + if ((this.CustomersRowChanging != null)) { + this.CustomersRowChanging(this, new CustomersRowChangeEvent(((CustomersRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowDeleted(e); + if ((this.CustomersRowDeleted != null)) { + this.CustomersRowDeleted(this, new CustomersRowChangeEvent(((CustomersRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowDeleting(e); + if ((this.CustomersRowDeleting != null)) { + this.CustomersRowDeleting(this, new CustomersRowChangeEvent(((CustomersRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void RemoveCustomersRow(CustomersRow row) { + this.Rows.Remove(row); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { + global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); + global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); + AutoLotDataSet ds = new AutoLotDataSet(); + global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); + any1.Namespace = "http://www.w3.org/2001/XMLSchema"; + any1.MinOccurs = new decimal(0); + any1.MaxOccurs = decimal.MaxValue; + any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; + sequence.Items.Add(any1); + global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); + any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; + any2.MinOccurs = new decimal(1); + any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; + sequence.Items.Add(any2); + global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); + attribute1.Name = "namespace"; + attribute1.FixedValue = ds.Namespace; + type.Attributes.Add(attribute1); + global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); + attribute2.Name = "tableTypeName"; + attribute2.FixedValue = "CustomersDataTable"; + type.Attributes.Add(attribute2); + type.Particle = sequence; + global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); + if (xs.Contains(dsSchema.TargetNamespace)) { + global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); + global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); + try { + global::System.Xml.Schema.XmlSchema schema = null; + dsSchema.Write(s1); + for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { + schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); + s2.SetLength(0); + schema.Write(s2); + if ((s1.Length == s2.Length)) { + s1.Position = 0; + s2.Position = 0; + for (; ((s1.Position != s1.Length) + && (s1.ReadByte() == s2.ReadByte())); ) { + ; + } + if ((s1.Position == s1.Length)) { + return type; + } + } + } + } + finally { + if ((s1 != null)) { + s1.Close(); + } + if ((s2 != null)) { + s2.Close(); + } + } + } + xs.Add(dsSchema); + return type; + } + } + + /// + ///Represents the strongly named DataTable class. + /// + [global::System.Serializable()] + [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")] + public partial class InventoryDataTable : global::System.Data.TypedTableBase { + + private global::System.Data.DataColumn columnCarId; + + private global::System.Data.DataColumn columnMake; + + private global::System.Data.DataColumn columnColor; + + private global::System.Data.DataColumn columnPetName; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryDataTable() { + this.TableName = "Inventory"; + this.BeginInit(); + this.InitClass(); + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal InventoryDataTable(global::System.Data.DataTable table) { + this.TableName = table.TableName; + if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { + this.CaseSensitive = table.CaseSensitive; + } + if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { + this.Locale = table.Locale; + } + if ((table.Namespace != table.DataSet.Namespace)) { + this.Namespace = table.Namespace; + } + this.Prefix = table.Prefix; + this.MinimumCapacity = table.MinimumCapacity; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected InventoryDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : + base(info, context) { + this.InitVars(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn CarIdColumn { + get { + return this.columnCarId; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn MakeColumn { + get { + return this.columnMake; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn ColorColumn { + get { + return this.columnColor; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn PetNameColumn { + get { + return this.columnPetName; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + public int Count { + get { + return this.Rows.Count; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow this[int index] { + get { + return ((InventoryRow)(this.Rows[index])); + } + } + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event InventoryRowChangeEventHandler InventoryRowChanging; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event InventoryRowChangeEventHandler InventoryRowChanged; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event InventoryRowChangeEventHandler InventoryRowDeleting; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event InventoryRowChangeEventHandler InventoryRowDeleted; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void AddInventoryRow(InventoryRow row) { + this.Rows.Add(row); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow AddInventoryRow(string Make, string Color, string PetName) { + InventoryRow rowInventoryRow = ((InventoryRow)(this.NewRow())); + object[] columnValuesArray = new object[] { + null, + Make, + Color, + PetName}; + rowInventoryRow.ItemArray = columnValuesArray; + this.Rows.Add(rowInventoryRow); + return rowInventoryRow; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow FindByCarId(int CarId) { + return ((InventoryRow)(this.Rows.Find(new object[] { + CarId}))); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public override global::System.Data.DataTable Clone() { + InventoryDataTable cln = ((InventoryDataTable)(base.Clone())); + cln.InitVars(); + return cln; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Data.DataTable CreateInstance() { + return new InventoryDataTable(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars() { + this.columnCarId = base.Columns["CarId"]; + this.columnMake = base.Columns["Make"]; + this.columnColor = base.Columns["Color"]; + this.columnPetName = base.Columns["PetName"]; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitClass() { + this.columnCarId = new global::System.Data.DataColumn("CarId", typeof(int), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnCarId); + this.columnMake = new global::System.Data.DataColumn("Make", typeof(string), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnMake); + this.columnColor = new global::System.Data.DataColumn("Color", typeof(string), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnColor); + this.columnPetName = new global::System.Data.DataColumn("PetName", typeof(string), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnPetName); + this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] { + this.columnCarId}, true)); + this.columnCarId.AutoIncrement = true; + this.columnCarId.AutoIncrementSeed = -1; + this.columnCarId.AutoIncrementStep = -1; + this.columnCarId.AllowDBNull = false; + this.columnCarId.ReadOnly = true; + this.columnCarId.Unique = true; + this.columnMake.MaxLength = 50; + this.columnColor.MaxLength = 50; + this.columnPetName.MaxLength = 50; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow NewInventoryRow() { + return ((InventoryRow)(this.NewRow())); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) { + return new InventoryRow(builder); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Type GetRowType() { + return typeof(InventoryRow); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowChanged(e); + if ((this.InventoryRowChanged != null)) { + this.InventoryRowChanged(this, new InventoryRowChangeEvent(((InventoryRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowChanging(e); + if ((this.InventoryRowChanging != null)) { + this.InventoryRowChanging(this, new InventoryRowChangeEvent(((InventoryRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowDeleted(e); + if ((this.InventoryRowDeleted != null)) { + this.InventoryRowDeleted(this, new InventoryRowChangeEvent(((InventoryRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowDeleting(e); + if ((this.InventoryRowDeleting != null)) { + this.InventoryRowDeleting(this, new InventoryRowChangeEvent(((InventoryRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void RemoveInventoryRow(InventoryRow row) { + this.Rows.Remove(row); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { + global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); + global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); + AutoLotDataSet ds = new AutoLotDataSet(); + global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); + any1.Namespace = "http://www.w3.org/2001/XMLSchema"; + any1.MinOccurs = new decimal(0); + any1.MaxOccurs = decimal.MaxValue; + any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; + sequence.Items.Add(any1); + global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); + any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; + any2.MinOccurs = new decimal(1); + any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; + sequence.Items.Add(any2); + global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); + attribute1.Name = "namespace"; + attribute1.FixedValue = ds.Namespace; + type.Attributes.Add(attribute1); + global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); + attribute2.Name = "tableTypeName"; + attribute2.FixedValue = "InventoryDataTable"; + type.Attributes.Add(attribute2); + type.Particle = sequence; + global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); + if (xs.Contains(dsSchema.TargetNamespace)) { + global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); + global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); + try { + global::System.Xml.Schema.XmlSchema schema = null; + dsSchema.Write(s1); + for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { + schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); + s2.SetLength(0); + schema.Write(s2); + if ((s1.Length == s2.Length)) { + s1.Position = 0; + s2.Position = 0; + for (; ((s1.Position != s1.Length) + && (s1.ReadByte() == s2.ReadByte())); ) { + ; + } + if ((s1.Position == s1.Length)) { + return type; + } + } + } + } + finally { + if ((s1 != null)) { + s1.Close(); + } + if ((s2 != null)) { + s2.Close(); + } + } + } + xs.Add(dsSchema); + return type; + } + } + + /// + ///Represents strongly named DataRow class. + /// + public partial class OrdersRow : global::System.Data.DataRow { + + private OrdersDataTable tableOrders; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal OrdersRow(global::System.Data.DataRowBuilder rb) : + base(rb) { + this.tableOrders = ((OrdersDataTable)(this.Table)); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public int OrderId { + get { + return ((int)(this[this.tableOrders.OrderIdColumn])); + } + set { + this[this.tableOrders.OrderIdColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public int CustId { + get { + return ((int)(this[this.tableOrders.CustIdColumn])); + } + set { + this[this.tableOrders.CustIdColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public int CarId { + get { + return ((int)(this[this.tableOrders.CarIdColumn])); + } + set { + this[this.tableOrders.CarIdColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersRow CustomersRow { + get { + return ((CustomersRow)(this.GetParentRow(this.Table.ParentRelations["FK_Orders_Customers"]))); + } + set { + this.SetParentRow(value, this.Table.ParentRelations["FK_Orders_Customers"]); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow InventoryRow { + get { + return ((InventoryRow)(this.GetParentRow(this.Table.ParentRelations["FK_Orders_Inventory"]))); + } + set { + this.SetParentRow(value, this.Table.ParentRelations["FK_Orders_Inventory"]); + } + } + } + + /// + ///Represents strongly named DataRow class. + /// + public partial class CustomersRow : global::System.Data.DataRow { + + private CustomersDataTable tableCustomers; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal CustomersRow(global::System.Data.DataRowBuilder rb) : + base(rb) { + this.tableCustomers = ((CustomersDataTable)(this.Table)); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public int CustId { + get { + return ((int)(this[this.tableCustomers.CustIdColumn])); + } + set { + this[this.tableCustomers.CustIdColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public string FirstName { + get { + try { + return ((string)(this[this.tableCustomers.FirstNameColumn])); + } + catch (global::System.InvalidCastException e) { + throw new global::System.Data.StrongTypingException("The value for column \'FirstName\' in table \'Customers\' is DBNull.", e); + } + } + set { + this[this.tableCustomers.FirstNameColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public string LastName { + get { + try { + return ((string)(this[this.tableCustomers.LastNameColumn])); + } + catch (global::System.InvalidCastException e) { + throw new global::System.Data.StrongTypingException("The value for column \'LastName\' in table \'Customers\' is DBNull.", e); + } + } + set { + this[this.tableCustomers.LastNameColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool IsFirstNameNull() { + return this.IsNull(this.tableCustomers.FirstNameColumn); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void SetFirstNameNull() { + this[this.tableCustomers.FirstNameColumn] = global::System.Convert.DBNull; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool IsLastNameNull() { + return this.IsNull(this.tableCustomers.LastNameColumn); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void SetLastNameNull() { + this[this.tableCustomers.LastNameColumn] = global::System.Convert.DBNull; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersRow[] GetOrdersRows() { + if ((this.Table.ChildRelations["FK_Orders_Customers"] == null)) { + return new OrdersRow[0]; + } + else { + return ((OrdersRow[])(base.GetChildRows(this.Table.ChildRelations["FK_Orders_Customers"]))); + } + } + } + + /// + ///Represents strongly named DataRow class. + /// + public partial class InventoryRow : global::System.Data.DataRow { + + private InventoryDataTable tableInventory; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal InventoryRow(global::System.Data.DataRowBuilder rb) : + base(rb) { + this.tableInventory = ((InventoryDataTable)(this.Table)); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public int CarId { + get { + return ((int)(this[this.tableInventory.CarIdColumn])); + } + set { + this[this.tableInventory.CarIdColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public string Make { + get { + try { + return ((string)(this[this.tableInventory.MakeColumn])); + } + catch (global::System.InvalidCastException e) { + throw new global::System.Data.StrongTypingException("The value for column \'Make\' in table \'Inventory\' is DBNull.", e); + } + } + set { + this[this.tableInventory.MakeColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public string Color { + get { + try { + return ((string)(this[this.tableInventory.ColorColumn])); + } + catch (global::System.InvalidCastException e) { + throw new global::System.Data.StrongTypingException("The value for column \'Color\' in table \'Inventory\' is DBNull.", e); + } + } + set { + this[this.tableInventory.ColorColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public string PetName { + get { + try { + return ((string)(this[this.tableInventory.PetNameColumn])); + } + catch (global::System.InvalidCastException e) { + throw new global::System.Data.StrongTypingException("The value for column \'PetName\' in table \'Inventory\' is DBNull.", e); + } + } + set { + this[this.tableInventory.PetNameColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool IsMakeNull() { + return this.IsNull(this.tableInventory.MakeColumn); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void SetMakeNull() { + this[this.tableInventory.MakeColumn] = global::System.Convert.DBNull; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool IsColorNull() { + return this.IsNull(this.tableInventory.ColorColumn); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void SetColorNull() { + this[this.tableInventory.ColorColumn] = global::System.Convert.DBNull; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool IsPetNameNull() { + return this.IsNull(this.tableInventory.PetNameColumn); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void SetPetNameNull() { + this[this.tableInventory.PetNameColumn] = global::System.Convert.DBNull; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersRow[] GetOrdersRows() { + if ((this.Table.ChildRelations["FK_Orders_Inventory"] == null)) { + return new OrdersRow[0]; + } + else { + return ((OrdersRow[])(base.GetChildRows(this.Table.ChildRelations["FK_Orders_Inventory"]))); + } + } + } + + /// + ///Row event argument class + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public class OrdersRowChangeEvent : global::System.EventArgs { + + private OrdersRow eventRow; + + private global::System.Data.DataRowAction eventAction; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersRowChangeEvent(OrdersRow row, global::System.Data.DataRowAction action) { + this.eventRow = row; + this.eventAction = action; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersRow Row { + get { + return this.eventRow; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataRowAction Action { + get { + return this.eventAction; + } + } + } + + /// + ///Row event argument class + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public class CustomersRowChangeEvent : global::System.EventArgs { + + private CustomersRow eventRow; + + private global::System.Data.DataRowAction eventAction; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersRowChangeEvent(CustomersRow row, global::System.Data.DataRowAction action) { + this.eventRow = row; + this.eventAction = action; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersRow Row { + get { + return this.eventRow; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataRowAction Action { + get { + return this.eventAction; + } + } + } + + /// + ///Row event argument class + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public class InventoryRowChangeEvent : global::System.EventArgs { + + private InventoryRow eventRow; + + private global::System.Data.DataRowAction eventAction; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRowChangeEvent(InventoryRow row, global::System.Data.DataRowAction action) { + this.eventRow = row; + this.eventAction = action; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow Row { + get { + return this.eventRow; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataRowAction Action { + get { + return this.eventAction; + } + } + } + } +} +namespace AutoLotDAL3.DataSets.AutoLotDataSetTableAdapters { + + + /// + ///Represents the connection and commands used to retrieve and save data. + /// + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.ComponentModel.DataObjectAttribute(true)] + [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" + + ", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public partial class OrdersTableAdapter : global::System.ComponentModel.Component { + + private global::System.Data.SqlClient.SqlDataAdapter _adapter; + + private global::System.Data.SqlClient.SqlConnection _connection; + + private global::System.Data.SqlClient.SqlTransaction _transaction; + + private global::System.Data.SqlClient.SqlCommand[] _commandCollection; + + private bool _clearBeforeFill; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public OrdersTableAdapter() { + this.ClearBeforeFill = true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected internal global::System.Data.SqlClient.SqlDataAdapter Adapter { + get { + if ((this._adapter == null)) { + this.InitAdapter(); + } + return this._adapter; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal global::System.Data.SqlClient.SqlConnection Connection { + get { + if ((this._connection == null)) { + this.InitConnection(); + } + return this._connection; + } + set { + this._connection = value; + if ((this.Adapter.InsertCommand != null)) { + this.Adapter.InsertCommand.Connection = value; + } + if ((this.Adapter.DeleteCommand != null)) { + this.Adapter.DeleteCommand.Connection = value; + } + if ((this.Adapter.UpdateCommand != null)) { + this.Adapter.UpdateCommand.Connection = value; + } + for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { + if ((this.CommandCollection[i] != null)) { + ((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[i])).Connection = value; + } + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal global::System.Data.SqlClient.SqlTransaction Transaction { + get { + return this._transaction; + } + set { + this._transaction = value; + for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { + this.CommandCollection[i].Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.DeleteCommand != null))) { + this.Adapter.DeleteCommand.Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.InsertCommand != null))) { + this.Adapter.InsertCommand.Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.UpdateCommand != null))) { + this.Adapter.UpdateCommand.Transaction = this._transaction; + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected global::System.Data.SqlClient.SqlCommand[] CommandCollection { + get { + if ((this._commandCollection == null)) { + this.InitCommandCollection(); + } + return this._commandCollection; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool ClearBeforeFill { + get { + return this._clearBeforeFill; + } + set { + this._clearBeforeFill = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitAdapter() { + this._adapter = new global::System.Data.SqlClient.SqlDataAdapter(); + global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping(); + tableMapping.SourceTable = "Table"; + tableMapping.DataSetTable = "Orders"; + tableMapping.ColumnMappings.Add("OrderId", "OrderId"); + tableMapping.ColumnMappings.Add("CustId", "CustId"); + tableMapping.ColumnMappings.Add("CarId", "CarId"); + this._adapter.TableMappings.Add(tableMapping); + this._adapter.DeleteCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.DeleteCommand.Connection = this.Connection; + this._adapter.DeleteCommand.CommandText = "DELETE FROM [dbo].[Orders] WHERE (([OrderId] = @Original_OrderId) AND ([CustId] =" + + " @Original_CustId) AND ([CarId] = @Original_CarId))"; + this._adapter.DeleteCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_OrderId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "OrderId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CustId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CustId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CarId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.InsertCommand.Connection = this.Connection; + this._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[Orders] ([CustId], [CarId]) VALUES (@CustId, @CarId);\r\nSELECT " + + "OrderId, CustId, CarId FROM Orders WHERE (OrderId = SCOPE_IDENTITY())"; + this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@CustId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CustId", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@CarId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.UpdateCommand.Connection = this.Connection; + this._adapter.UpdateCommand.CommandText = "UPDATE [dbo].[Orders] SET [CustId] = @CustId, [CarId] = @CarId WHERE (([OrderId] " + + "= @Original_OrderId) AND ([CustId] = @Original_CustId) AND ([CarId] = @Original_" + + "CarId));\r\nSELECT OrderId, CustId, CarId FROM Orders WHERE (OrderId = @OrderId)"; + this._adapter.UpdateCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@CustId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CustId", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@CarId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_OrderId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "OrderId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CustId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CustId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CarId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@OrderId", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.Input, 0, 0, "OrderId", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitConnection() { + this._connection = new global::System.Data.SqlClient.SqlConnection(); + this._connection.ConnectionString = global::AutoLotDAL3.Properties.Settings.Default.AutoLotConnectionString; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitCommandCollection() { + this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1]; + this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); + this._commandCollection[0].Connection = this.Connection; + this._commandCollection[0].CommandText = "SELECT OrderId, CustId, CarId FROM dbo.Orders"; + this._commandCollection[0].CommandType = global::System.Data.CommandType.Text; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)] + public virtual int Fill(AutoLotDataSet.OrdersDataTable dataTable) { + this.Adapter.SelectCommand = this.CommandCollection[0]; + if ((this.ClearBeforeFill == true)) { + dataTable.Clear(); + } + int returnValue = this.Adapter.Fill(dataTable); + return returnValue; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)] + public virtual AutoLotDataSet.OrdersDataTable GetData() { + this.Adapter.SelectCommand = this.CommandCollection[0]; + AutoLotDataSet.OrdersDataTable dataTable = new AutoLotDataSet.OrdersDataTable(); + this.Adapter.Fill(dataTable); + return dataTable; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(AutoLotDataSet.OrdersDataTable dataTable) { + return this.Adapter.Update(dataTable); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(AutoLotDataSet dataSet) { + return this.Adapter.Update(dataSet, "Orders"); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(global::System.Data.DataRow dataRow) { + return this.Adapter.Update(new global::System.Data.DataRow[] { + dataRow}); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(global::System.Data.DataRow[] dataRows) { + return this.Adapter.Update(dataRows); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Delete, true)] + public virtual int Delete(int Original_OrderId, int Original_CustId, int Original_CarId) { + this.Adapter.DeleteCommand.Parameters[0].Value = ((int)(Original_OrderId)); + this.Adapter.DeleteCommand.Parameters[1].Value = ((int)(Original_CustId)); + this.Adapter.DeleteCommand.Parameters[2].Value = ((int)(Original_CarId)); + global::System.Data.ConnectionState previousConnectionState = this.Adapter.DeleteCommand.Connection.State; + if (((this.Adapter.DeleteCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.DeleteCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.DeleteCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.DeleteCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, true)] + public virtual int Insert(int CustId, int CarId) { + this.Adapter.InsertCommand.Parameters[0].Value = ((int)(CustId)); + this.Adapter.InsertCommand.Parameters[1].Value = ((int)(CarId)); + global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State; + if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.InsertCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.InsertCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] + public virtual int Update(int CustId, int CarId, int Original_OrderId, int Original_CustId, int Original_CarId, int OrderId) { + this.Adapter.UpdateCommand.Parameters[0].Value = ((int)(CustId)); + this.Adapter.UpdateCommand.Parameters[1].Value = ((int)(CarId)); + this.Adapter.UpdateCommand.Parameters[2].Value = ((int)(Original_OrderId)); + this.Adapter.UpdateCommand.Parameters[3].Value = ((int)(Original_CustId)); + this.Adapter.UpdateCommand.Parameters[4].Value = ((int)(Original_CarId)); + this.Adapter.UpdateCommand.Parameters[5].Value = ((int)(OrderId)); + global::System.Data.ConnectionState previousConnectionState = this.Adapter.UpdateCommand.Connection.State; + if (((this.Adapter.UpdateCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.UpdateCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.UpdateCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] + public virtual int Update(int CustId, int CarId, int Original_OrderId, int Original_CustId, int Original_CarId) { + return this.Update(CustId, CarId, Original_OrderId, Original_CustId, Original_CarId, Original_OrderId); + } + } + + /// + ///Represents the connection and commands used to retrieve and save data. + /// + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.ComponentModel.DataObjectAttribute(true)] + [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" + + ", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public partial class CustomersTableAdapter : global::System.ComponentModel.Component { + + private global::System.Data.SqlClient.SqlDataAdapter _adapter; + + private global::System.Data.SqlClient.SqlConnection _connection; + + private global::System.Data.SqlClient.SqlTransaction _transaction; + + private global::System.Data.SqlClient.SqlCommand[] _commandCollection; + + private bool _clearBeforeFill; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public CustomersTableAdapter() { + this.ClearBeforeFill = true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected internal global::System.Data.SqlClient.SqlDataAdapter Adapter { + get { + if ((this._adapter == null)) { + this.InitAdapter(); + } + return this._adapter; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal global::System.Data.SqlClient.SqlConnection Connection { + get { + if ((this._connection == null)) { + this.InitConnection(); + } + return this._connection; + } + set { + this._connection = value; + if ((this.Adapter.InsertCommand != null)) { + this.Adapter.InsertCommand.Connection = value; + } + if ((this.Adapter.DeleteCommand != null)) { + this.Adapter.DeleteCommand.Connection = value; + } + if ((this.Adapter.UpdateCommand != null)) { + this.Adapter.UpdateCommand.Connection = value; + } + for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { + if ((this.CommandCollection[i] != null)) { + ((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[i])).Connection = value; + } + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal global::System.Data.SqlClient.SqlTransaction Transaction { + get { + return this._transaction; + } + set { + this._transaction = value; + for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { + this.CommandCollection[i].Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.DeleteCommand != null))) { + this.Adapter.DeleteCommand.Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.InsertCommand != null))) { + this.Adapter.InsertCommand.Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.UpdateCommand != null))) { + this.Adapter.UpdateCommand.Transaction = this._transaction; + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected global::System.Data.SqlClient.SqlCommand[] CommandCollection { + get { + if ((this._commandCollection == null)) { + this.InitCommandCollection(); + } + return this._commandCollection; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool ClearBeforeFill { + get { + return this._clearBeforeFill; + } + set { + this._clearBeforeFill = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitAdapter() { + this._adapter = new global::System.Data.SqlClient.SqlDataAdapter(); + global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping(); + tableMapping.SourceTable = "Table"; + tableMapping.DataSetTable = "Customers"; + tableMapping.ColumnMappings.Add("CustId", "CustId"); + tableMapping.ColumnMappings.Add("FirstName", "FirstName"); + tableMapping.ColumnMappings.Add("LastName", "LastName"); + this._adapter.TableMappings.Add(tableMapping); + this._adapter.DeleteCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.DeleteCommand.Connection = this.Connection; + this._adapter.DeleteCommand.CommandText = "DELETE FROM [dbo].[Customers] WHERE (([CustId] = @Original_CustId) AND ((@IsNull_" + + "FirstName = 1 AND [FirstName] IS NULL) OR ([FirstName] = @Original_FirstName)) A" + + "ND ((@IsNull_LastName = 1 AND [LastName] IS NULL) OR ([LastName] = @Original_Las" + + "tName)))"; + this._adapter.DeleteCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CustId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CustId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_FirstName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "FirstName", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_FirstName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "FirstName", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_LastName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "LastName", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_LastName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "LastName", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.InsertCommand.Connection = this.Connection; + this._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[Customers] ([FirstName], [LastName]) VALUES (@FirstName, @Last" + + "Name);\r\nSELECT CustId, FirstName, LastName FROM Customers WHERE (CustId = SCOPE_" + + "IDENTITY())"; + this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@FirstName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "FirstName", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@LastName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "LastName", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.UpdateCommand.Connection = this.Connection; + this._adapter.UpdateCommand.CommandText = @"UPDATE [dbo].[Customers] SET [FirstName] = @FirstName, [LastName] = @LastName WHERE (([CustId] = @Original_CustId) AND ((@IsNull_FirstName = 1 AND [FirstName] IS NULL) OR ([FirstName] = @Original_FirstName)) AND ((@IsNull_LastName = 1 AND [LastName] IS NULL) OR ([LastName] = @Original_LastName))); +SELECT CustId, FirstName, LastName FROM Customers WHERE (CustId = @CustId)"; + this._adapter.UpdateCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@FirstName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "FirstName", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@LastName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "LastName", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CustId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CustId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_FirstName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "FirstName", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_FirstName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "FirstName", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_LastName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "LastName", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_LastName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "LastName", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@CustId", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.Input, 0, 0, "CustId", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitConnection() { + this._connection = new global::System.Data.SqlClient.SqlConnection(); + this._connection.ConnectionString = global::AutoLotDAL3.Properties.Settings.Default.AutoLotConnectionString; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitCommandCollection() { + this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1]; + this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); + this._commandCollection[0].Connection = this.Connection; + this._commandCollection[0].CommandText = "SELECT CustId, FirstName, LastName FROM dbo.Customers"; + this._commandCollection[0].CommandType = global::System.Data.CommandType.Text; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)] + public virtual int Fill(AutoLotDataSet.CustomersDataTable dataTable) { + this.Adapter.SelectCommand = this.CommandCollection[0]; + if ((this.ClearBeforeFill == true)) { + dataTable.Clear(); + } + int returnValue = this.Adapter.Fill(dataTable); + return returnValue; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)] + public virtual AutoLotDataSet.CustomersDataTable GetData() { + this.Adapter.SelectCommand = this.CommandCollection[0]; + AutoLotDataSet.CustomersDataTable dataTable = new AutoLotDataSet.CustomersDataTable(); + this.Adapter.Fill(dataTable); + return dataTable; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(AutoLotDataSet.CustomersDataTable dataTable) { + return this.Adapter.Update(dataTable); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(AutoLotDataSet dataSet) { + return this.Adapter.Update(dataSet, "Customers"); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(global::System.Data.DataRow dataRow) { + return this.Adapter.Update(new global::System.Data.DataRow[] { + dataRow}); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(global::System.Data.DataRow[] dataRows) { + return this.Adapter.Update(dataRows); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Delete, true)] + public virtual int Delete(int Original_CustId, string Original_FirstName, string Original_LastName) { + this.Adapter.DeleteCommand.Parameters[0].Value = ((int)(Original_CustId)); + if ((Original_FirstName == null)) { + this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(1)); + this.Adapter.DeleteCommand.Parameters[2].Value = global::System.DBNull.Value; + } + else { + this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(0)); + this.Adapter.DeleteCommand.Parameters[2].Value = ((string)(Original_FirstName)); + } + if ((Original_LastName == null)) { + this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(1)); + this.Adapter.DeleteCommand.Parameters[4].Value = global::System.DBNull.Value; + } + else { + this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(0)); + this.Adapter.DeleteCommand.Parameters[4].Value = ((string)(Original_LastName)); + } + global::System.Data.ConnectionState previousConnectionState = this.Adapter.DeleteCommand.Connection.State; + if (((this.Adapter.DeleteCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.DeleteCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.DeleteCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.DeleteCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, true)] + public virtual int Insert(string FirstName, string LastName) { + if ((FirstName == null)) { + this.Adapter.InsertCommand.Parameters[0].Value = global::System.DBNull.Value; + } + else { + this.Adapter.InsertCommand.Parameters[0].Value = ((string)(FirstName)); + } + if ((LastName == null)) { + this.Adapter.InsertCommand.Parameters[1].Value = global::System.DBNull.Value; + } + else { + this.Adapter.InsertCommand.Parameters[1].Value = ((string)(LastName)); + } + global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State; + if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.InsertCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.InsertCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] + public virtual int Update(string FirstName, string LastName, int Original_CustId, string Original_FirstName, string Original_LastName, int CustId) { + if ((FirstName == null)) { + this.Adapter.UpdateCommand.Parameters[0].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[0].Value = ((string)(FirstName)); + } + if ((LastName == null)) { + this.Adapter.UpdateCommand.Parameters[1].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[1].Value = ((string)(LastName)); + } + this.Adapter.UpdateCommand.Parameters[2].Value = ((int)(Original_CustId)); + if ((Original_FirstName == null)) { + this.Adapter.UpdateCommand.Parameters[3].Value = ((object)(1)); + this.Adapter.UpdateCommand.Parameters[4].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[3].Value = ((object)(0)); + this.Adapter.UpdateCommand.Parameters[4].Value = ((string)(Original_FirstName)); + } + if ((Original_LastName == null)) { + this.Adapter.UpdateCommand.Parameters[5].Value = ((object)(1)); + this.Adapter.UpdateCommand.Parameters[6].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[5].Value = ((object)(0)); + this.Adapter.UpdateCommand.Parameters[6].Value = ((string)(Original_LastName)); + } + this.Adapter.UpdateCommand.Parameters[7].Value = ((int)(CustId)); + global::System.Data.ConnectionState previousConnectionState = this.Adapter.UpdateCommand.Connection.State; + if (((this.Adapter.UpdateCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.UpdateCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.UpdateCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] + public virtual int Update(string FirstName, string LastName, int Original_CustId, string Original_FirstName, string Original_LastName) { + return this.Update(FirstName, LastName, Original_CustId, Original_FirstName, Original_LastName, Original_CustId); + } + } + + /// + ///Represents the connection and commands used to retrieve and save data. + /// + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.ComponentModel.DataObjectAttribute(true)] + [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" + + ", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public partial class InventoryTableAdapter : global::System.ComponentModel.Component { + + private global::System.Data.SqlClient.SqlDataAdapter _adapter; + + private global::System.Data.SqlClient.SqlConnection _connection; + + private global::System.Data.SqlClient.SqlTransaction _transaction; + + private global::System.Data.SqlClient.SqlCommand[] _commandCollection; + + private bool _clearBeforeFill; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryTableAdapter() { + this.ClearBeforeFill = true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected internal global::System.Data.SqlClient.SqlDataAdapter Adapter { + get { + if ((this._adapter == null)) { + this.InitAdapter(); + } + return this._adapter; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal global::System.Data.SqlClient.SqlConnection Connection { + get { + if ((this._connection == null)) { + this.InitConnection(); + } + return this._connection; + } + set { + this._connection = value; + if ((this.Adapter.InsertCommand != null)) { + this.Adapter.InsertCommand.Connection = value; + } + if ((this.Adapter.DeleteCommand != null)) { + this.Adapter.DeleteCommand.Connection = value; + } + if ((this.Adapter.UpdateCommand != null)) { + this.Adapter.UpdateCommand.Connection = value; + } + for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { + if ((this.CommandCollection[i] != null)) { + ((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[i])).Connection = value; + } + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal global::System.Data.SqlClient.SqlTransaction Transaction { + get { + return this._transaction; + } + set { + this._transaction = value; + for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { + this.CommandCollection[i].Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.DeleteCommand != null))) { + this.Adapter.DeleteCommand.Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.InsertCommand != null))) { + this.Adapter.InsertCommand.Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.UpdateCommand != null))) { + this.Adapter.UpdateCommand.Transaction = this._transaction; + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected global::System.Data.SqlClient.SqlCommand[] CommandCollection { + get { + if ((this._commandCollection == null)) { + this.InitCommandCollection(); + } + return this._commandCollection; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool ClearBeforeFill { + get { + return this._clearBeforeFill; + } + set { + this._clearBeforeFill = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitAdapter() { + this._adapter = new global::System.Data.SqlClient.SqlDataAdapter(); + global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping(); + tableMapping.SourceTable = "Table"; + tableMapping.DataSetTable = "Inventory"; + tableMapping.ColumnMappings.Add("CarId", "CarId"); + tableMapping.ColumnMappings.Add("Make", "Make"); + tableMapping.ColumnMappings.Add("Color", "Color"); + tableMapping.ColumnMappings.Add("PetName", "PetName"); + this._adapter.TableMappings.Add(tableMapping); + this._adapter.DeleteCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.DeleteCommand.Connection = this.Connection; + this._adapter.DeleteCommand.CommandText = @"DELETE FROM [dbo].[Inventory] WHERE (([CarId] = @Original_CarId) AND ((@IsNull_Make = 1 AND [Make] IS NULL) OR ([Make] = @Original_Make)) AND ((@IsNull_Color = 1 AND [Color] IS NULL) OR ([Color] = @Original_Color)) AND ((@IsNull_PetName = 1 AND [PetName] IS NULL) OR ([PetName] = @Original_PetName)))"; + this._adapter.DeleteCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CarId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Make", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Make", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Color", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Color", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_PetName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PetName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.InsertCommand.Connection = this.Connection; + this._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[Inventory] ([Make], [Color], [PetName]) VALUES (@Make, @Color," + + " @PetName);\r\nSELECT CarId, Make, Color, PetName FROM Inventory WHERE (CarId = SC" + + "OPE_IDENTITY())"; + this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Make", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Color", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PetName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.UpdateCommand.Connection = this.Connection; + this._adapter.UpdateCommand.CommandText = @"UPDATE [dbo].[Inventory] SET [Make] = @Make, [Color] = @Color, [PetName] = @PetName WHERE (([CarId] = @Original_CarId) AND ((@IsNull_Make = 1 AND [Make] IS NULL) OR ([Make] = @Original_Make)) AND ((@IsNull_Color = 1 AND [Color] IS NULL) OR ([Color] = @Original_Color)) AND ((@IsNull_PetName = 1 AND [PetName] IS NULL) OR ([PetName] = @Original_PetName))); +SELECT CarId, Make, Color, PetName FROM Inventory WHERE (CarId = @CarId)"; + this._adapter.UpdateCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Make", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Color", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PetName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CarId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Make", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Make", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Color", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Color", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_PetName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PetName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@CarId", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitConnection() { + this._connection = new global::System.Data.SqlClient.SqlConnection(); + this._connection.ConnectionString = global::AutoLotDAL3.Properties.Settings.Default.AutoLotConnectionString; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitCommandCollection() { + this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1]; + this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); + this._commandCollection[0].Connection = this.Connection; + this._commandCollection[0].CommandText = "SELECT CarId, Make, Color, PetName FROM dbo.Inventory"; + this._commandCollection[0].CommandType = global::System.Data.CommandType.Text; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)] + public virtual int Fill(AutoLotDataSet.InventoryDataTable dataTable) { + this.Adapter.SelectCommand = this.CommandCollection[0]; + if ((this.ClearBeforeFill == true)) { + dataTable.Clear(); + } + int returnValue = this.Adapter.Fill(dataTable); + return returnValue; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)] + public virtual AutoLotDataSet.InventoryDataTable GetData() { + this.Adapter.SelectCommand = this.CommandCollection[0]; + AutoLotDataSet.InventoryDataTable dataTable = new AutoLotDataSet.InventoryDataTable(); + this.Adapter.Fill(dataTable); + return dataTable; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(AutoLotDataSet.InventoryDataTable dataTable) { + return this.Adapter.Update(dataTable); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(AutoLotDataSet dataSet) { + return this.Adapter.Update(dataSet, "Inventory"); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(global::System.Data.DataRow dataRow) { + return this.Adapter.Update(new global::System.Data.DataRow[] { + dataRow}); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(global::System.Data.DataRow[] dataRows) { + return this.Adapter.Update(dataRows); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Delete, true)] + public virtual int Delete(int Original_CarId, string Original_Make, string Original_Color, string Original_PetName) { + this.Adapter.DeleteCommand.Parameters[0].Value = ((int)(Original_CarId)); + if ((Original_Make == null)) { + this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(1)); + this.Adapter.DeleteCommand.Parameters[2].Value = global::System.DBNull.Value; + } + else { + this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(0)); + this.Adapter.DeleteCommand.Parameters[2].Value = ((string)(Original_Make)); + } + if ((Original_Color == null)) { + this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(1)); + this.Adapter.DeleteCommand.Parameters[4].Value = global::System.DBNull.Value; + } + else { + this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(0)); + this.Adapter.DeleteCommand.Parameters[4].Value = ((string)(Original_Color)); + } + if ((Original_PetName == null)) { + this.Adapter.DeleteCommand.Parameters[5].Value = ((object)(1)); + this.Adapter.DeleteCommand.Parameters[6].Value = global::System.DBNull.Value; + } + else { + this.Adapter.DeleteCommand.Parameters[5].Value = ((object)(0)); + this.Adapter.DeleteCommand.Parameters[6].Value = ((string)(Original_PetName)); + } + global::System.Data.ConnectionState previousConnectionState = this.Adapter.DeleteCommand.Connection.State; + if (((this.Adapter.DeleteCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.DeleteCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.DeleteCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.DeleteCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, true)] + public virtual int Insert(string Make, string Color, string PetName) { + if ((Make == null)) { + this.Adapter.InsertCommand.Parameters[0].Value = global::System.DBNull.Value; + } + else { + this.Adapter.InsertCommand.Parameters[0].Value = ((string)(Make)); + } + if ((Color == null)) { + this.Adapter.InsertCommand.Parameters[1].Value = global::System.DBNull.Value; + } + else { + this.Adapter.InsertCommand.Parameters[1].Value = ((string)(Color)); + } + if ((PetName == null)) { + this.Adapter.InsertCommand.Parameters[2].Value = global::System.DBNull.Value; + } + else { + this.Adapter.InsertCommand.Parameters[2].Value = ((string)(PetName)); + } + global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State; + if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.InsertCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.InsertCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] + public virtual int Update(string Make, string Color, string PetName, int Original_CarId, string Original_Make, string Original_Color, string Original_PetName, int CarId) { + if ((Make == null)) { + this.Adapter.UpdateCommand.Parameters[0].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[0].Value = ((string)(Make)); + } + if ((Color == null)) { + this.Adapter.UpdateCommand.Parameters[1].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[1].Value = ((string)(Color)); + } + if ((PetName == null)) { + this.Adapter.UpdateCommand.Parameters[2].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[2].Value = ((string)(PetName)); + } + this.Adapter.UpdateCommand.Parameters[3].Value = ((int)(Original_CarId)); + if ((Original_Make == null)) { + this.Adapter.UpdateCommand.Parameters[4].Value = ((object)(1)); + this.Adapter.UpdateCommand.Parameters[5].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[4].Value = ((object)(0)); + this.Adapter.UpdateCommand.Parameters[5].Value = ((string)(Original_Make)); + } + if ((Original_Color == null)) { + this.Adapter.UpdateCommand.Parameters[6].Value = ((object)(1)); + this.Adapter.UpdateCommand.Parameters[7].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[6].Value = ((object)(0)); + this.Adapter.UpdateCommand.Parameters[7].Value = ((string)(Original_Color)); + } + if ((Original_PetName == null)) { + this.Adapter.UpdateCommand.Parameters[8].Value = ((object)(1)); + this.Adapter.UpdateCommand.Parameters[9].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[8].Value = ((object)(0)); + this.Adapter.UpdateCommand.Parameters[9].Value = ((string)(Original_PetName)); + } + this.Adapter.UpdateCommand.Parameters[10].Value = ((int)(CarId)); + global::System.Data.ConnectionState previousConnectionState = this.Adapter.UpdateCommand.Connection.State; + if (((this.Adapter.UpdateCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.UpdateCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.UpdateCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] + public virtual int Update(string Make, string Color, string PetName, int Original_CarId, string Original_Make, string Original_Color, string Original_PetName) { + return this.Update(Make, Color, PetName, Original_CarId, Original_Make, Original_Color, Original_PetName, Original_CarId); + } + } + + /// + ///Represents the connection and commands used to retrieve and save data. + /// + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.ComponentModel.DataObjectAttribute(true)] + [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" + + ", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public partial class QueriesTableAdapter : global::System.ComponentModel.Component { + + private global::System.Data.IDbCommand[] _commandCollection; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected global::System.Data.IDbCommand[] CommandCollection { + get { + if ((this._commandCollection == null)) { + this.InitCommandCollection(); + } + return this._commandCollection; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitCommandCollection() { + this._commandCollection = new global::System.Data.IDbCommand[1]; + this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); + ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).Connection = new global::System.Data.SqlClient.SqlConnection(global::AutoLotDAL3.Properties.Settings.Default.AutoLotConnectionString); + ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).CommandText = "dbo.GetPetName"; + ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).CommandType = global::System.Data.CommandType.StoredProcedure; + ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@RETURN_VALUE", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.ReturnValue, 10, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@carId", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.Input, 10, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@petName", global::System.Data.SqlDbType.NVarChar, 10, global::System.Data.ParameterDirection.InputOutput, 0, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int GetPetName(global::System.Nullable carId, ref string petName) { + global::System.Data.SqlClient.SqlCommand command = ((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[0])); + if ((carId.HasValue == true)) { + command.Parameters[1].Value = ((int)(carId.Value)); + } + else { + command.Parameters[1].Value = global::System.DBNull.Value; + } + if ((petName == null)) { + command.Parameters[2].Value = global::System.DBNull.Value; + } + else { + command.Parameters[2].Value = ((string)(petName)); + } + global::System.Data.ConnectionState previousConnectionState = command.Connection.State; + if (((command.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + command.Connection.Open(); + } + int returnValue; + try { + returnValue = command.ExecuteNonQuery(); + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + command.Connection.Close(); + } + } + if (((command.Parameters[2].Value == null) + || (command.Parameters[2].Value.GetType() == typeof(global::System.DBNull)))) { + petName = null; + } + else { + petName = ((string)(command.Parameters[2].Value)); + } + return returnValue; + } + } + + /// + ///TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios + /// + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD" + + "esigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")] + public partial class TableAdapterManager : global::System.ComponentModel.Component { + + private UpdateOrderOption _updateOrder; + + private OrdersTableAdapter _ordersTableAdapter; + + private CustomersTableAdapter _customersTableAdapter; + + private InventoryTableAdapter _inventoryTableAdapter; + + private bool _backupDataSetBeforeUpdate; + + private global::System.Data.IDbConnection _connection; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public UpdateOrderOption UpdateOrder { + get { + return this._updateOrder; + } + set { + this._updateOrder = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso" + + "ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3" + + "a", "System.Drawing.Design.UITypeEditor")] + public OrdersTableAdapter OrdersTableAdapter { + get { + return this._ordersTableAdapter; + } + set { + this._ordersTableAdapter = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso" + + "ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3" + + "a", "System.Drawing.Design.UITypeEditor")] + public CustomersTableAdapter CustomersTableAdapter { + get { + return this._customersTableAdapter; + } + set { + this._customersTableAdapter = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso" + + "ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3" + + "a", "System.Drawing.Design.UITypeEditor")] + public InventoryTableAdapter InventoryTableAdapter { + get { + return this._inventoryTableAdapter; + } + set { + this._inventoryTableAdapter = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool BackupDataSetBeforeUpdate { + get { + return this._backupDataSetBeforeUpdate; + } + set { + this._backupDataSetBeforeUpdate = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + public global::System.Data.IDbConnection Connection { + get { + if ((this._connection != null)) { + return this._connection; + } + if (((this._ordersTableAdapter != null) + && (this._ordersTableAdapter.Connection != null))) { + return this._ordersTableAdapter.Connection; + } + if (((this._customersTableAdapter != null) + && (this._customersTableAdapter.Connection != null))) { + return this._customersTableAdapter.Connection; + } + if (((this._inventoryTableAdapter != null) + && (this._inventoryTableAdapter.Connection != null))) { + return this._inventoryTableAdapter.Connection; + } + return null; + } + set { + this._connection = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + public int TableAdapterInstanceCount { + get { + int count = 0; + if ((this._ordersTableAdapter != null)) { + count = (count + 1); + } + if ((this._customersTableAdapter != null)) { + count = (count + 1); + } + if ((this._inventoryTableAdapter != null)) { + count = (count + 1); + } + return count; + } + } + + /// + ///Update rows in top-down order. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private int UpdateUpdatedRows(AutoLotDataSet dataSet, global::System.Collections.Generic.List allChangedRows, global::System.Collections.Generic.List allAddedRows) { + int result = 0; + if ((this._customersTableAdapter != null)) { + global::System.Data.DataRow[] updatedRows = dataSet.Customers.Select(null, null, global::System.Data.DataViewRowState.ModifiedCurrent); + updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows); + if (((updatedRows != null) + && (0 < updatedRows.Length))) { + result = (result + this._customersTableAdapter.Update(updatedRows)); + allChangedRows.AddRange(updatedRows); + } + } + if ((this._inventoryTableAdapter != null)) { + global::System.Data.DataRow[] updatedRows = dataSet.Inventory.Select(null, null, global::System.Data.DataViewRowState.ModifiedCurrent); + updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows); + if (((updatedRows != null) + && (0 < updatedRows.Length))) { + result = (result + this._inventoryTableAdapter.Update(updatedRows)); + allChangedRows.AddRange(updatedRows); + } + } + if ((this._ordersTableAdapter != null)) { + global::System.Data.DataRow[] updatedRows = dataSet.Orders.Select(null, null, global::System.Data.DataViewRowState.ModifiedCurrent); + updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows); + if (((updatedRows != null) + && (0 < updatedRows.Length))) { + result = (result + this._ordersTableAdapter.Update(updatedRows)); + allChangedRows.AddRange(updatedRows); + } + } + return result; + } + + /// + ///Insert rows in top-down order. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private int UpdateInsertedRows(AutoLotDataSet dataSet, global::System.Collections.Generic.List allAddedRows) { + int result = 0; + if ((this._customersTableAdapter != null)) { + global::System.Data.DataRow[] addedRows = dataSet.Customers.Select(null, null, global::System.Data.DataViewRowState.Added); + if (((addedRows != null) + && (0 < addedRows.Length))) { + result = (result + this._customersTableAdapter.Update(addedRows)); + allAddedRows.AddRange(addedRows); + } + } + if ((this._inventoryTableAdapter != null)) { + global::System.Data.DataRow[] addedRows = dataSet.Inventory.Select(null, null, global::System.Data.DataViewRowState.Added); + if (((addedRows != null) + && (0 < addedRows.Length))) { + result = (result + this._inventoryTableAdapter.Update(addedRows)); + allAddedRows.AddRange(addedRows); + } + } + if ((this._ordersTableAdapter != null)) { + global::System.Data.DataRow[] addedRows = dataSet.Orders.Select(null, null, global::System.Data.DataViewRowState.Added); + if (((addedRows != null) + && (0 < addedRows.Length))) { + result = (result + this._ordersTableAdapter.Update(addedRows)); + allAddedRows.AddRange(addedRows); + } + } + return result; + } + + /// + ///Delete rows in bottom-up order. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private int UpdateDeletedRows(AutoLotDataSet dataSet, global::System.Collections.Generic.List allChangedRows) { + int result = 0; + if ((this._ordersTableAdapter != null)) { + global::System.Data.DataRow[] deletedRows = dataSet.Orders.Select(null, null, global::System.Data.DataViewRowState.Deleted); + if (((deletedRows != null) + && (0 < deletedRows.Length))) { + result = (result + this._ordersTableAdapter.Update(deletedRows)); + allChangedRows.AddRange(deletedRows); + } + } + if ((this._inventoryTableAdapter != null)) { + global::System.Data.DataRow[] deletedRows = dataSet.Inventory.Select(null, null, global::System.Data.DataViewRowState.Deleted); + if (((deletedRows != null) + && (0 < deletedRows.Length))) { + result = (result + this._inventoryTableAdapter.Update(deletedRows)); + allChangedRows.AddRange(deletedRows); + } + } + if ((this._customersTableAdapter != null)) { + global::System.Data.DataRow[] deletedRows = dataSet.Customers.Select(null, null, global::System.Data.DataViewRowState.Deleted); + if (((deletedRows != null) + && (0 < deletedRows.Length))) { + result = (result + this._customersTableAdapter.Update(deletedRows)); + allChangedRows.AddRange(deletedRows); + } + } + return result; + } + + /// + ///Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private global::System.Data.DataRow[] GetRealUpdatedRows(global::System.Data.DataRow[] updatedRows, global::System.Collections.Generic.List allAddedRows) { + if (((updatedRows == null) + || (updatedRows.Length < 1))) { + return updatedRows; + } + if (((allAddedRows == null) + || (allAddedRows.Count < 1))) { + return updatedRows; + } + global::System.Collections.Generic.List realUpdatedRows = new global::System.Collections.Generic.List(); + for (int i = 0; (i < updatedRows.Length); i = (i + 1)) { + global::System.Data.DataRow row = updatedRows[i]; + if ((allAddedRows.Contains(row) == false)) { + realUpdatedRows.Add(row); + } + } + return realUpdatedRows.ToArray(); + } + + /// + ///Update all changes to the dataset. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public virtual int UpdateAll(AutoLotDataSet dataSet) { + if ((dataSet == null)) { + throw new global::System.ArgumentNullException("dataSet"); + } + if ((dataSet.HasChanges() == false)) { + return 0; + } + if (((this._ordersTableAdapter != null) + && (this.MatchTableAdapterConnection(this._ordersTableAdapter.Connection) == false))) { + throw new global::System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s" + + "tring."); + } + if (((this._customersTableAdapter != null) + && (this.MatchTableAdapterConnection(this._customersTableAdapter.Connection) == false))) { + throw new global::System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s" + + "tring."); + } + if (((this._inventoryTableAdapter != null) + && (this.MatchTableAdapterConnection(this._inventoryTableAdapter.Connection) == false))) { + throw new global::System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s" + + "tring."); + } + global::System.Data.IDbConnection workConnection = this.Connection; + if ((workConnection == null)) { + throw new global::System.ApplicationException("TableAdapterManager contains no connection information. Set each TableAdapterMana" + + "ger TableAdapter property to a valid TableAdapter instance."); + } + bool workConnOpened = false; + if (((workConnection.State & global::System.Data.ConnectionState.Broken) + == global::System.Data.ConnectionState.Broken)) { + workConnection.Close(); + } + if ((workConnection.State == global::System.Data.ConnectionState.Closed)) { + workConnection.Open(); + workConnOpened = true; + } + global::System.Data.IDbTransaction workTransaction = workConnection.BeginTransaction(); + if ((workTransaction == null)) { + throw new global::System.ApplicationException("The transaction cannot begin. The current data connection does not support transa" + + "ctions or the current state is not allowing the transaction to begin."); + } + global::System.Collections.Generic.List allChangedRows = new global::System.Collections.Generic.List(); + global::System.Collections.Generic.List allAddedRows = new global::System.Collections.Generic.List(); + global::System.Collections.Generic.List adaptersWithAcceptChangesDuringUpdate = new global::System.Collections.Generic.List(); + global::System.Collections.Generic.Dictionary revertConnections = new global::System.Collections.Generic.Dictionary(); + int result = 0; + global::System.Data.DataSet backupDataSet = null; + if (this.BackupDataSetBeforeUpdate) { + backupDataSet = new global::System.Data.DataSet(); + backupDataSet.Merge(dataSet); + } + try { + // ---- Prepare for update ----------- + // + if ((this._ordersTableAdapter != null)) { + revertConnections.Add(this._ordersTableAdapter, this._ordersTableAdapter.Connection); + this._ordersTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(workConnection)); + this._ordersTableAdapter.Transaction = ((global::System.Data.SqlClient.SqlTransaction)(workTransaction)); + if (this._ordersTableAdapter.Adapter.AcceptChangesDuringUpdate) { + this._ordersTableAdapter.Adapter.AcceptChangesDuringUpdate = false; + adaptersWithAcceptChangesDuringUpdate.Add(this._ordersTableAdapter.Adapter); + } + } + if ((this._customersTableAdapter != null)) { + revertConnections.Add(this._customersTableAdapter, this._customersTableAdapter.Connection); + this._customersTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(workConnection)); + this._customersTableAdapter.Transaction = ((global::System.Data.SqlClient.SqlTransaction)(workTransaction)); + if (this._customersTableAdapter.Adapter.AcceptChangesDuringUpdate) { + this._customersTableAdapter.Adapter.AcceptChangesDuringUpdate = false; + adaptersWithAcceptChangesDuringUpdate.Add(this._customersTableAdapter.Adapter); + } + } + if ((this._inventoryTableAdapter != null)) { + revertConnections.Add(this._inventoryTableAdapter, this._inventoryTableAdapter.Connection); + this._inventoryTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(workConnection)); + this._inventoryTableAdapter.Transaction = ((global::System.Data.SqlClient.SqlTransaction)(workTransaction)); + if (this._inventoryTableAdapter.Adapter.AcceptChangesDuringUpdate) { + this._inventoryTableAdapter.Adapter.AcceptChangesDuringUpdate = false; + adaptersWithAcceptChangesDuringUpdate.Add(this._inventoryTableAdapter.Adapter); + } + } + // + //---- Perform updates ----------- + // + if ((this.UpdateOrder == UpdateOrderOption.UpdateInsertDelete)) { + result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows)); + result = (result + this.UpdateInsertedRows(dataSet, allAddedRows)); + } + else { + result = (result + this.UpdateInsertedRows(dataSet, allAddedRows)); + result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows)); + } + result = (result + this.UpdateDeletedRows(dataSet, allChangedRows)); + // + //---- Commit updates ----------- + // + workTransaction.Commit(); + if ((0 < allAddedRows.Count)) { + global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count]; + allAddedRows.CopyTo(rows); + for (int i = 0; (i < rows.Length); i = (i + 1)) { + global::System.Data.DataRow row = rows[i]; + row.AcceptChanges(); + } + } + if ((0 < allChangedRows.Count)) { + global::System.Data.DataRow[] rows = new System.Data.DataRow[allChangedRows.Count]; + allChangedRows.CopyTo(rows); + for (int i = 0; (i < rows.Length); i = (i + 1)) { + global::System.Data.DataRow row = rows[i]; + row.AcceptChanges(); + } + } + } + catch (global::System.Exception ex) { + workTransaction.Rollback(); + // ---- Restore the dataset ----------- + if (this.BackupDataSetBeforeUpdate) { + global::System.Diagnostics.Debug.Assert((backupDataSet != null)); + dataSet.Clear(); + dataSet.Merge(backupDataSet); + } + else { + if ((0 < allAddedRows.Count)) { + global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count]; + allAddedRows.CopyTo(rows); + for (int i = 0; (i < rows.Length); i = (i + 1)) { + global::System.Data.DataRow row = rows[i]; + row.AcceptChanges(); + row.SetAdded(); + } + } + } + throw ex; + } + finally { + if (workConnOpened) { + workConnection.Close(); + } + if ((this._ordersTableAdapter != null)) { + this._ordersTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(revertConnections[this._ordersTableAdapter])); + this._ordersTableAdapter.Transaction = null; + } + if ((this._customersTableAdapter != null)) { + this._customersTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(revertConnections[this._customersTableAdapter])); + this._customersTableAdapter.Transaction = null; + } + if ((this._inventoryTableAdapter != null)) { + this._inventoryTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(revertConnections[this._inventoryTableAdapter])); + this._inventoryTableAdapter.Transaction = null; + } + if ((0 < adaptersWithAcceptChangesDuringUpdate.Count)) { + global::System.Data.Common.DataAdapter[] adapters = new System.Data.Common.DataAdapter[adaptersWithAcceptChangesDuringUpdate.Count]; + adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters); + for (int i = 0; (i < adapters.Length); i = (i + 1)) { + global::System.Data.Common.DataAdapter adapter = adapters[i]; + adapter.AcceptChangesDuringUpdate = true; + } + } + } + return result; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected virtual void SortSelfReferenceRows(global::System.Data.DataRow[] rows, global::System.Data.DataRelation relation, bool childFirst) { + global::System.Array.Sort(rows, new SelfReferenceComparer(relation, childFirst)); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected virtual bool MatchTableAdapterConnection(global::System.Data.IDbConnection inputConnection) { + if ((this._connection != null)) { + return true; + } + if (((this.Connection == null) + || (inputConnection == null))) { + return true; + } + if (string.Equals(this.Connection.ConnectionString, inputConnection.ConnectionString, global::System.StringComparison.Ordinal)) { + return true; + } + return false; + } + + /// + ///Update Order Option + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public enum UpdateOrderOption { + + InsertUpdateDelete = 0, + + UpdateInsertDelete = 1, + } + + /// + ///Used to sort self-referenced table's rows + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private class SelfReferenceComparer : object, global::System.Collections.Generic.IComparer { + + private global::System.Data.DataRelation _relation; + + private int _childFirst; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal SelfReferenceComparer(global::System.Data.DataRelation relation, bool childFirst) { + this._relation = relation; + if (childFirst) { + this._childFirst = -1; + } + else { + this._childFirst = 1; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private global::System.Data.DataRow GetRoot(global::System.Data.DataRow row, out int distance) { + global::System.Diagnostics.Debug.Assert((row != null)); + global::System.Data.DataRow root = row; + distance = 0; + + global::System.Collections.Generic.IDictionary traversedRows = new global::System.Collections.Generic.Dictionary(); + traversedRows[row] = row; + + global::System.Data.DataRow parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default); + for ( + ; ((parent != null) + && (traversedRows.ContainsKey(parent) == false)); + ) { + distance = (distance + 1); + root = parent; + traversedRows[parent] = parent; + parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default); + } + + if ((distance == 0)) { + traversedRows.Clear(); + traversedRows[row] = row; + parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original); + for ( + ; ((parent != null) + && (traversedRows.ContainsKey(parent) == false)); + ) { + distance = (distance + 1); + root = parent; + traversedRows[parent] = parent; + parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original); + } + } + + return root; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public int Compare(global::System.Data.DataRow row1, global::System.Data.DataRow row2) { + if (object.ReferenceEquals(row1, row2)) { + return 0; + } + if ((row1 == null)) { + return -1; + } + if ((row2 == null)) { + return 1; + } + + int distance1 = 0; + global::System.Data.DataRow root1 = this.GetRoot(row1, out distance1); + + int distance2 = 0; + global::System.Data.DataRow root2 = this.GetRoot(row2, out distance2); + + if (object.ReferenceEquals(root1, root2)) { + return (this._childFirst * distance1.CompareTo(distance2)); + } + else { + global::System.Diagnostics.Debug.Assert(((root1.Table != null) + && (root2.Table != null))); + if ((root1.Table.Rows.IndexOf(root1) < root2.Table.Rows.IndexOf(root2))) { + return -1; + } + else { + return 1; + } + } + } + } + } +} + +#pragma warning restore 1591 \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xsc b/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xsc new file mode 100644 index 0000000..05b0199 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xsc @@ -0,0 +1,9 @@ + + + + + \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xsd b/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xsd new file mode 100644 index 0000000..ed542f3 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xsd @@ -0,0 +1,281 @@ + + + + + + + + + + + + + + + DELETE FROM [dbo].[Orders] WHERE (([OrderId] = @Original_OrderId) AND ([CustId] = @Original_CustId) AND ([CarId] = @Original_CarId)) + + + + + + + + + + INSERT INTO [dbo].[Orders] ([CustId], [CarId]) VALUES (@CustId, @CarId); +SELECT OrderId, CustId, CarId FROM Orders WHERE (OrderId = SCOPE_IDENTITY()) + + + + + + + + + SELECT OrderId, CustId, CarId FROM dbo.Orders + + + + + + UPDATE [dbo].[Orders] SET [CustId] = @CustId, [CarId] = @CarId WHERE (([OrderId] = @Original_OrderId) AND ([CustId] = @Original_CustId) AND ([CarId] = @Original_CarId)); +SELECT OrderId, CustId, CarId FROM Orders WHERE (OrderId = @OrderId) + + + + + + + + + + + + + + + + + + + + + + + + + DELETE FROM [dbo].[Customers] WHERE (([CustId] = @Original_CustId) AND ((@IsNull_FirstName = 1 AND [FirstName] IS NULL) OR ([FirstName] = @Original_FirstName)) AND ((@IsNull_LastName = 1 AND [LastName] IS NULL) OR ([LastName] = @Original_LastName))) + + + + + + + + + + + + INSERT INTO [dbo].[Customers] ([FirstName], [LastName]) VALUES (@FirstName, @LastName); +SELECT CustId, FirstName, LastName FROM Customers WHERE (CustId = SCOPE_IDENTITY()) + + + + + + + + + SELECT CustId, FirstName, LastName FROM dbo.Customers + + + + + + UPDATE [dbo].[Customers] SET [FirstName] = @FirstName, [LastName] = @LastName WHERE (([CustId] = @Original_CustId) AND ((@IsNull_FirstName = 1 AND [FirstName] IS NULL) OR ([FirstName] = @Original_FirstName)) AND ((@IsNull_LastName = 1 AND [LastName] IS NULL) OR ([LastName] = @Original_LastName))); +SELECT CustId, FirstName, LastName FROM Customers WHERE (CustId = @CustId) + + + + + + + + + + + + + + + + + + + + + + + + + + + DELETE FROM [dbo].[Inventory] WHERE (([CarId] = @Original_CarId) AND ((@IsNull_Make = 1 AND [Make] IS NULL) OR ([Make] = @Original_Make)) AND ((@IsNull_Color = 1 AND [Color] IS NULL) OR ([Color] = @Original_Color)) AND ((@IsNull_PetName = 1 AND [PetName] IS NULL) OR ([PetName] = @Original_PetName))) + + + + + + + + + + + + + + INSERT INTO [dbo].[Inventory] ([Make], [Color], [PetName]) VALUES (@Make, @Color, @PetName); +SELECT CarId, Make, Color, PetName FROM Inventory WHERE (CarId = SCOPE_IDENTITY()) + + + + + + + + + + SELECT CarId, Make, Color, PetName FROM dbo.Inventory + + + + + + UPDATE [dbo].[Inventory] SET [Make] = @Make, [Color] = @Color, [PetName] = @PetName WHERE (([CarId] = @Original_CarId) AND ((@IsNull_Make = 1 AND [Make] IS NULL) OR ([Make] = @Original_Make)) AND ((@IsNull_Color = 1 AND [Color] IS NULL) OR ([Color] = @Original_Color)) AND ((@IsNull_PetName = 1 AND [PetName] IS NULL) OR ([PetName] = @Original_PetName))); +SELECT CarId, Make, Color, PetName FROM Inventory WHERE (CarId = @CarId) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + dbo.GetPetName + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xss b/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xss new file mode 100644 index 0000000..94dd3c1 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DataSets/AutoLotDataSet.xss @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + 584 + 136 + + + 668 + 136 + + + + + + + 952 + 149 + + + 882 + 149 + + + + + \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/DataSets/DataSet1.Designer.cs b/Appendix_A/AutoLotDAL3/DataSets/DataSet1.Designer.cs new file mode 100644 index 0000000..811a84c --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DataSets/DataSet1.Designer.cs @@ -0,0 +1,242 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#pragma warning disable 1591 + +namespace AutoLotDAL3.DataSets { + + + /// + ///Represents a strongly typed in-memory cache of data. + /// + [global::System.Serializable()] + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")] + [global::System.Xml.Serialization.XmlRootAttribute("DataSet1")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")] + public partial class DataSet1 : global::System.Data.DataSet { + + private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public DataSet1() { + this.BeginInit(); + this.InitClass(); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + base.Tables.CollectionChanged += schemaChangedHandler; + base.Relations.CollectionChanged += schemaChangedHandler; + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected DataSet1(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : + base(info, context, false) { + if ((this.IsBinarySerialized(info, context) == true)) { + this.InitVars(false); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + this.Tables.CollectionChanged += schemaChangedHandler1; + this.Relations.CollectionChanged += schemaChangedHandler1; + return; + } + string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); + if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { + global::System.Data.DataSet ds = new global::System.Data.DataSet(); + ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); + this.DataSetName = ds.DataSetName; + this.Prefix = ds.Prefix; + this.Namespace = ds.Namespace; + this.Locale = ds.Locale; + this.CaseSensitive = ds.CaseSensitive; + this.EnforceConstraints = ds.EnforceConstraints; + this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); + this.InitVars(); + } + else { + this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); + } + this.GetSerializationData(info, context); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + base.Tables.CollectionChanged += schemaChangedHandler; + this.Relations.CollectionChanged += schemaChangedHandler; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.BrowsableAttribute(true)] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)] + public override global::System.Data.SchemaSerializationMode SchemaSerializationMode { + get { + return this._schemaSerializationMode; + } + set { + this._schemaSerializationMode = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] + public new global::System.Data.DataTableCollection Tables { + get { + return base.Tables; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] + public new global::System.Data.DataRelationCollection Relations { + get { + return base.Relations; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void InitializeDerivedDataSet() { + this.BeginInit(); + this.InitClass(); + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public override global::System.Data.DataSet Clone() { + DataSet1 cln = ((DataSet1)(base.Clone())); + cln.InitVars(); + cln.SchemaSerializationMode = this.SchemaSerializationMode; + return cln; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override bool ShouldSerializeTables() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override bool ShouldSerializeRelations() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) { + if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { + this.Reset(); + global::System.Data.DataSet ds = new global::System.Data.DataSet(); + ds.ReadXml(reader); + this.DataSetName = ds.DataSetName; + this.Prefix = ds.Prefix; + this.Namespace = ds.Namespace; + this.Locale = ds.Locale; + this.CaseSensitive = ds.CaseSensitive; + this.EnforceConstraints = ds.EnforceConstraints; + this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); + this.InitVars(); + } + else { + this.ReadXml(reader); + this.InitVars(); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() { + global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream(); + this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null)); + stream.Position = 0; + return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars() { + this.InitVars(true); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars(bool initTable) { + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitClass() { + this.DataSetName = "DataSet1"; + this.Prefix = ""; + this.Namespace = "http://tempuri.org/DataSet1.xsd"; + this.EnforceConstraints = true; + this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) { + if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) { + this.InitVars(); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { + DataSet1 ds = new DataSet1(); + global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); + global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); + global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); + any.Namespace = ds.Namespace; + sequence.Items.Add(any); + type.Particle = sequence; + global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); + if (xs.Contains(dsSchema.TargetNamespace)) { + global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); + global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); + try { + global::System.Xml.Schema.XmlSchema schema = null; + dsSchema.Write(s1); + for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { + schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); + s2.SetLength(0); + schema.Write(s2); + if ((s1.Length == s2.Length)) { + s1.Position = 0; + s2.Position = 0; + for (; ((s1.Position != s1.Length) + && (s1.ReadByte() == s2.ReadByte())); ) { + ; + } + if ((s1.Position == s1.Length)) { + return type; + } + } + } + } + finally { + if ((s1 != null)) { + s1.Close(); + } + if ((s2 != null)) { + s2.Close(); + } + } + } + xs.Add(dsSchema); + return type; + } + } +} + +#pragma warning restore 1591 \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xsc b/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xsc new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xsc @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xsd b/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xsd new file mode 100644 index 0000000..b1cc2b8 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xsd @@ -0,0 +1,16 @@ + + + + + + + + diff --git a/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xss b/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xss new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DataSets/DataSet1.xss @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/DisconnectedLayer/InventoryDALDC.cs b/Appendix_A/AutoLotDAL3/DisconnectedLayer/InventoryDALDC.cs new file mode 100644 index 0000000..dc7f594 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/DisconnectedLayer/InventoryDALDC.cs @@ -0,0 +1,40 @@ +using System.Data; +using System.Data.SqlClient; + +namespace AutoLotDAL3.DisconnectedLayer +{ + public class InventoryDALDC + { + // Field data. + private string _connectionString; + private SqlDataAdapter _adapter = null; + + public InventoryDALDC(string connectionString) + { + _connectionString = connectionString; + + // Configure the SqlDataAdapter. + ConfigureAdapter(out _adapter); + } + private void ConfigureAdapter(out SqlDataAdapter adapter) + { + // Create the adapter and set up the SelectCommand. + adapter = new SqlDataAdapter("Select * From Inventory", _connectionString); + + // Obtain the remaining command objects dynamically at runtime + // using the SqlCommandBuilder. + var builder = new SqlCommandBuilder(adapter); + } + public DataTable GetAllInventory() + { + DataTable inv = new DataTable("Inventory"); + _adapter.Fill(inv); + return inv; + } + + public void UpdateInventory(DataTable modifiedTable) + { + _adapter.Update(modifiedTable); + } + } +} diff --git a/Appendix_A/AutoLotDAL3/Models/NewCar.cs b/Appendix_A/AutoLotDAL3/Models/NewCar.cs new file mode 100644 index 0000000..d30f49f --- /dev/null +++ b/Appendix_A/AutoLotDAL3/Models/NewCar.cs @@ -0,0 +1,10 @@ +namespace AutoLotDAL3.Models +{ + public class NewCar + { + public int CarID { get; set; } + public string Color { get; set; } + public string Make { get; set; } + public string PetName { get; set; } + } +} \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/Properties/AssemblyInfo.cs b/Appendix_A/AutoLotDAL3/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..473e56b --- /dev/null +++ b/Appendix_A/AutoLotDAL3/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDAL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDAL")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0447cd8f-ee61-425d-a04f-f56468c8890a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/AutoLotDAL3/Properties/Settings.Designer.cs b/Appendix_A/AutoLotDAL3/Properties/Settings.Designer.cs new file mode 100644 index 0000000..0bb5174 --- /dev/null +++ b/Appendix_A/AutoLotDAL3/Properties/Settings.Designer.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace AutoLotDAL3.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] + [global::System.Configuration.DefaultSettingValueAttribute("Data Source=.\\SQLEXPRESS2014;Initial Catalog=AutoLot;Integrated Security=True")] + public string AutoLotConnectionString { + get { + return ((string)(this["AutoLotConnectionString"])); + } + } + } +} diff --git a/Appendix_A/AutoLotDAL3/Properties/Settings.settings b/Appendix_A/AutoLotDAL3/Properties/Settings.settings new file mode 100644 index 0000000..5b7dd2d --- /dev/null +++ b/Appendix_A/AutoLotDAL3/Properties/Settings.settings @@ -0,0 +1,14 @@ + + + + + + <?xml version="1.0" encoding="utf-16"?> +<SerializableConnectionString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <ConnectionString>Data Source=.\SQLEXPRESS2014;Initial Catalog=AutoLot;Integrated Security=True</ConnectionString> + <ProviderName>System.Data.SqlClient</ProviderName> +</SerializableConnectionString> + Data Source=.\SQLEXPRESS2014;Initial Catalog=AutoLot;Integrated Security=True + + + \ No newline at end of file diff --git a/Appendix_A/AutoLotDAL3/app.config b/Appendix_A/AutoLotDAL3/app.config new file mode 100644 index 0000000..102ebde --- /dev/null +++ b/Appendix_A/AutoLotDAL3/app.config @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/App.config b/Appendix_A/DataGridViewDataDesigner/App.config new file mode 100644 index 0000000..3b7296c --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/App.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/ClassDiagram1.cd b/Appendix_A/DataGridViewDataDesigner/ClassDiagram1.cd new file mode 100644 index 0000000..8ada402 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/ClassDiagram1.cd @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AAAAAAAAAwAAAAJABAACQAAAAAgCQBgAAAAAAgEAFBA= + + + + + + ACABgAAgACAAAAIAAACAEEACAEAAAAAAAAAACAAAAAA= + MainForm.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAA= + Program.cs + + + + + + EASAAGAAEAAAAAcAIAAAAAAAACEICAAAAAAAAAAABBA= + + + + + + AQAAACAAAABABAEBAAAAMAAgAAACgACAAAQABAAABAQ= + + + + + + AAAAAAAAAAAAAAAAAAABEAAAAQAAAAAAAAAAAAAAAIA= + + + + + + AAAAAAAAAAAAAAAAAAAAIAAAAAABAAAgAAAAAAAAAAA= + + + + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/DataGridViewDataDesigner.csproj b/Appendix_A/DataGridViewDataDesigner/DataGridViewDataDesigner.csproj new file mode 100644 index 0000000..826aeb2 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/DataGridViewDataDesigner.csproj @@ -0,0 +1,110 @@ + + + + + Debug + AnyCPU + {143DE2EE-324A-4CAD-982A-A5BC7684DBC0} + WinExe + Properties + DataGridViewDataDesigner + DataGridViewDataDesigner + v4.6 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + InventoryDataSet.xsd + + + True + True + InventoryDataSet.xsd + + + Form + + + MainForm.cs + + + + + MainForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + + InventoryDataSet.xsd + + + MSDataSetGenerator + InventoryDataSet.Designer.cs + Designer + + + InventoryDataSet.xsd + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/DataGridViewDataDesigner.sln b/Appendix_A/DataGridViewDataDesigner/DataGridViewDataDesigner.sln new file mode 100644 index 0000000..6bab618 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/DataGridViewDataDesigner.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataGridViewDataDesigner", "DataGridViewDataDesigner.csproj", "{143DE2EE-324A-4CAD-982A-A5BC7684DBC0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {143DE2EE-324A-4CAD-982A-A5BC7684DBC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {143DE2EE-324A-4CAD-982A-A5BC7684DBC0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {143DE2EE-324A-4CAD-982A-A5BC7684DBC0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {143DE2EE-324A-4CAD-982A-A5BC7684DBC0}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.Designer.cs b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.Designer.cs new file mode 100644 index 0000000..c06c324 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.Designer.cs @@ -0,0 +1,1551 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#pragma warning disable 1591 + +namespace DataGridViewDataDesigner { + + + /// + ///Represents a strongly typed in-memory cache of data. + /// + [global::System.Serializable()] + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")] + [global::System.Xml.Serialization.XmlRootAttribute("InventoryDataSet")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")] + public partial class InventoryDataSet : global::System.Data.DataSet { + + private InventoryDataTable tableInventory; + + private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryDataSet() { + this.BeginInit(); + this.InitClass(); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + base.Tables.CollectionChanged += schemaChangedHandler; + base.Relations.CollectionChanged += schemaChangedHandler; + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected InventoryDataSet(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : + base(info, context, false) { + if ((this.IsBinarySerialized(info, context) == true)) { + this.InitVars(false); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + this.Tables.CollectionChanged += schemaChangedHandler1; + this.Relations.CollectionChanged += schemaChangedHandler1; + return; + } + string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); + if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { + global::System.Data.DataSet ds = new global::System.Data.DataSet(); + ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); + if ((ds.Tables["Inventory"] != null)) { + base.Tables.Add(new InventoryDataTable(ds.Tables["Inventory"])); + } + this.DataSetName = ds.DataSetName; + this.Prefix = ds.Prefix; + this.Namespace = ds.Namespace; + this.Locale = ds.Locale; + this.CaseSensitive = ds.CaseSensitive; + this.EnforceConstraints = ds.EnforceConstraints; + this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); + this.InitVars(); + } + else { + this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); + } + this.GetSerializationData(info, context); + global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); + base.Tables.CollectionChanged += schemaChangedHandler; + this.Relations.CollectionChanged += schemaChangedHandler; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] + public InventoryDataTable Inventory { + get { + return this.tableInventory; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.BrowsableAttribute(true)] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)] + public override global::System.Data.SchemaSerializationMode SchemaSerializationMode { + get { + return this._schemaSerializationMode; + } + set { + this._schemaSerializationMode = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] + public new global::System.Data.DataTableCollection Tables { + get { + return base.Tables; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] + public new global::System.Data.DataRelationCollection Relations { + get { + return base.Relations; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void InitializeDerivedDataSet() { + this.BeginInit(); + this.InitClass(); + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public override global::System.Data.DataSet Clone() { + InventoryDataSet cln = ((InventoryDataSet)(base.Clone())); + cln.InitVars(); + cln.SchemaSerializationMode = this.SchemaSerializationMode; + return cln; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override bool ShouldSerializeTables() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override bool ShouldSerializeRelations() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) { + if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { + this.Reset(); + global::System.Data.DataSet ds = new global::System.Data.DataSet(); + ds.ReadXml(reader); + if ((ds.Tables["Inventory"] != null)) { + base.Tables.Add(new InventoryDataTable(ds.Tables["Inventory"])); + } + this.DataSetName = ds.DataSetName; + this.Prefix = ds.Prefix; + this.Namespace = ds.Namespace; + this.Locale = ds.Locale; + this.CaseSensitive = ds.CaseSensitive; + this.EnforceConstraints = ds.EnforceConstraints; + this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); + this.InitVars(); + } + else { + this.ReadXml(reader); + this.InitVars(); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() { + global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream(); + this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null)); + stream.Position = 0; + return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars() { + this.InitVars(true); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars(bool initTable) { + this.tableInventory = ((InventoryDataTable)(base.Tables["Inventory"])); + if ((initTable == true)) { + if ((this.tableInventory != null)) { + this.tableInventory.InitVars(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitClass() { + this.DataSetName = "InventoryDataSet"; + this.Prefix = ""; + this.Namespace = "http://tempuri.org/InventoryDataSet.xsd"; + this.EnforceConstraints = true; + this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; + this.tableInventory = new InventoryDataTable(); + base.Tables.Add(this.tableInventory); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private bool ShouldSerializeInventory() { + return false; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) { + if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) { + this.InitVars(); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { + InventoryDataSet ds = new InventoryDataSet(); + global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); + global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); + global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); + any.Namespace = ds.Namespace; + sequence.Items.Add(any); + type.Particle = sequence; + global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); + if (xs.Contains(dsSchema.TargetNamespace)) { + global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); + global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); + try { + global::System.Xml.Schema.XmlSchema schema = null; + dsSchema.Write(s1); + for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { + schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); + s2.SetLength(0); + schema.Write(s2); + if ((s1.Length == s2.Length)) { + s1.Position = 0; + s2.Position = 0; + for (; ((s1.Position != s1.Length) + && (s1.ReadByte() == s2.ReadByte())); ) { + ; + } + if ((s1.Position == s1.Length)) { + return type; + } + } + } + } + finally { + if ((s1 != null)) { + s1.Close(); + } + if ((s2 != null)) { + s2.Close(); + } + } + } + xs.Add(dsSchema); + return type; + } + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public delegate void InventoryRowChangeEventHandler(object sender, InventoryRowChangeEvent e); + + /// + ///Represents the strongly named DataTable class. + /// + [global::System.Serializable()] + [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")] + public partial class InventoryDataTable : global::System.Data.TypedTableBase { + + private global::System.Data.DataColumn columnCarId; + + private global::System.Data.DataColumn columnMake; + + private global::System.Data.DataColumn columnColor; + + private global::System.Data.DataColumn columnPetName; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryDataTable() { + this.TableName = "Inventory"; + this.BeginInit(); + this.InitClass(); + this.EndInit(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal InventoryDataTable(global::System.Data.DataTable table) { + this.TableName = table.TableName; + if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { + this.CaseSensitive = table.CaseSensitive; + } + if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { + this.Locale = table.Locale; + } + if ((table.Namespace != table.DataSet.Namespace)) { + this.Namespace = table.Namespace; + } + this.Prefix = table.Prefix; + this.MinimumCapacity = table.MinimumCapacity; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected InventoryDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : + base(info, context) { + this.InitVars(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn CarIdColumn { + get { + return this.columnCarId; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn MakeColumn { + get { + return this.columnMake; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn ColorColumn { + get { + return this.columnColor; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataColumn PetNameColumn { + get { + return this.columnPetName; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + public int Count { + get { + return this.Rows.Count; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow this[int index] { + get { + return ((InventoryRow)(this.Rows[index])); + } + } + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event InventoryRowChangeEventHandler InventoryRowChanging; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event InventoryRowChangeEventHandler InventoryRowChanged; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event InventoryRowChangeEventHandler InventoryRowDeleting; + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public event InventoryRowChangeEventHandler InventoryRowDeleted; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void AddInventoryRow(InventoryRow row) { + this.Rows.Add(row); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow AddInventoryRow(string Make, string Color, string PetName) { + InventoryRow rowInventoryRow = ((InventoryRow)(this.NewRow())); + object[] columnValuesArray = new object[] { + null, + Make, + Color, + PetName}; + rowInventoryRow.ItemArray = columnValuesArray; + this.Rows.Add(rowInventoryRow); + return rowInventoryRow; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow FindByCarId(int CarId) { + return ((InventoryRow)(this.Rows.Find(new object[] { + CarId}))); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public override global::System.Data.DataTable Clone() { + InventoryDataTable cln = ((InventoryDataTable)(base.Clone())); + cln.InitVars(); + return cln; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Data.DataTable CreateInstance() { + return new InventoryDataTable(); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal void InitVars() { + this.columnCarId = base.Columns["CarId"]; + this.columnMake = base.Columns["Make"]; + this.columnColor = base.Columns["Color"]; + this.columnPetName = base.Columns["PetName"]; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitClass() { + this.columnCarId = new global::System.Data.DataColumn("CarId", typeof(int), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnCarId); + this.columnMake = new global::System.Data.DataColumn("Make", typeof(string), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnMake); + this.columnColor = new global::System.Data.DataColumn("Color", typeof(string), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnColor); + this.columnPetName = new global::System.Data.DataColumn("PetName", typeof(string), null, global::System.Data.MappingType.Element); + base.Columns.Add(this.columnPetName); + this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] { + this.columnCarId}, true)); + this.columnCarId.AutoIncrement = true; + this.columnCarId.AutoIncrementSeed = -1; + this.columnCarId.AutoIncrementStep = -1; + this.columnCarId.AllowDBNull = false; + this.columnCarId.ReadOnly = true; + this.columnCarId.Unique = true; + this.columnMake.MaxLength = 50; + this.columnColor.MaxLength = 50; + this.columnPetName.MaxLength = 50; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow NewInventoryRow() { + return ((InventoryRow)(this.NewRow())); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) { + return new InventoryRow(builder); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override global::System.Type GetRowType() { + return typeof(InventoryRow); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowChanged(e); + if ((this.InventoryRowChanged != null)) { + this.InventoryRowChanged(this, new InventoryRowChangeEvent(((InventoryRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowChanging(e); + if ((this.InventoryRowChanging != null)) { + this.InventoryRowChanging(this, new InventoryRowChangeEvent(((InventoryRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowDeleted(e); + if ((this.InventoryRowDeleted != null)) { + this.InventoryRowDeleted(this, new InventoryRowChangeEvent(((InventoryRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) { + base.OnRowDeleting(e); + if ((this.InventoryRowDeleting != null)) { + this.InventoryRowDeleting(this, new InventoryRowChangeEvent(((InventoryRow)(e.Row)), e.Action)); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void RemoveInventoryRow(InventoryRow row) { + this.Rows.Remove(row); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { + global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); + global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); + InventoryDataSet ds = new InventoryDataSet(); + global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); + any1.Namespace = "http://www.w3.org/2001/XMLSchema"; + any1.MinOccurs = new decimal(0); + any1.MaxOccurs = decimal.MaxValue; + any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; + sequence.Items.Add(any1); + global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); + any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; + any2.MinOccurs = new decimal(1); + any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; + sequence.Items.Add(any2); + global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); + attribute1.Name = "namespace"; + attribute1.FixedValue = ds.Namespace; + type.Attributes.Add(attribute1); + global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); + attribute2.Name = "tableTypeName"; + attribute2.FixedValue = "InventoryDataTable"; + type.Attributes.Add(attribute2); + type.Particle = sequence; + global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); + if (xs.Contains(dsSchema.TargetNamespace)) { + global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); + global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); + try { + global::System.Xml.Schema.XmlSchema schema = null; + dsSchema.Write(s1); + for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { + schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); + s2.SetLength(0); + schema.Write(s2); + if ((s1.Length == s2.Length)) { + s1.Position = 0; + s2.Position = 0; + for (; ((s1.Position != s1.Length) + && (s1.ReadByte() == s2.ReadByte())); ) { + ; + } + if ((s1.Position == s1.Length)) { + return type; + } + } + } + } + finally { + if ((s1 != null)) { + s1.Close(); + } + if ((s2 != null)) { + s2.Close(); + } + } + } + xs.Add(dsSchema); + return type; + } + } + + /// + ///Represents strongly named DataRow class. + /// + public partial class InventoryRow : global::System.Data.DataRow { + + private InventoryDataTable tableInventory; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal InventoryRow(global::System.Data.DataRowBuilder rb) : + base(rb) { + this.tableInventory = ((InventoryDataTable)(this.Table)); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public int CarId { + get { + return ((int)(this[this.tableInventory.CarIdColumn])); + } + set { + this[this.tableInventory.CarIdColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public string Make { + get { + try { + return ((string)(this[this.tableInventory.MakeColumn])); + } + catch (global::System.InvalidCastException e) { + throw new global::System.Data.StrongTypingException("The value for column \'Make\' in table \'Inventory\' is DBNull.", e); + } + } + set { + this[this.tableInventory.MakeColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public string Color { + get { + try { + return ((string)(this[this.tableInventory.ColorColumn])); + } + catch (global::System.InvalidCastException e) { + throw new global::System.Data.StrongTypingException("The value for column \'Color\' in table \'Inventory\' is DBNull.", e); + } + } + set { + this[this.tableInventory.ColorColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public string PetName { + get { + try { + return ((string)(this[this.tableInventory.PetNameColumn])); + } + catch (global::System.InvalidCastException e) { + throw new global::System.Data.StrongTypingException("The value for column \'PetName\' in table \'Inventory\' is DBNull.", e); + } + } + set { + this[this.tableInventory.PetNameColumn] = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool IsMakeNull() { + return this.IsNull(this.tableInventory.MakeColumn); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void SetMakeNull() { + this[this.tableInventory.MakeColumn] = global::System.Convert.DBNull; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool IsColorNull() { + return this.IsNull(this.tableInventory.ColorColumn); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void SetColorNull() { + this[this.tableInventory.ColorColumn] = global::System.Convert.DBNull; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool IsPetNameNull() { + return this.IsNull(this.tableInventory.PetNameColumn); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public void SetPetNameNull() { + this[this.tableInventory.PetNameColumn] = global::System.Convert.DBNull; + } + } + + /// + ///Row event argument class + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public class InventoryRowChangeEvent : global::System.EventArgs { + + private InventoryRow eventRow; + + private global::System.Data.DataRowAction eventAction; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRowChangeEvent(InventoryRow row, global::System.Data.DataRowAction action) { + this.eventRow = row; + this.eventAction = action; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryRow Row { + get { + return this.eventRow; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public global::System.Data.DataRowAction Action { + get { + return this.eventAction; + } + } + } + } +} +namespace DataGridViewDataDesigner.InventoryDataSetTableAdapters { + + + /// + ///Represents the connection and commands used to retrieve and save data. + /// + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.ComponentModel.DataObjectAttribute(true)] + [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" + + ", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public partial class InventoryTableAdapter : global::System.ComponentModel.Component { + + private global::System.Data.SqlClient.SqlDataAdapter _adapter; + + private global::System.Data.SqlClient.SqlConnection _connection; + + private global::System.Data.SqlClient.SqlTransaction _transaction; + + private global::System.Data.SqlClient.SqlCommand[] _commandCollection; + + private bool _clearBeforeFill; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public InventoryTableAdapter() { + this.ClearBeforeFill = true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected internal global::System.Data.SqlClient.SqlDataAdapter Adapter { + get { + if ((this._adapter == null)) { + this.InitAdapter(); + } + return this._adapter; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal global::System.Data.SqlClient.SqlConnection Connection { + get { + if ((this._connection == null)) { + this.InitConnection(); + } + return this._connection; + } + set { + this._connection = value; + if ((this.Adapter.InsertCommand != null)) { + this.Adapter.InsertCommand.Connection = value; + } + if ((this.Adapter.DeleteCommand != null)) { + this.Adapter.DeleteCommand.Connection = value; + } + if ((this.Adapter.UpdateCommand != null)) { + this.Adapter.UpdateCommand.Connection = value; + } + for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { + if ((this.CommandCollection[i] != null)) { + ((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[i])).Connection = value; + } + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal global::System.Data.SqlClient.SqlTransaction Transaction { + get { + return this._transaction; + } + set { + this._transaction = value; + for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { + this.CommandCollection[i].Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.DeleteCommand != null))) { + this.Adapter.DeleteCommand.Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.InsertCommand != null))) { + this.Adapter.InsertCommand.Transaction = this._transaction; + } + if (((this.Adapter != null) + && (this.Adapter.UpdateCommand != null))) { + this.Adapter.UpdateCommand.Transaction = this._transaction; + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected global::System.Data.SqlClient.SqlCommand[] CommandCollection { + get { + if ((this._commandCollection == null)) { + this.InitCommandCollection(); + } + return this._commandCollection; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool ClearBeforeFill { + get { + return this._clearBeforeFill; + } + set { + this._clearBeforeFill = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitAdapter() { + this._adapter = new global::System.Data.SqlClient.SqlDataAdapter(); + global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping(); + tableMapping.SourceTable = "Table"; + tableMapping.DataSetTable = "Inventory"; + tableMapping.ColumnMappings.Add("CarId", "CarId"); + tableMapping.ColumnMappings.Add("Make", "Make"); + tableMapping.ColumnMappings.Add("Color", "Color"); + tableMapping.ColumnMappings.Add("PetName", "PetName"); + this._adapter.TableMappings.Add(tableMapping); + this._adapter.DeleteCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.DeleteCommand.Connection = this.Connection; + this._adapter.DeleteCommand.CommandText = @"DELETE FROM [dbo].[Inventory] WHERE (([CarId] = @Original_CarId) AND ((@IsNull_Make = 1 AND [Make] IS NULL) OR ([Make] = @Original_Make)) AND ((@IsNull_Color = 1 AND [Color] IS NULL) OR ([Color] = @Original_Color)) AND ((@IsNull_PetName = 1 AND [PetName] IS NULL) OR ([PetName] = @Original_PetName)))"; + this._adapter.DeleteCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CarId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Make", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Make", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Color", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Color", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_PetName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PetName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.InsertCommand.Connection = this.Connection; + this._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[Inventory] ([Make], [Color], [PetName]) VALUES (@Make, @Color," + + " @PetName);\r\nSELECT CarId, Make, Color, PetName FROM Inventory WHERE (CarId = SC" + + "OPE_IDENTITY())"; + this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Make", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Color", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PetName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand = new global::System.Data.SqlClient.SqlCommand(); + this._adapter.UpdateCommand.Connection = this.Connection; + this._adapter.UpdateCommand.CommandText = @"UPDATE [dbo].[Inventory] SET [Make] = @Make, [Color] = @Color, [PetName] = @PetName WHERE (([CarId] = @Original_CarId) AND ((@IsNull_Make = 1 AND [Make] IS NULL) OR ([Make] = @Original_Make)) AND ((@IsNull_Color = 1 AND [Color] IS NULL) OR ([Color] = @Original_Color)) AND ((@IsNull_PetName = 1 AND [PetName] IS NULL) OR ([PetName] = @Original_PetName))); +SELECT CarId, Make, Color, PetName FROM Inventory WHERE (CarId = @CarId)"; + this._adapter.UpdateCommand.CommandType = global::System.Data.CommandType.Text; + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Make", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Color", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PetName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_CarId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Make", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Make", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Make", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Color", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Color", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Color", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_PetName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PetName", global::System.Data.SqlDbType.NVarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PetName", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); + this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@CarId", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.Input, 0, 0, "CarId", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitConnection() { + this._connection = new global::System.Data.SqlClient.SqlConnection(); + this._connection.ConnectionString = global::DataGridViewDataDesigner.Properties.Settings.Default.AutoLotConnectionString; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private void InitCommandCollection() { + this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1]; + this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); + this._commandCollection[0].Connection = this.Connection; + this._commandCollection[0].CommandText = "SELECT CarId, Make, Color, PetName FROM dbo.Inventory"; + this._commandCollection[0].CommandType = global::System.Data.CommandType.Text; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)] + public virtual int Fill(InventoryDataSet.InventoryDataTable dataTable) { + this.Adapter.SelectCommand = this.CommandCollection[0]; + if ((this.ClearBeforeFill == true)) { + dataTable.Clear(); + } + int returnValue = this.Adapter.Fill(dataTable); + return returnValue; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)] + public virtual InventoryDataSet.InventoryDataTable GetData() { + this.Adapter.SelectCommand = this.CommandCollection[0]; + InventoryDataSet.InventoryDataTable dataTable = new InventoryDataSet.InventoryDataTable(); + this.Adapter.Fill(dataTable); + return dataTable; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(InventoryDataSet.InventoryDataTable dataTable) { + return this.Adapter.Update(dataTable); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(InventoryDataSet dataSet) { + return this.Adapter.Update(dataSet, "Inventory"); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(global::System.Data.DataRow dataRow) { + return this.Adapter.Update(new global::System.Data.DataRow[] { + dataRow}); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int Update(global::System.Data.DataRow[] dataRows) { + return this.Adapter.Update(dataRows); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Delete, true)] + public virtual int Delete(int Original_CarId, string Original_Make, string Original_Color, string Original_PetName) { + this.Adapter.DeleteCommand.Parameters[0].Value = ((int)(Original_CarId)); + if ((Original_Make == null)) { + this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(1)); + this.Adapter.DeleteCommand.Parameters[2].Value = global::System.DBNull.Value; + } + else { + this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(0)); + this.Adapter.DeleteCommand.Parameters[2].Value = ((string)(Original_Make)); + } + if ((Original_Color == null)) { + this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(1)); + this.Adapter.DeleteCommand.Parameters[4].Value = global::System.DBNull.Value; + } + else { + this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(0)); + this.Adapter.DeleteCommand.Parameters[4].Value = ((string)(Original_Color)); + } + if ((Original_PetName == null)) { + this.Adapter.DeleteCommand.Parameters[5].Value = ((object)(1)); + this.Adapter.DeleteCommand.Parameters[6].Value = global::System.DBNull.Value; + } + else { + this.Adapter.DeleteCommand.Parameters[5].Value = ((object)(0)); + this.Adapter.DeleteCommand.Parameters[6].Value = ((string)(Original_PetName)); + } + global::System.Data.ConnectionState previousConnectionState = this.Adapter.DeleteCommand.Connection.State; + if (((this.Adapter.DeleteCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.DeleteCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.DeleteCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.DeleteCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, true)] + public virtual int Insert(string Make, string Color, string PetName) { + if ((Make == null)) { + this.Adapter.InsertCommand.Parameters[0].Value = global::System.DBNull.Value; + } + else { + this.Adapter.InsertCommand.Parameters[0].Value = ((string)(Make)); + } + if ((Color == null)) { + this.Adapter.InsertCommand.Parameters[1].Value = global::System.DBNull.Value; + } + else { + this.Adapter.InsertCommand.Parameters[1].Value = ((string)(Color)); + } + if ((PetName == null)) { + this.Adapter.InsertCommand.Parameters[2].Value = global::System.DBNull.Value; + } + else { + this.Adapter.InsertCommand.Parameters[2].Value = ((string)(PetName)); + } + global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State; + if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.InsertCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.InsertCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] + public virtual int Update(string Make, string Color, string PetName, int Original_CarId, string Original_Make, string Original_Color, string Original_PetName, int CarId) { + if ((Make == null)) { + this.Adapter.UpdateCommand.Parameters[0].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[0].Value = ((string)(Make)); + } + if ((Color == null)) { + this.Adapter.UpdateCommand.Parameters[1].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[1].Value = ((string)(Color)); + } + if ((PetName == null)) { + this.Adapter.UpdateCommand.Parameters[2].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[2].Value = ((string)(PetName)); + } + this.Adapter.UpdateCommand.Parameters[3].Value = ((int)(Original_CarId)); + if ((Original_Make == null)) { + this.Adapter.UpdateCommand.Parameters[4].Value = ((object)(1)); + this.Adapter.UpdateCommand.Parameters[5].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[4].Value = ((object)(0)); + this.Adapter.UpdateCommand.Parameters[5].Value = ((string)(Original_Make)); + } + if ((Original_Color == null)) { + this.Adapter.UpdateCommand.Parameters[6].Value = ((object)(1)); + this.Adapter.UpdateCommand.Parameters[7].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[6].Value = ((object)(0)); + this.Adapter.UpdateCommand.Parameters[7].Value = ((string)(Original_Color)); + } + if ((Original_PetName == null)) { + this.Adapter.UpdateCommand.Parameters[8].Value = ((object)(1)); + this.Adapter.UpdateCommand.Parameters[9].Value = global::System.DBNull.Value; + } + else { + this.Adapter.UpdateCommand.Parameters[8].Value = ((object)(0)); + this.Adapter.UpdateCommand.Parameters[9].Value = ((string)(Original_PetName)); + } + this.Adapter.UpdateCommand.Parameters[10].Value = ((int)(CarId)); + global::System.Data.ConnectionState previousConnectionState = this.Adapter.UpdateCommand.Connection.State; + if (((this.Adapter.UpdateCommand.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + this.Adapter.UpdateCommand.Connection.Open(); + } + try { + int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery(); + return returnValue; + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + this.Adapter.UpdateCommand.Connection.Close(); + } + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] + public virtual int Update(string Make, string Color, string PetName, int Original_CarId, string Original_Make, string Original_Color, string Original_PetName) { + return this.Update(Make, Color, PetName, Original_CarId, Original_Make, Original_Color, Original_PetName, Original_CarId); + } + } + + /// + ///TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios + /// + [global::System.ComponentModel.DesignerCategoryAttribute("code")] + [global::System.ComponentModel.ToolboxItem(true)] + [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD" + + "esigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")] + public partial class TableAdapterManager : global::System.ComponentModel.Component { + + private UpdateOrderOption _updateOrder; + + private InventoryTableAdapter _inventoryTableAdapter; + + private bool _backupDataSetBeforeUpdate; + + private global::System.Data.IDbConnection _connection; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public UpdateOrderOption UpdateOrder { + get { + return this._updateOrder; + } + set { + this._updateOrder = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso" + + "ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3" + + "a", "System.Drawing.Design.UITypeEditor")] + public InventoryTableAdapter InventoryTableAdapter { + get { + return this._inventoryTableAdapter; + } + set { + this._inventoryTableAdapter = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public bool BackupDataSetBeforeUpdate { + get { + return this._backupDataSetBeforeUpdate; + } + set { + this._backupDataSetBeforeUpdate = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + public global::System.Data.IDbConnection Connection { + get { + if ((this._connection != null)) { + return this._connection; + } + if (((this._inventoryTableAdapter != null) + && (this._inventoryTableAdapter.Connection != null))) { + return this._inventoryTableAdapter.Connection; + } + return null; + } + set { + this._connection = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + [global::System.ComponentModel.Browsable(false)] + public int TableAdapterInstanceCount { + get { + int count = 0; + if ((this._inventoryTableAdapter != null)) { + count = (count + 1); + } + return count; + } + } + + /// + ///Update rows in top-down order. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private int UpdateUpdatedRows(InventoryDataSet dataSet, global::System.Collections.Generic.List allChangedRows, global::System.Collections.Generic.List allAddedRows) { + int result = 0; + if ((this._inventoryTableAdapter != null)) { + global::System.Data.DataRow[] updatedRows = dataSet.Inventory.Select(null, null, global::System.Data.DataViewRowState.ModifiedCurrent); + updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows); + if (((updatedRows != null) + && (0 < updatedRows.Length))) { + result = (result + this._inventoryTableAdapter.Update(updatedRows)); + allChangedRows.AddRange(updatedRows); + } + } + return result; + } + + /// + ///Insert rows in top-down order. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private int UpdateInsertedRows(InventoryDataSet dataSet, global::System.Collections.Generic.List allAddedRows) { + int result = 0; + if ((this._inventoryTableAdapter != null)) { + global::System.Data.DataRow[] addedRows = dataSet.Inventory.Select(null, null, global::System.Data.DataViewRowState.Added); + if (((addedRows != null) + && (0 < addedRows.Length))) { + result = (result + this._inventoryTableAdapter.Update(addedRows)); + allAddedRows.AddRange(addedRows); + } + } + return result; + } + + /// + ///Delete rows in bottom-up order. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private int UpdateDeletedRows(InventoryDataSet dataSet, global::System.Collections.Generic.List allChangedRows) { + int result = 0; + if ((this._inventoryTableAdapter != null)) { + global::System.Data.DataRow[] deletedRows = dataSet.Inventory.Select(null, null, global::System.Data.DataViewRowState.Deleted); + if (((deletedRows != null) + && (0 < deletedRows.Length))) { + result = (result + this._inventoryTableAdapter.Update(deletedRows)); + allChangedRows.AddRange(deletedRows); + } + } + return result; + } + + /// + ///Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private global::System.Data.DataRow[] GetRealUpdatedRows(global::System.Data.DataRow[] updatedRows, global::System.Collections.Generic.List allAddedRows) { + if (((updatedRows == null) + || (updatedRows.Length < 1))) { + return updatedRows; + } + if (((allAddedRows == null) + || (allAddedRows.Count < 1))) { + return updatedRows; + } + global::System.Collections.Generic.List realUpdatedRows = new global::System.Collections.Generic.List(); + for (int i = 0; (i < updatedRows.Length); i = (i + 1)) { + global::System.Data.DataRow row = updatedRows[i]; + if ((allAddedRows.Contains(row) == false)) { + realUpdatedRows.Add(row); + } + } + return realUpdatedRows.ToArray(); + } + + /// + ///Update all changes to the dataset. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public virtual int UpdateAll(InventoryDataSet dataSet) { + if ((dataSet == null)) { + throw new global::System.ArgumentNullException("dataSet"); + } + if ((dataSet.HasChanges() == false)) { + return 0; + } + if (((this._inventoryTableAdapter != null) + && (this.MatchTableAdapterConnection(this._inventoryTableAdapter.Connection) == false))) { + throw new global::System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s" + + "tring."); + } + global::System.Data.IDbConnection workConnection = this.Connection; + if ((workConnection == null)) { + throw new global::System.ApplicationException("TableAdapterManager contains no connection information. Set each TableAdapterMana" + + "ger TableAdapter property to a valid TableAdapter instance."); + } + bool workConnOpened = false; + if (((workConnection.State & global::System.Data.ConnectionState.Broken) + == global::System.Data.ConnectionState.Broken)) { + workConnection.Close(); + } + if ((workConnection.State == global::System.Data.ConnectionState.Closed)) { + workConnection.Open(); + workConnOpened = true; + } + global::System.Data.IDbTransaction workTransaction = workConnection.BeginTransaction(); + if ((workTransaction == null)) { + throw new global::System.ApplicationException("The transaction cannot begin. The current data connection does not support transa" + + "ctions or the current state is not allowing the transaction to begin."); + } + global::System.Collections.Generic.List allChangedRows = new global::System.Collections.Generic.List(); + global::System.Collections.Generic.List allAddedRows = new global::System.Collections.Generic.List(); + global::System.Collections.Generic.List adaptersWithAcceptChangesDuringUpdate = new global::System.Collections.Generic.List(); + global::System.Collections.Generic.Dictionary revertConnections = new global::System.Collections.Generic.Dictionary(); + int result = 0; + global::System.Data.DataSet backupDataSet = null; + if (this.BackupDataSetBeforeUpdate) { + backupDataSet = new global::System.Data.DataSet(); + backupDataSet.Merge(dataSet); + } + try { + // ---- Prepare for update ----------- + // + if ((this._inventoryTableAdapter != null)) { + revertConnections.Add(this._inventoryTableAdapter, this._inventoryTableAdapter.Connection); + this._inventoryTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(workConnection)); + this._inventoryTableAdapter.Transaction = ((global::System.Data.SqlClient.SqlTransaction)(workTransaction)); + if (this._inventoryTableAdapter.Adapter.AcceptChangesDuringUpdate) { + this._inventoryTableAdapter.Adapter.AcceptChangesDuringUpdate = false; + adaptersWithAcceptChangesDuringUpdate.Add(this._inventoryTableAdapter.Adapter); + } + } + // + //---- Perform updates ----------- + // + if ((this.UpdateOrder == UpdateOrderOption.UpdateInsertDelete)) { + result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows)); + result = (result + this.UpdateInsertedRows(dataSet, allAddedRows)); + } + else { + result = (result + this.UpdateInsertedRows(dataSet, allAddedRows)); + result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows)); + } + result = (result + this.UpdateDeletedRows(dataSet, allChangedRows)); + // + //---- Commit updates ----------- + // + workTransaction.Commit(); + if ((0 < allAddedRows.Count)) { + global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count]; + allAddedRows.CopyTo(rows); + for (int i = 0; (i < rows.Length); i = (i + 1)) { + global::System.Data.DataRow row = rows[i]; + row.AcceptChanges(); + } + } + if ((0 < allChangedRows.Count)) { + global::System.Data.DataRow[] rows = new System.Data.DataRow[allChangedRows.Count]; + allChangedRows.CopyTo(rows); + for (int i = 0; (i < rows.Length); i = (i + 1)) { + global::System.Data.DataRow row = rows[i]; + row.AcceptChanges(); + } + } + } + catch (global::System.Exception ex) { + workTransaction.Rollback(); + // ---- Restore the dataset ----------- + if (this.BackupDataSetBeforeUpdate) { + global::System.Diagnostics.Debug.Assert((backupDataSet != null)); + dataSet.Clear(); + dataSet.Merge(backupDataSet); + } + else { + if ((0 < allAddedRows.Count)) { + global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count]; + allAddedRows.CopyTo(rows); + for (int i = 0; (i < rows.Length); i = (i + 1)) { + global::System.Data.DataRow row = rows[i]; + row.AcceptChanges(); + row.SetAdded(); + } + } + } + throw ex; + } + finally { + if (workConnOpened) { + workConnection.Close(); + } + if ((this._inventoryTableAdapter != null)) { + this._inventoryTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(revertConnections[this._inventoryTableAdapter])); + this._inventoryTableAdapter.Transaction = null; + } + if ((0 < adaptersWithAcceptChangesDuringUpdate.Count)) { + global::System.Data.Common.DataAdapter[] adapters = new System.Data.Common.DataAdapter[adaptersWithAcceptChangesDuringUpdate.Count]; + adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters); + for (int i = 0; (i < adapters.Length); i = (i + 1)) { + global::System.Data.Common.DataAdapter adapter = adapters[i]; + adapter.AcceptChangesDuringUpdate = true; + } + } + } + return result; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected virtual void SortSelfReferenceRows(global::System.Data.DataRow[] rows, global::System.Data.DataRelation relation, bool childFirst) { + global::System.Array.Sort(rows, new SelfReferenceComparer(relation, childFirst)); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + protected virtual bool MatchTableAdapterConnection(global::System.Data.IDbConnection inputConnection) { + if ((this._connection != null)) { + return true; + } + if (((this.Connection == null) + || (inputConnection == null))) { + return true; + } + if (string.Equals(this.Connection.ConnectionString, inputConnection.ConnectionString, global::System.StringComparison.Ordinal)) { + return true; + } + return false; + } + + /// + ///Update Order Option + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public enum UpdateOrderOption { + + InsertUpdateDelete = 0, + + UpdateInsertDelete = 1, + } + + /// + ///Used to sort self-referenced table's rows + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private class SelfReferenceComparer : object, global::System.Collections.Generic.IComparer { + + private global::System.Data.DataRelation _relation; + + private int _childFirst; + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + internal SelfReferenceComparer(global::System.Data.DataRelation relation, bool childFirst) { + this._relation = relation; + if (childFirst) { + this._childFirst = -1; + } + else { + this._childFirst = 1; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + private global::System.Data.DataRow GetRoot(global::System.Data.DataRow row, out int distance) { + global::System.Diagnostics.Debug.Assert((row != null)); + global::System.Data.DataRow root = row; + distance = 0; + + global::System.Collections.Generic.IDictionary traversedRows = new global::System.Collections.Generic.Dictionary(); + traversedRows[row] = row; + + global::System.Data.DataRow parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default); + for ( + ; ((parent != null) + && (traversedRows.ContainsKey(parent) == false)); + ) { + distance = (distance + 1); + root = parent; + traversedRows[parent] = parent; + parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default); + } + + if ((distance == 0)) { + traversedRows.Clear(); + traversedRows[row] = row; + parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original); + for ( + ; ((parent != null) + && (traversedRows.ContainsKey(parent) == false)); + ) { + distance = (distance + 1); + root = parent; + traversedRows[parent] = parent; + parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original); + } + } + + return root; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] + public int Compare(global::System.Data.DataRow row1, global::System.Data.DataRow row2) { + if (object.ReferenceEquals(row1, row2)) { + return 0; + } + if ((row1 == null)) { + return -1; + } + if ((row2 == null)) { + return 1; + } + + int distance1 = 0; + global::System.Data.DataRow root1 = this.GetRoot(row1, out distance1); + + int distance2 = 0; + global::System.Data.DataRow root2 = this.GetRoot(row2, out distance2); + + if (object.ReferenceEquals(root1, root2)) { + return (this._childFirst * distance1.CompareTo(distance2)); + } + else { + global::System.Diagnostics.Debug.Assert(((root1.Table != null) + && (root2.Table != null))); + if ((root1.Table.Rows.IndexOf(root1) < root2.Table.Rows.IndexOf(root2))) { + return -1; + } + else { + return 1; + } + } + } + } + } +} + +#pragma warning restore 1591 \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.cs b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.cs new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.cs @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xsc b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xsc new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xsc @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xsd b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xsd new file mode 100644 index 0000000..5dc0e72 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xsd @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + DELETE FROM [dbo].[Inventory] WHERE (([CarId] = @Original_CarId) AND ((@IsNull_Make = 1 AND [Make] IS NULL) OR ([Make] = @Original_Make)) AND ((@IsNull_Color = 1 AND [Color] IS NULL) OR ([Color] = @Original_Color)) AND ((@IsNull_PetName = 1 AND [PetName] IS NULL) OR ([PetName] = @Original_PetName))) + + + + + + + + + + + + + + INSERT INTO [dbo].[Inventory] ([Make], [Color], [PetName]) VALUES (@Make, @Color, @PetName); +SELECT CarId, Make, Color, PetName FROM Inventory WHERE (CarId = SCOPE_IDENTITY()) + + + + + + + + + + SELECT CarId, Make, Color, PetName FROM dbo.Inventory + + + + + + UPDATE [dbo].[Inventory] SET [Make] = @Make, [Color] = @Color, [PetName] = @PetName WHERE (([CarId] = @Original_CarId) AND ((@IsNull_Make = 1 AND [Make] IS NULL) OR ([Make] = @Original_Make)) AND ((@IsNull_Color = 1 AND [Color] IS NULL) OR ([Color] = @Original_Color)) AND ((@IsNull_PetName = 1 AND [PetName] IS NULL) OR ([PetName] = @Original_PetName))); +SELECT CarId, Make, Color, PetName FROM Inventory WHERE (CarId = @CarId) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xss b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xss new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/InventoryDataSet.xss @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/MainForm.Designer.cs b/Appendix_A/DataGridViewDataDesigner/MainForm.Designer.cs new file mode 100644 index 0000000..e48f24a --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/MainForm.Designer.cs @@ -0,0 +1,142 @@ +namespace DataGridViewDataDesigner +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.inventoryDataGridView = new System.Windows.Forms.DataGridView(); + this.carIdDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.makeDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.colorDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.petNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.inventoryDataSet = new DataGridViewDataDesigner.InventoryDataSet(); + this.inventoryBindingSource = new System.Windows.Forms.BindingSource(this.components); + this.inventoryTableAdapter = new DataGridViewDataDesigner.InventoryDataSetTableAdapters.InventoryTableAdapter(); + this.btnUpdateInventory = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.inventoryDataGridView)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.inventoryDataSet)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.inventoryBindingSource)).BeginInit(); + this.SuspendLayout(); + // + // inventoryDataGridView + // + this.inventoryDataGridView.AutoGenerateColumns = false; + this.inventoryDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.inventoryDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.carIdDataGridViewTextBoxColumn, + this.makeDataGridViewTextBoxColumn, + this.colorDataGridViewTextBoxColumn, + this.petNameDataGridViewTextBoxColumn}); + this.inventoryDataGridView.DataSource = this.inventoryBindingSource; + this.inventoryDataGridView.Location = new System.Drawing.Point(12, 12); + this.inventoryDataGridView.Name = "inventoryDataGridView"; + this.inventoryDataGridView.RowTemplate.Height = 24; + this.inventoryDataGridView.Size = new System.Drawing.Size(762, 355); + this.inventoryDataGridView.TabIndex = 0; + // + // carIdDataGridViewTextBoxColumn + // + this.carIdDataGridViewTextBoxColumn.DataPropertyName = "CarId"; + this.carIdDataGridViewTextBoxColumn.HeaderText = "CarId"; + this.carIdDataGridViewTextBoxColumn.Name = "carIdDataGridViewTextBoxColumn"; + this.carIdDataGridViewTextBoxColumn.ReadOnly = true; + // + // makeDataGridViewTextBoxColumn + // + this.makeDataGridViewTextBoxColumn.DataPropertyName = "Make"; + this.makeDataGridViewTextBoxColumn.HeaderText = "Make"; + this.makeDataGridViewTextBoxColumn.Name = "makeDataGridViewTextBoxColumn"; + // + // colorDataGridViewTextBoxColumn + // + this.colorDataGridViewTextBoxColumn.DataPropertyName = "Color"; + this.colorDataGridViewTextBoxColumn.HeaderText = "Color"; + this.colorDataGridViewTextBoxColumn.Name = "colorDataGridViewTextBoxColumn"; + // + // petNameDataGridViewTextBoxColumn + // + this.petNameDataGridViewTextBoxColumn.DataPropertyName = "PetName"; + this.petNameDataGridViewTextBoxColumn.HeaderText = "PetName"; + this.petNameDataGridViewTextBoxColumn.Name = "petNameDataGridViewTextBoxColumn"; + // + // inventoryDataSet + // + this.inventoryDataSet.DataSetName = "InventoryDataSet"; + this.inventoryDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; + // + // inventoryBindingSource + // + this.inventoryBindingSource.DataMember = "Inventory"; + this.inventoryBindingSource.DataSource = this.inventoryDataSet; + // + // inventoryTableAdapter + // + this.inventoryTableAdapter.ClearBeforeFill = true; + // + // btnUpdateInventory + // + this.btnUpdateInventory.Location = new System.Drawing.Point(674, 374); + this.btnUpdateInventory.Margin = new System.Windows.Forms.Padding(4); + this.btnUpdateInventory.Name = "btnUpdateInventory"; + this.btnUpdateInventory.Size = new System.Drawing.Size(100, 28); + this.btnUpdateInventory.TabIndex = 2; + this.btnUpdateInventory.Text = "Update!"; + this.btnUpdateInventory.UseVisualStyleBackColor = true; + this.btnUpdateInventory.Click += new System.EventHandler(this.btnUpdateInventory_Click); + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(786, 408); + this.Controls.Add(this.btnUpdateInventory); + this.Controls.Add(this.inventoryDataGridView); + this.Name = "MainForm"; + this.Text = "Windows Forms Data Wizards"; + this.Load += new System.EventHandler(this.MainForm_Load); + ((System.ComponentModel.ISupportInitialize)(this.inventoryDataGridView)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.inventoryDataSet)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.inventoryBindingSource)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.DataGridView inventoryDataGridView; + private System.Windows.Forms.DataGridViewTextBoxColumn carIdDataGridViewTextBoxColumn; + private System.Windows.Forms.DataGridViewTextBoxColumn makeDataGridViewTextBoxColumn; + private System.Windows.Forms.DataGridViewTextBoxColumn colorDataGridViewTextBoxColumn; + private System.Windows.Forms.DataGridViewTextBoxColumn petNameDataGridViewTextBoxColumn; + private InventoryDataSet inventoryDataSet; + private System.Windows.Forms.BindingSource inventoryBindingSource; + private InventoryDataSetTableAdapters.InventoryTableAdapter inventoryTableAdapter; + private System.Windows.Forms.Button btnUpdateInventory; + } +} + diff --git a/Appendix_A/DataGridViewDataDesigner/MainForm.cs b/Appendix_A/DataGridViewDataDesigner/MainForm.cs new file mode 100644 index 0000000..dffb3d1 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/MainForm.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace DataGridViewDataDesigner +{ + public partial class MainForm : Form + { + public MainForm() + { + InitializeComponent(); + } + + private void MainForm_Load(object sender, EventArgs e) + { + // TODO: This line of code loads data into the 'inventoryDataSet.Inventory' table. You can move, or remove it, as needed. + this.inventoryTableAdapter.Fill(this.inventoryDataSet.Inventory); + + } + + private void btnUpdateInventory_Click(object sender, EventArgs e) + { + try + { + // Save changes with the Inventory table back to the database. + inventoryTableAdapter.Update(this.inventoryDataSet.Inventory); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + } + // Get fresh copy for grid. + inventoryTableAdapter.Fill(this.inventoryDataSet.Inventory); + } + } +} diff --git a/Appendix_A/DataGridViewDataDesigner/MainForm.resx b/Appendix_A/DataGridViewDataDesigner/MainForm.resx new file mode 100644 index 0000000..f33eef9 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/MainForm.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 187, 18 + + + 13, 18 + + + 13, 18 + + + 414, 18 + + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/Program.cs b/Appendix_A/DataGridViewDataDesigner/Program.cs new file mode 100644 index 0000000..2402b3c --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace DataGridViewDataDesigner +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/Appendix_A/DataGridViewDataDesigner/Properties/AssemblyInfo.cs b/Appendix_A/DataGridViewDataDesigner/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d5cf174 --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DataGridViewDataDesigner")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DataGridViewDataDesigner")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("143de2ee-324a-4cad-982a-a5bc7684dbc0")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/DataGridViewDataDesigner/Properties/Resources.Designer.cs b/Appendix_A/DataGridViewDataDesigner/Properties/Resources.Designer.cs new file mode 100644 index 0000000..8316dca --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DataGridViewDataDesigner.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DataGridViewDataDesigner.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Appendix_A/DataGridViewDataDesigner/Properties/Resources.resx b/Appendix_A/DataGridViewDataDesigner/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_A/DataGridViewDataDesigner/Properties/Settings.Designer.cs b/Appendix_A/DataGridViewDataDesigner/Properties/Settings.Designer.cs new file mode 100644 index 0000000..e81194c --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/Properties/Settings.Designer.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DataGridViewDataDesigner.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] + [global::System.Configuration.DefaultSettingValueAttribute("Data Source=.\\SQLEXPRESS2014;Initial Catalog=AutoLot;Integrated Security=True")] + public string AutoLotConnectionString { + get { + return ((string)(this["AutoLotConnectionString"])); + } + } + } +} diff --git a/Appendix_A/DataGridViewDataDesigner/Properties/Settings.settings b/Appendix_A/DataGridViewDataDesigner/Properties/Settings.settings new file mode 100644 index 0000000..d4e7cbc --- /dev/null +++ b/Appendix_A/DataGridViewDataDesigner/Properties/Settings.settings @@ -0,0 +1,14 @@ + + + + + + <?xml version="1.0" encoding="utf-16"?> +<SerializableConnectionString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <ConnectionString>Data Source=.\SQLEXPRESS2014;Initial Catalog=AutoLot;Integrated Security=True</ConnectionString> + <ProviderName>System.Data.SqlClient</ProviderName> +</SerializableConnectionString> + Data Source=.\SQLEXPRESS2014;Initial Catalog=AutoLot;Integrated Security=True + + + \ No newline at end of file diff --git a/Appendix_A/FillDataSetUsingSqlDataAdapter/App.config b/Appendix_A/FillDataSetUsingSqlDataAdapter/App.config new file mode 100644 index 0000000..8324aa6 --- /dev/null +++ b/Appendix_A/FillDataSetUsingSqlDataAdapter/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_A/FillDataSetUsingSqlDataAdapter/FillDataSetUsingSqlDataAdapter.csproj b/Appendix_A/FillDataSetUsingSqlDataAdapter/FillDataSetUsingSqlDataAdapter.csproj new file mode 100644 index 0000000..15ab848 --- /dev/null +++ b/Appendix_A/FillDataSetUsingSqlDataAdapter/FillDataSetUsingSqlDataAdapter.csproj @@ -0,0 +1,60 @@ + + + + + Debug + AnyCPU + {20549E2F-7B55-4F61-A969-02F7C97DDC7C} + Exe + Properties + FillDataSetUsingSqlDataAdapter + FillDataSetUsingSqlDataAdapter + v4.6 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/FillDataSetUsingSqlDataAdapter/FillDataSetUsingSqlDataAdapter.sln b/Appendix_A/FillDataSetUsingSqlDataAdapter/FillDataSetUsingSqlDataAdapter.sln new file mode 100644 index 0000000..ff00798 --- /dev/null +++ b/Appendix_A/FillDataSetUsingSqlDataAdapter/FillDataSetUsingSqlDataAdapter.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FillDataSetUsingSqlDataAdapter", "FillDataSetUsingSqlDataAdapter.csproj", "{20549E2F-7B55-4F61-A969-02F7C97DDC7C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {20549E2F-7B55-4F61-A969-02F7C97DDC7C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {20549E2F-7B55-4F61-A969-02F7C97DDC7C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {20549E2F-7B55-4F61-A969-02F7C97DDC7C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {20549E2F-7B55-4F61-A969-02F7C97DDC7C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/FillDataSetUsingSqlDataAdapter/Program.cs b/Appendix_A/FillDataSetUsingSqlDataAdapter/Program.cs new file mode 100644 index 0000000..13f6881 --- /dev/null +++ b/Appendix_A/FillDataSetUsingSqlDataAdapter/Program.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using static System.Console; + +namespace FillDataSetUsingSqlDataAdapter +{ + class Program + { + static void Main(string[] args) + { + WriteLine("***** Fun with Data Adapters *****\n"); + + // Hard-coded connection string. + string connectionString = "Integrated Security = SSPI;Initial Catalog=AutoLot;" + + @"Data Source=(local)\SQLEXPRESS2014"; + + // Caller creates the DataSet object. + DataSet ds = new DataSet("AutoLot"); + + // Inform adapter of the Select command text and connection. + SqlDataAdapter adapter = + new SqlDataAdapter("Select * From Inventory", connectionString); + + // Now map DB column names to user-friendly names. + DataTableMapping tableMapping = + adapter.TableMappings.Add("Inventory", "Current Inventory"); + tableMapping.ColumnMappings.Add("CarId", "Car Id"); + tableMapping.ColumnMappings.Add("PetName", "Name of Car"); + adapter.Fill(ds, "Inventory"); + + // Display contents of DataSet. + PrintDataSet(ds); + ReadLine(); + } + static void PrintDataSet(DataSet ds) + { + // Print out any name and extended properties. + WriteLine($"DataSet is named: {ds.DataSetName}"); + foreach (DictionaryEntry de in ds.ExtendedProperties) + { + WriteLine($"Key = {de.Key}, Value = {de.Value}"); + } + WriteLine(); + + foreach (DataTable dt in ds.Tables) + { + WriteLine($"=> {dt.TableName} Table:"); + + // Print out the column names. + for (int curCol = 0; curCol < dt.Columns.Count; curCol++) + { + Write(dt.Columns[curCol].ColumnName + "\t"); + } + WriteLine("\n----------------------------------"); + + // Print the DataTable. + for (int curRow = 0; curRow < dt.Rows.Count; curRow++) + { + for (int curCol = 0; curCol < dt.Columns.Count; curCol++) + { + Write(dt.Rows[curRow][curCol].ToString().Trim() + "\t"); + } + WriteLine(); + } + } + } + + } +} diff --git a/Appendix_A/FillDataSetUsingSqlDataAdapter/Properties/AssemblyInfo.cs b/Appendix_A/FillDataSetUsingSqlDataAdapter/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e5f540b --- /dev/null +++ b/Appendix_A/FillDataSetUsingSqlDataAdapter/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("FillDataSetUsingSqlDataAdapter")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FillDataSetUsingSqlDataAdapter")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("20549e2f-7b55-4f61-a969-02f7c97ddc7c")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/InventoryDALDisconnectedGUI/App.config b/Appendix_A/InventoryDALDisconnectedGUI/App.config new file mode 100644 index 0000000..8324aa6 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_A/InventoryDALDisconnectedGUI/InventoryDALDisconnectedGUI.csproj b/Appendix_A/InventoryDALDisconnectedGUI/InventoryDALDisconnectedGUI.csproj new file mode 100644 index 0000000..b0afd7d --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/InventoryDALDisconnectedGUI.csproj @@ -0,0 +1,96 @@ + + + + + Debug + AnyCPU + {E5A9A945-F792-44FF-A5FE-61CEB0072284} + WinExe + Properties + InventoryDALDisconnectedGUI + InventoryDALDisconnectedGUI + v4.6 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + MainForm.cs + + + + + MainForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {0447cd8f-ee61-425d-a04f-f56468c8890a} + AutoLotDAL2 + + + + + \ No newline at end of file diff --git a/Appendix_A/InventoryDALDisconnectedGUI/InventoryDALDisconnectedGUI.sln b/Appendix_A/InventoryDALDisconnectedGUI/InventoryDALDisconnectedGUI.sln new file mode 100644 index 0000000..f517815 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/InventoryDALDisconnectedGUI.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryDALDisconnectedGUI", "InventoryDALDisconnectedGUI.csproj", "{E5A9A945-F792-44FF-A5FE-61CEB0072284}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL2", "..\AutoLotDAL2\AutoLotDAL2.csproj", "{0447CD8F-EE61-425D-A04F-F56468C8890A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E5A9A945-F792-44FF-A5FE-61CEB0072284}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E5A9A945-F792-44FF-A5FE-61CEB0072284}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E5A9A945-F792-44FF-A5FE-61CEB0072284}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E5A9A945-F792-44FF-A5FE-61CEB0072284}.Release|Any CPU.Build.0 = Release|Any CPU + {0447CD8F-EE61-425D-A04F-F56468C8890A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0447CD8F-EE61-425D-A04F-F56468C8890A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0447CD8F-EE61-425D-A04F-F56468C8890A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0447CD8F-EE61-425D-A04F-F56468C8890A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/InventoryDALDisconnectedGUI/MainForm.Designer.cs b/Appendix_A/InventoryDALDisconnectedGUI/MainForm.Designer.cs new file mode 100644 index 0000000..a740622 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/MainForm.Designer.cs @@ -0,0 +1,91 @@ +namespace InventoryDALDisconnectedGUI +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.lblInstructions = new System.Windows.Forms.Label(); + this.inventoryGrid = new System.Windows.Forms.DataGridView(); + this.btnUpdateInventory = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.inventoryGrid)).BeginInit(); + this.SuspendLayout(); + // + // lblInstructions + // + this.lblInstructions.AutoSize = true; + this.lblInstructions.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblInstructions.Location = new System.Drawing.Point(13, 9); + this.lblInstructions.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.lblInstructions.Name = "lblInstructions"; + this.lblInstructions.Size = new System.Drawing.Size(271, 29); + this.lblInstructions.TabIndex = 3; + this.lblInstructions.Text = "Please Edit the Data..."; + // + // inventoryGrid + // + this.inventoryGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.inventoryGrid.Location = new System.Drawing.Point(13, 44); + this.inventoryGrid.Margin = new System.Windows.Forms.Padding(4); + this.inventoryGrid.Name = "inventoryGrid"; + this.inventoryGrid.Size = new System.Drawing.Size(740, 218); + this.inventoryGrid.TabIndex = 2; + // + // btnUpdateInventory + // + this.btnUpdateInventory.Location = new System.Drawing.Point(653, 270); + this.btnUpdateInventory.Margin = new System.Windows.Forms.Padding(4); + this.btnUpdateInventory.Name = "btnUpdateInventory"; + this.btnUpdateInventory.Size = new System.Drawing.Size(100, 28); + this.btnUpdateInventory.TabIndex = 4; + this.btnUpdateInventory.Text = "Update!"; + this.btnUpdateInventory.UseVisualStyleBackColor = true; + this.btnUpdateInventory.Click += new System.EventHandler(this.btnUpdateInventory_Click); + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(755, 305); + this.Controls.Add(this.btnUpdateInventory); + this.Controls.Add(this.lblInstructions); + this.Controls.Add(this.inventoryGrid); + this.Name = "MainForm"; + this.Text = "Simple GUI Front End to the Inventory Table"; + ((System.ComponentModel.ISupportInitialize)(this.inventoryGrid)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label lblInstructions; + private System.Windows.Forms.DataGridView inventoryGrid; + private System.Windows.Forms.Button btnUpdateInventory; + } +} + diff --git a/Appendix_A/InventoryDALDisconnectedGUI/MainForm.cs b/Appendix_A/InventoryDALDisconnectedGUI/MainForm.cs new file mode 100644 index 0000000..2fc7792 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/MainForm.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using AutoLotDAL2.DisconnectedLayer; + +namespace InventoryDALDisconnectedGUI +{ + public partial class MainForm : Form + { + private InventoryDALDC _dal = null; + public MainForm() + { + InitializeComponent(); + string connectionString = + @"Data Source=(local)\SQLEXPRESS2014;Initial Catalog=AutoLot;" + + "Integrated Security=True;Pooling=False"; + + // Create our data access object. + _dal = new InventoryDALDC(connectionString); + + // Fill up our grid! + inventoryGrid.DataSource = _dal.GetAllInventory(); + + } + + private void btnUpdateInventory_Click(object sender, EventArgs e) + { + // Get modified data from the grid. + DataTable changedDT = (DataTable)inventoryGrid.DataSource; + try + { + // Commit our changes. + _dal.UpdateInventory(changedDT); + inventoryGrid.DataSource = _dal.GetAllInventory(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + } + + } + } +} diff --git a/Appendix_A/InventoryDALDisconnectedGUI/MainForm.resx b/Appendix_A/InventoryDALDisconnectedGUI/MainForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/MainForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_A/InventoryDALDisconnectedGUI/Program.cs b/Appendix_A/InventoryDALDisconnectedGUI/Program.cs new file mode 100644 index 0000000..d076fce --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace InventoryDALDisconnectedGUI +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/Appendix_A/InventoryDALDisconnectedGUI/Properties/AssemblyInfo.cs b/Appendix_A/InventoryDALDisconnectedGUI/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7f3a3e9 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("InventoryDALDisconnectedGUI")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("InventoryDALDisconnectedGUI")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e5a9a945-f792-44ff-a5fe-61ceb0072284")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/InventoryDALDisconnectedGUI/Properties/Resources.Designer.cs b/Appendix_A/InventoryDALDisconnectedGUI/Properties/Resources.Designer.cs new file mode 100644 index 0000000..cbdea93 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace InventoryDALDisconnectedGUI.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("InventoryDALDisconnectedGUI.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Appendix_A/InventoryDALDisconnectedGUI/Properties/Resources.resx b/Appendix_A/InventoryDALDisconnectedGUI/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_A/InventoryDALDisconnectedGUI/Properties/Settings.Designer.cs b/Appendix_A/InventoryDALDisconnectedGUI/Properties/Settings.Designer.cs new file mode 100644 index 0000000..fce58f6 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace InventoryDALDisconnectedGUI.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Appendix_A/InventoryDALDisconnectedGUI/Properties/Settings.settings b/Appendix_A/InventoryDALDisconnectedGUI/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/Appendix_A/InventoryDALDisconnectedGUI/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Appendix_A/LinqToDataSetApp/App.config b/Appendix_A/LinqToDataSetApp/App.config new file mode 100644 index 0000000..8324aa6 --- /dev/null +++ b/Appendix_A/LinqToDataSetApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_A/LinqToDataSetApp/LinqToDataSetApp.csproj b/Appendix_A/LinqToDataSetApp/LinqToDataSetApp.csproj new file mode 100644 index 0000000..71774d1 --- /dev/null +++ b/Appendix_A/LinqToDataSetApp/LinqToDataSetApp.csproj @@ -0,0 +1,66 @@ + + + + + Debug + AnyCPU + {BCEC1973-121B-42D9-9401-2A5013F2C1A8} + Exe + Properties + LinqToDataSetApp + LinqToDataSetApp + v4.6 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + {732ccd23-b8e3-479e-845d-d082490f58d9} + AutoLotDAL3 + + + + + \ No newline at end of file diff --git a/Appendix_A/LinqToDataSetApp/LinqToDataSetApp.sln b/Appendix_A/LinqToDataSetApp/LinqToDataSetApp.sln new file mode 100644 index 0000000..0937856 --- /dev/null +++ b/Appendix_A/LinqToDataSetApp/LinqToDataSetApp.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqToDataSetApp", "LinqToDataSetApp.csproj", "{BCEC1973-121B-42D9-9401-2A5013F2C1A8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL3", "..\AutoLotDAL3\AutoLotDAL3.csproj", "{732CCD23-B8E3-479E-845D-D082490F58D9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BCEC1973-121B-42D9-9401-2A5013F2C1A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BCEC1973-121B-42D9-9401-2A5013F2C1A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BCEC1973-121B-42D9-9401-2A5013F2C1A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BCEC1973-121B-42D9-9401-2A5013F2C1A8}.Release|Any CPU.Build.0 = Release|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/LinqToDataSetApp/Program.cs b/Appendix_A/LinqToDataSetApp/Program.cs new file mode 100644 index 0000000..0d3fb1f --- /dev/null +++ b/Appendix_A/LinqToDataSetApp/Program.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL3.DataSets; +using AutoLotDAL3.DataSets.AutoLotDataSetTableAdapters; +using static System.Console; + +namespace LinqToDataSetApp +{ + class Program + { + static void Main(string[] args) + { + WriteLine("***** LINQ over DataSet *****\n"); + + // Get a strongly typed DataTable containing the current Inventory + // of the AutoLot database. + AutoLotDataSet dal = new AutoLotDataSet(); + InventoryTableAdapter tableAdapter = new InventoryTableAdapter(); + AutoLotDataSet.InventoryDataTable data = tableAdapter.GetData(); + + // Print all car ids. + PrintAllCarIDs(data); + WriteLine(); + + // Show all red cars. + ShowRedCars(data); + WriteLine(); + + BuildDataTableFromQuery(data); + WriteLine(); + + ReadLine(); + + } + static void PrintAllCarIDs(DataTable data) + { + // Get enumerable version of DataTable. + EnumerableRowCollection enumData = data.AsEnumerable(); + + // Print the car ID values. + foreach (DataRow r in enumData) + { + WriteLine($"Car ID = {r["CarID"]}"); + } + } + static void ShowRedCars(DataTable data) + { + // Project a new result set containing + // the ID/Make for rows where Color == Red. + var cars = from car in data.AsEnumerable() + where + car.Field("Color") == "Black" + select new + { + ID = car.Field("CarID"), + Make = car.Field("Make") + }; + + + WriteLine("Here are the red cars we have in stock:"); + foreach (var item in cars) + { + WriteLine($"-> CarID = {item.ID} is {item.Make}"); + } + } + static void BuildDataTableFromQuery(DataTable data) + { + var cars = from car in data.AsEnumerable() + where car.Field("CarID") > 5 + select car; + + // Use this result set to build a new DataTable. + DataTable newTable = cars.CopyToDataTable(); + + // Print the DataTable. + for (var curRow = 0; curRow < newTable.Rows.Count; curRow++) + { + for (var curCol = 0; curCol < newTable.Columns.Count; curCol++) + { + Write(newTable.Rows[curRow][curCol].ToString().Trim() + "\t"); + } + WriteLine(); + } + } + + } +} diff --git a/Appendix_A/LinqToDataSetApp/Properties/AssemblyInfo.cs b/Appendix_A/LinqToDataSetApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9bdac68 --- /dev/null +++ b/Appendix_A/LinqToDataSetApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LinqToDataSetApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LinqToDataSetApp")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("bcec1973-121b-42d9-9401-2a5013f2c1a8")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/MultitabledDataSetApp/App.config b/Appendix_A/MultitabledDataSetApp/App.config new file mode 100644 index 0000000..79e767d --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/App.config @@ -0,0 +1,10 @@ + + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/MultitabledDataSetApp/MainForm.Designer.cs b/Appendix_A/MultitabledDataSetApp/MainForm.Designer.cs new file mode 100644 index 0000000..0d1c37f --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/MainForm.Designer.cs @@ -0,0 +1,197 @@ +namespace MultitabledDataSetApp +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.btnUpdateDatabase = new System.Windows.Forms.Button(); + this.label3 = new System.Windows.Forms.Label(); + this.dataGridViewOrders = new System.Windows.Forms.DataGridView(); + this.label2 = new System.Windows.Forms.Label(); + this.dataGridViewCustomers = new System.Windows.Forms.DataGridView(); + this.label1 = new System.Windows.Forms.Label(); + this.dataGridViewInventory = new System.Windows.Forms.DataGridView(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.btnGetOrderInfo = new System.Windows.Forms.Button(); + this.label4 = new System.Windows.Forms.Label(); + this.txtCustID = new System.Windows.Forms.TextBox(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridViewOrders)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridViewCustomers)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridViewInventory)).BeginInit(); + this.groupBox1.SuspendLayout(); + this.SuspendLayout(); + // + // btnUpdateDatabase + // + this.btnUpdateDatabase.Location = new System.Drawing.Point(540, 434); + this.btnUpdateDatabase.Margin = new System.Windows.Forms.Padding(4); + this.btnUpdateDatabase.Name = "btnUpdateDatabase"; + this.btnUpdateDatabase.Size = new System.Drawing.Size(152, 28); + this.btnUpdateDatabase.TabIndex = 13; + this.btnUpdateDatabase.Text = "Update Database"; + this.btnUpdateDatabase.Click += new System.EventHandler(this.btnUpdateDatabase_Click); + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(13, 285); + this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(103, 17); + this.label3.TabIndex = 12; + this.label3.Text = "Current Orders"; + // + // dataGridViewOrders + // + this.dataGridViewOrders.Location = new System.Drawing.Point(14, 310); + this.dataGridViewOrders.Margin = new System.Windows.Forms.Padding(4); + this.dataGridViewOrders.Name = "dataGridViewOrders"; + this.dataGridViewOrders.Size = new System.Drawing.Size(679, 111); + this.dataGridViewOrders.TabIndex = 11; + this.dataGridViewOrders.Text = "dataGridView3"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(13, 140); + this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(126, 17); + this.label2.TabIndex = 10; + this.label2.Text = "Current Customers"; + // + // dataGridViewCustomers + // + this.dataGridViewCustomers.Location = new System.Drawing.Point(14, 165); + this.dataGridViewCustomers.Margin = new System.Windows.Forms.Padding(4); + this.dataGridViewCustomers.Name = "dataGridViewCustomers"; + this.dataGridViewCustomers.Size = new System.Drawing.Size(679, 111); + this.dataGridViewCustomers.TabIndex = 9; + this.dataGridViewCustomers.Text = "dataGridView2"; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 7); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(117, 17); + this.label1.TabIndex = 8; + this.label1.Text = "Current Inventory"; + // + // dataGridViewInventory + // + this.dataGridViewInventory.Location = new System.Drawing.Point(13, 32); + this.dataGridViewInventory.Margin = new System.Windows.Forms.Padding(4); + this.dataGridViewInventory.Name = "dataGridViewInventory"; + this.dataGridViewInventory.Size = new System.Drawing.Size(679, 101); + this.dataGridViewInventory.TabIndex = 7; + this.dataGridViewInventory.Text = "dataGridView1"; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.btnGetOrderInfo); + this.groupBox1.Controls.Add(this.label4); + this.groupBox1.Controls.Add(this.txtCustID); + this.groupBox1.Location = new System.Drawing.Point(13, 429); + this.groupBox1.Margin = new System.Windows.Forms.Padding(4); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Padding = new System.Windows.Forms.Padding(4); + this.groupBox1.Size = new System.Drawing.Size(267, 123); + this.groupBox1.TabIndex = 14; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "Lookup Customer Order"; + // + // btnGetOrderInfo + // + this.btnGetOrderInfo.Location = new System.Drawing.Point(112, 87); + this.btnGetOrderInfo.Margin = new System.Windows.Forms.Padding(4); + this.btnGetOrderInfo.Name = "btnGetOrderInfo"; + this.btnGetOrderInfo.Size = new System.Drawing.Size(147, 28); + this.btnGetOrderInfo.TabIndex = 7; + this.btnGetOrderInfo.Text = "Get Order Details"; + this.btnGetOrderInfo.Click += new System.EventHandler(this.btnGetOrderInfo_Click); + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(13, 36); + this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(89, 17); + this.label4.TabIndex = 9; + this.label4.Text = "Customer ID:"; + // + // txtCustID + // + this.txtCustID.Location = new System.Drawing.Point(112, 36); + this.txtCustID.Margin = new System.Windows.Forms.Padding(4); + this.txtCustID.Name = "txtCustID"; + this.txtCustID.Size = new System.Drawing.Size(145, 22); + this.txtCustID.TabIndex = 8; + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(704, 559); + this.Controls.Add(this.groupBox1); + this.Controls.Add(this.btnUpdateDatabase); + this.Controls.Add(this.label3); + this.Controls.Add(this.dataGridViewOrders); + this.Controls.Add(this.label2); + this.Controls.Add(this.dataGridViewCustomers); + this.Controls.Add(this.label1); + this.Controls.Add(this.dataGridViewInventory); + this.Name = "MainForm"; + this.Text = "AutoLot Database Manipulator"; + ((System.ComponentModel.ISupportInitialize)(this.dataGridViewOrders)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridViewCustomers)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridViewInventory)).EndInit(); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnUpdateDatabase; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.DataGridView dataGridViewOrders; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.DataGridView dataGridViewCustomers; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.DataGridView dataGridViewInventory; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.Button btnGetOrderInfo; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.TextBox txtCustID; + } +} + diff --git a/Appendix_A/MultitabledDataSetApp/MainForm.cs b/Appendix_A/MultitabledDataSetApp/MainForm.cs new file mode 100644 index 0000000..3580248 --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/MainForm.cs @@ -0,0 +1,119 @@ +using System; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.Windows.Forms; + +namespace MultitabledDataSetApp +{ + public partial class MainForm : Form + { + // Form wide DataSet. + private DataSet _autoLotDs = new DataSet("AutoLot"); + + // Make use of command builders to simplify data adapter configuration. + private SqlCommandBuilder _sqlCbInventory; + private SqlCommandBuilder _sqlCbCustomers; + private SqlCommandBuilder _sqlCbOrders; + + // Our data adapters (for each table). + private SqlDataAdapter _invTableAdapter; + private SqlDataAdapter _custTableAdapter; + private SqlDataAdapter _ordersTableAdapter; + + // Form wide connection string. + private string _connectionString; + + public MainForm() + { + InitializeComponent(); + + // Get connection string. + _connectionString = + ConfigurationManager.ConnectionStrings["AutoLotSqlProvider"].ConnectionString; + + // Create adapters. + _invTableAdapter = new SqlDataAdapter("Select * from Inventory", _connectionString); + _custTableAdapter = new SqlDataAdapter("Select * from Customers", _connectionString); + _ordersTableAdapter = new SqlDataAdapter("Select * from Orders", _connectionString); + + // Autogenerate commands. + _sqlCbInventory = new SqlCommandBuilder(_invTableAdapter); + _sqlCbOrders = new SqlCommandBuilder(_ordersTableAdapter); + _sqlCbCustomers = new SqlCommandBuilder(_custTableAdapter); + + // Fill tables in DataSet. + _invTableAdapter.Fill(_autoLotDs, "Inventory"); + _custTableAdapter.Fill(_autoLotDs, "Customers"); + _ordersTableAdapter.Fill(_autoLotDs, "Orders"); + + // Build relations between tables. + BuildTableRelationship(); + + // Bind to grids + dataGridViewInventory.DataSource = _autoLotDs.Tables["Inventory"]; + dataGridViewCustomers.DataSource = _autoLotDs.Tables["Customers"]; + dataGridViewOrders.DataSource = _autoLotDs.Tables["Orders"]; + } + private void BuildTableRelationship() + { + // Create CustomerOrder data relation object. + DataRelation dr = new DataRelation("CustomerOrder", + _autoLotDs.Tables["Customers"].Columns["CustID"], + _autoLotDs.Tables["Orders"].Columns["CustID"]); + _autoLotDs.Relations.Add(dr); + + // Create InventoryOrder data relation object. + dr = new DataRelation("InventoryOrder", + _autoLotDs.Tables["Inventory"].Columns["CarID"], + _autoLotDs.Tables["Orders"].Columns["CarID"]); + _autoLotDs.Relations.Add(dr); + } + + private void btnUpdateDatabase_Click(object sender, System.EventArgs e) + { + try + { + _invTableAdapter.Update(_autoLotDs, "Inventory"); + _custTableAdapter.Update(_autoLotDs, "Customers"); + _ordersTableAdapter.Update(_autoLotDs, "Orders"); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + } + } + + private void btnGetOrderInfo_Click(object sender, EventArgs e) + { + string strOrderInfo = string.Empty; + + // Get the customer ID in the text box. + int custID = int.Parse(txtCustID.Text); + + // Now based on custID, get the correct row in Customers table. + var drsCust = _autoLotDs.Tables["Customers"].Select($"CustID = {custID}"); + strOrderInfo += + $"Customer {drsCust[0]["CustID"]}: {drsCust[0]["FirstName"].ToString().Trim()} {drsCust[0]["LastName"].ToString().Trim()}\n"; + + // Navigate from customer table to order table. + var drsOrder = drsCust[0].GetChildRows(_autoLotDs.Relations["CustomerOrder"]); + + // Loop through all orders for this customer. + foreach (DataRow order in drsOrder) + { + strOrderInfo += $"----\nOrder Number: {order["OrderID"]}\n"; + + // Get the car referenced by this order. + DataRow[] drsInv = order.GetParentRows(_autoLotDs.Relations["InventoryOrder"]); + + // Get info for (SINGLE) car info for this order. + DataRow car = drsInv[0]; + strOrderInfo += $"Make: {car["Make"]}\n"; + strOrderInfo += $"Color: {car["Color"]}\n"; + strOrderInfo += $"Pet Name: {car["PetName"]}\n"; + } + MessageBox.Show(strOrderInfo, "Order Details"); + } + } +} diff --git a/Appendix_A/MultitabledDataSetApp/MainForm.resx b/Appendix_A/MultitabledDataSetApp/MainForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/MainForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_A/MultitabledDataSetApp/MultitabledDataSetApp.csproj b/Appendix_A/MultitabledDataSetApp/MultitabledDataSetApp.csproj new file mode 100644 index 0000000..24d4769 --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/MultitabledDataSetApp.csproj @@ -0,0 +1,91 @@ + + + + + Debug + AnyCPU + {EACB32FA-3076-4FDC-9AE8-79BBEEBCDBDF} + WinExe + Properties + MultitabledDataSetApp + MultitabledDataSetApp + v4.6 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + Form + + + MainForm.cs + + + + + MainForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/MultitabledDataSetApp/MultitabledDataSetApp.sln b/Appendix_A/MultitabledDataSetApp/MultitabledDataSetApp.sln new file mode 100644 index 0000000..5c09bbd --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/MultitabledDataSetApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultitabledDataSetApp", "MultitabledDataSetApp.csproj", "{EACB32FA-3076-4FDC-9AE8-79BBEEBCDBDF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EACB32FA-3076-4FDC-9AE8-79BBEEBCDBDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EACB32FA-3076-4FDC-9AE8-79BBEEBCDBDF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EACB32FA-3076-4FDC-9AE8-79BBEEBCDBDF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EACB32FA-3076-4FDC-9AE8-79BBEEBCDBDF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/MultitabledDataSetApp/Program.cs b/Appendix_A/MultitabledDataSetApp/Program.cs new file mode 100644 index 0000000..9ea9313 --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MultitabledDataSetApp +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/Appendix_A/MultitabledDataSetApp/Properties/AssemblyInfo.cs b/Appendix_A/MultitabledDataSetApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..fcd4db9 --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MultitabledDataSetApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MultitabledDataSetApp")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("eacb32fa-3076-4fdc-9ae8-79bbeebcdbdf")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/MultitabledDataSetApp/Properties/Resources.Designer.cs b/Appendix_A/MultitabledDataSetApp/Properties/Resources.Designer.cs new file mode 100644 index 0000000..64f9dbb --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace MultitabledDataSetApp.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MultitabledDataSetApp.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Appendix_A/MultitabledDataSetApp/Properties/Resources.resx b/Appendix_A/MultitabledDataSetApp/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_A/MultitabledDataSetApp/Properties/Settings.Designer.cs b/Appendix_A/MultitabledDataSetApp/Properties/Settings.Designer.cs new file mode 100644 index 0000000..1c74a98 --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace MultitabledDataSetApp.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Appendix_A/MultitabledDataSetApp/Properties/Settings.settings b/Appendix_A/MultitabledDataSetApp/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/Appendix_A/MultitabledDataSetApp/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Appendix_A/SimpleDataSet/App.config b/Appendix_A/SimpleDataSet/App.config new file mode 100644 index 0000000..8324aa6 --- /dev/null +++ b/Appendix_A/SimpleDataSet/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_A/SimpleDataSet/Program.cs b/Appendix_A/SimpleDataSet/Program.cs new file mode 100644 index 0000000..359e8ee --- /dev/null +++ b/Appendix_A/SimpleDataSet/Program.cs @@ -0,0 +1,205 @@ +using System; +using System.Collections; +using System.Data; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; +using static System.Console; + +namespace SimpleDataSet +{ + internal class Program + { + private static void Main(string[] args) + { + WriteLine("***** Fun with DataSets *****\n"); + + // Create the DataSet object and add a few properties. + var carsInventoryDS = new DataSet("Car Inventory"); + + carsInventoryDS.ExtendedProperties["TimeStamp"] = DateTime.Now; + carsInventoryDS.ExtendedProperties["DataSetID"] = Guid.NewGuid(); + carsInventoryDS.ExtendedProperties["Company"] = + "Mikko’s Hot Tub Super Store"; + + FillDataSet(carsInventoryDS); + PrintDataSet(carsInventoryDS); + SaveAndLoadAsXml(carsInventoryDS); + SaveAndLoadAsBinary(carsInventoryDS); + ReadLine(); + + } + private static void FillDataSet(DataSet ds) + { + // Create data columns that map to the + // 'real' columns in the Inventory table + // of the AutoLot database. + var carIDColumn = new DataColumn("CarID", typeof(int)) + { + Caption = "Car ID", + ReadOnly = true, + AllowDBNull = false, + Unique = true, + AutoIncrement = true, + AutoIncrementSeed = 1, + AutoIncrementStep = 1 + }; + + var carMakeColumn = new DataColumn("Make", typeof(string)); + var carColorColumn = new DataColumn("Color", typeof(string)); + var carPetNameColumn = new DataColumn("PetName", typeof(string)) + { Caption = "Pet Name" }; + + // Now add DataColumns to a DataTable. + var inventoryTable = new DataTable("Inventory"); + inventoryTable.Columns.AddRange(new[] + {carIDColumn, carMakeColumn, carColorColumn, carPetNameColumn}); + + // Now add some rows to the Inventory Table. + DataRow carRow = inventoryTable.NewRow(); + carRow["Make"] = "BMW"; + carRow["Color"] = "Black"; + carRow["PetName"] = "Hamlet"; + inventoryTable.Rows.Add(carRow); + + carRow = inventoryTable.NewRow(); + // Column 0 is the autoincremented ID field, + // so start at 1. + carRow[1] = "Saab"; + carRow[2] = "Red"; + carRow[3] = "Sea Breeze"; + inventoryTable.Rows.Add(carRow); + + // Mark the primary key of this table. + inventoryTable.PrimaryKey = new[] { inventoryTable.Columns[0] }; + + // Finally, add our table to the DataSet. + ds.Tables.Add(inventoryTable); + } + private static void ManipulateDataRowState() + { + // Create a temp DataTable for testing. + var temp = new DataTable("Temp"); + temp.Columns.Add(new DataColumn("TempColumn", typeof(int))); + + // RowState = Detached. + var row = temp.NewRow(); + WriteLine($"After calling NewRow(): {row.RowState}"); + + // RowState = Added. + temp.Rows.Add(row); + WriteLine($"After calling Rows.Add(): {row.RowState}"); + + // RowState = Added. + row["TempColumn"] = 10; + WriteLine($"After first assignment: {row.RowState}"); + + // RowState = Unchanged. + temp.AcceptChanges(); + WriteLine($"After calling AcceptChanges: {row.RowState}"); + + // RowState = Modified. + row["TempColumn"] = 11; + WriteLine($"After first assignment: {row.RowState}"); + + // RowState = Deleted. + temp.Rows[0].Delete(); + WriteLine($"After calling Delete: {row.RowState}"); + } + + static void PrintDataSet(DataSet ds) + { + // Print out any name and extended properties. + WriteLine($"DataSet is named: {ds.DataSetName}"); + foreach (DictionaryEntry de in ds.ExtendedProperties) + { + WriteLine($"Key = {de.Key}, Value = {de.Value}"); + } + WriteLine(); + + //Print out each table using rows and columns + //foreach (DataTable dt in ds.Tables) + //{ + // WriteLine($"=> {dt.TableName} Table:"); + + // // Print out the column names. + // for (var curCol = 0; curCol < dt.Columns.Count; curCol++) + // { + // Write($"{dt.Columns[curCol].ColumnName}\t"); + // } + // WriteLine("\n----------------------------------"); + + // // Print the DataTable. + // for (var curRow = 0; curRow < dt.Rows.Count; curRow++) + // { + // for (var curCol = 0; curCol < dt.Columns.Count; curCol++) + // { + // Write($"{dt.Rows[curRow][curCol]}\t"); + // } + // WriteLine(); + // } + //} + + //Print out each table using data reader + foreach (DataTable dt in ds.Tables) + { + WriteLine($"=> {dt.TableName} Table:"); + + // Print out the column names. + for (int curCol = 0; curCol < dt.Columns.Count; curCol++) + { + Write($"{dt.Columns[curCol].ColumnName.Trim()}\t"); + } + WriteLine("\n----------------------------------"); + + // Call our new helper method. + PrintTable(dt); + } + } + static void PrintTable(DataTable dt) + { + // Get the DataTableReader type. + DataTableReader dtReader = dt.CreateDataReader(); + + // The DataTableReader works just like the DataReader. + while (dtReader.Read()) + { + for (var i = 0; i < dtReader.FieldCount; i++) + { + Write($"{dtReader.GetValue(i).ToString().Trim()}\t"); + } + WriteLine(); + } + dtReader.Close(); + } + static void SaveAndLoadAsXml(DataSet carsInventoryDS) + { + // Save this DataSet as XML. + carsInventoryDS.WriteXml("carsDataSet.xml"); + carsInventoryDS.WriteXmlSchema("carsDataSet.xsd"); + + // Clear out DataSet. + carsInventoryDS.Clear(); + + // Load DataSet from XML file. + carsInventoryDS.ReadXml("carsDataSet.xml"); + } + static void SaveAndLoadAsBinary(DataSet carsInventoryDS) + { + // Set binary serialization flag. + carsInventoryDS.RemotingFormat = SerializationFormat.Binary; + + // Save this DataSet as binary. + var fs = new FileStream("BinaryCars.bin", FileMode.Create); + var bFormat = new BinaryFormatter(); + bFormat.Serialize(fs, carsInventoryDS); + fs.Close(); + + // Clear out DataSet. + carsInventoryDS.Clear(); + + // Load DataSet from binary file. + fs = new FileStream("BinaryCars.bin", FileMode.Open); + var data = (DataSet)bFormat.Deserialize(fs); + } + } +} diff --git a/Appendix_A/SimpleDataSet/Properties/AssemblyInfo.cs b/Appendix_A/SimpleDataSet/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..668b72f --- /dev/null +++ b/Appendix_A/SimpleDataSet/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("App1")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("App1")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c4d97a3e-6586-4a88-a1d0-af586596d48e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/SimpleDataSet/SimpleDataSet.csproj b/Appendix_A/SimpleDataSet/SimpleDataSet.csproj new file mode 100644 index 0000000..2109cba --- /dev/null +++ b/Appendix_A/SimpleDataSet/SimpleDataSet.csproj @@ -0,0 +1,60 @@ + + + + + Debug + AnyCPU + {C4D97A3E-6586-4A88-A1D0-AF586596D48E} + Exe + Properties + SimpleDataSet + SimpleDataSet + v4.6 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/SimpleDataSet/SimpleDataSet.sln b/Appendix_A/SimpleDataSet/SimpleDataSet.sln new file mode 100644 index 0000000..5a1c996 --- /dev/null +++ b/Appendix_A/SimpleDataSet/SimpleDataSet.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleDataSet", "SimpleDataSet.csproj", "{C4D97A3E-6586-4A88-A1D0-AF586596D48E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C4D97A3E-6586-4A88-A1D0-AF586596D48E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C4D97A3E-6586-4A88-A1D0-AF586596D48E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C4D97A3E-6586-4A88-A1D0-AF586596D48E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C4D97A3E-6586-4A88-A1D0-AF586596D48E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/StronglyTypedDataSetConsoleClient/App.config b/Appendix_A/StronglyTypedDataSetConsoleClient/App.config new file mode 100644 index 0000000..8324aa6 --- /dev/null +++ b/Appendix_A/StronglyTypedDataSetConsoleClient/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_A/StronglyTypedDataSetConsoleClient/Program.cs b/Appendix_A/StronglyTypedDataSetConsoleClient/Program.cs new file mode 100644 index 0000000..64ac290 --- /dev/null +++ b/Appendix_A/StronglyTypedDataSetConsoleClient/Program.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL3.DataSets; +using AutoLotDAL3.DataSets.AutoLotDataSetTableAdapters; +using static System.Console; + +namespace StronglyTypedDataSetConsoleClient +{ + class Program + { + static void Main(string[] args) + { + WriteLine("***** Fun with Strongly Typed DataSets *****\n"); + + // Caller creates the DataSet object. + var table = new AutoLotDataSet.InventoryDataTable(); + + // Inform adapter of the Select command text and connection. + var adapter = new InventoryTableAdapter(); + + // Fill our DataSet with a new table, named Inventory. + adapter.Fill(table); + PrintInventory(table); + WriteLine(); + + // Add rows, update and reprint. + AddRecords(table, adapter); + table.Clear(); + adapter.Fill(table); + PrintInventory(table); + WriteLine(); + + // Remove rows we just made and reprint. + RemoveRecords(table, adapter); + table.Clear(); + adapter.Fill(table); + PrintInventory(table); + WriteLine(); + + CallStoredProc(); + ReadLine(); + + } + static void PrintInventory(AutoLotDataSet.InventoryDataTable dt) + { + // Print out the column names. + for (int curCol = 0; curCol < dt.Columns.Count; curCol++) + { + Write(dt.Columns[curCol].ColumnName + "\t"); + } + WriteLine("\n----------------------------------"); + + // Print the DataTable. + for (int curRow = 0; curRow < dt.Rows.Count; curRow++) + { + for (int curCol = 0; curCol < dt.Columns.Count; curCol++) + { + Write(dt.Rows[curRow][curCol] + "\t"); + } + WriteLine(); + } + } + public static void AddRecords( + AutoLotDataSet.InventoryDataTable table, + InventoryTableAdapter adapter) + { + try + { + // Get a new strongly typed row from the table. + AutoLotDataSet.InventoryRow newRow = table.NewInventoryRow(); + + // Fill row with some sample data. + newRow.Color = "Purple"; + newRow.Make = "BMW"; + newRow.PetName = "Saku"; + + // Insert the new row. + table.AddInventoryRow(newRow); + + // Add one more row, using overloaded Add method. + table.AddInventoryRow("Yugo", "Green", "Zippy"); + + // Update database. + adapter.Update(table); + } + catch (Exception ex) + { + WriteLine(ex.Message); + } + } + private static void RemoveRecords(AutoLotDataSet.InventoryDataTable table, InventoryTableAdapter adapter) + { + try + { + AutoLotDataSet.InventoryRow rowToDelete = table.FindByCarId(8); + adapter.Delete(rowToDelete.CarId, rowToDelete.Make, rowToDelete.Color, rowToDelete.PetName); + rowToDelete = table.FindByCarId(9); + adapter.Delete(rowToDelete.CarId, rowToDelete.Make, rowToDelete.Color, rowToDelete.PetName); + } + catch (Exception ex) + { + WriteLine(ex.Message); + } + } + public static void CallStoredProc() + { + try + { + var queriesTableAdapter = new QueriesTableAdapter(); + Write("Enter ID of car to look up: "); + string carID = ReadLine() ?? "0"; + string carName = ""; + queriesTableAdapter.GetPetName(int.Parse(carID), ref carName); + WriteLine($"CarID {carID} has the name of {carName}"); + } + catch (Exception ex) + { + WriteLine(ex.Message); + } + } + + + } +} diff --git a/Appendix_A/StronglyTypedDataSetConsoleClient/Properties/AssemblyInfo.cs b/Appendix_A/StronglyTypedDataSetConsoleClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8d0ceba --- /dev/null +++ b/Appendix_A/StronglyTypedDataSetConsoleClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("StronglyTypedDataSetConsoleClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("StronglyTypedDataSetConsoleClient")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("72f92de8-0b9a-4f5c-a344-882e7844d5af")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/StronglyTypedDataSetConsoleClient/StronglyTypedDataSetConsoleClient.csproj b/Appendix_A/StronglyTypedDataSetConsoleClient/StronglyTypedDataSetConsoleClient.csproj new file mode 100644 index 0000000..f44df23 --- /dev/null +++ b/Appendix_A/StronglyTypedDataSetConsoleClient/StronglyTypedDataSetConsoleClient.csproj @@ -0,0 +1,66 @@ + + + + + Debug + AnyCPU + {72F92DE8-0B9A-4F5C-A344-882E7844D5AF} + Exe + Properties + StronglyTypedDataSetConsoleClient + StronglyTypedDataSetConsoleClient + v4.6 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + {732ccd23-b8e3-479e-845d-d082490f58d9} + AutoLotDAL3 + + + + + \ No newline at end of file diff --git a/Appendix_A/StronglyTypedDataSetConsoleClient/StronglyTypedDataSetConsoleClient.sln b/Appendix_A/StronglyTypedDataSetConsoleClient/StronglyTypedDataSetConsoleClient.sln new file mode 100644 index 0000000..1ee93a4 --- /dev/null +++ b/Appendix_A/StronglyTypedDataSetConsoleClient/StronglyTypedDataSetConsoleClient.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StronglyTypedDataSetConsoleClient", "StronglyTypedDataSetConsoleClient.csproj", "{72F92DE8-0B9A-4F5C-A344-882E7844D5AF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL3", "..\AutoLotDAL3\AutoLotDAL3.csproj", "{732CCD23-B8E3-479E-845D-D082490F58D9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {72F92DE8-0B9A-4F5C-A344-882E7844D5AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {72F92DE8-0B9A-4F5C-A344-882E7844D5AF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {72F92DE8-0B9A-4F5C-A344-882E7844D5AF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {72F92DE8-0B9A-4F5C-A344-882E7844D5AF}.Release|Any CPU.Build.0 = Release|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {732CCD23-B8E3-479E-845D-D082490F58D9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_A/WindowsFormsDataBinding/App.config b/Appendix_A/WindowsFormsDataBinding/App.config new file mode 100644 index 0000000..8324aa6 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_A/WindowsFormsDataBinding/Car.cs b/Appendix_A/WindowsFormsDataBinding/Car.cs new file mode 100644 index 0000000..8a72bfa --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/Car.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WindowsFormsDataBinding +{ + public class Car + { + public int Id { get; set; } + public string PetName { get; set; } + public string Make { get; set; } + public string Color { get; set; } + + } +} diff --git a/Appendix_A/WindowsFormsDataBinding/MainForm.Designer.cs b/Appendix_A/WindowsFormsDataBinding/MainForm.Designer.cs new file mode 100644 index 0000000..586fe48 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/MainForm.Designer.cs @@ -0,0 +1,203 @@ +namespace WindowsFormsDataBinding +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.carInventoryGridView = new System.Windows.Forms.DataGridView(); + this.lblGridInfoMessage = new System.Windows.Forms.Label(); + this.groupBoxDeleteRow = new System.Windows.Forms.GroupBox(); + this.btnRemoveCar = new System.Windows.Forms.Button(); + this.txtCarToRemove = new System.Windows.Forms.TextBox(); + this.groupBoxViewMakes = new System.Windows.Forms.GroupBox(); + this.btnDisplayMakes = new System.Windows.Forms.Button(); + this.txtMakeToView = new System.Windows.Forms.TextBox(); + this.btnChangeMakes = new System.Windows.Forms.Button(); + this.dataGridYugosView = new System.Windows.Forms.DataGridView(); + this.lblOnlyYugos = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.carInventoryGridView)).BeginInit(); + this.groupBoxDeleteRow.SuspendLayout(); + this.groupBoxViewMakes.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridYugosView)).BeginInit(); + this.SuspendLayout(); + // + // carInventoryGridView + // + this.carInventoryGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.carInventoryGridView.Location = new System.Drawing.Point(16, 68); + this.carInventoryGridView.Name = "carInventoryGridView"; + this.carInventoryGridView.RowTemplate.Height = 24; + this.carInventoryGridView.Size = new System.Drawing.Size(716, 235); + this.carInventoryGridView.TabIndex = 0; + // + // lblGridInfoMessage + // + this.lblGridInfoMessage.AutoSize = true; + this.lblGridInfoMessage.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblGridInfoMessage.Location = new System.Drawing.Point(16, 16); + this.lblGridInfoMessage.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.lblGridInfoMessage.Name = "lblGridInfoMessage"; + this.lblGridInfoMessage.Size = new System.Drawing.Size(357, 29); + this.lblGridInfoMessage.TabIndex = 2; + this.lblGridInfoMessage.Text = "Here is what we have in stock"; + // + // groupBoxDeleteRow + // + this.groupBoxDeleteRow.Controls.Add(this.btnRemoveCar); + this.groupBoxDeleteRow.Controls.Add(this.txtCarToRemove); + this.groupBoxDeleteRow.Location = new System.Drawing.Point(21, 321); + this.groupBoxDeleteRow.Margin = new System.Windows.Forms.Padding(4); + this.groupBoxDeleteRow.Name = "groupBoxDeleteRow"; + this.groupBoxDeleteRow.Padding = new System.Windows.Forms.Padding(4); + this.groupBoxDeleteRow.Size = new System.Drawing.Size(352, 97); + this.groupBoxDeleteRow.TabIndex = 3; + this.groupBoxDeleteRow.TabStop = false; + this.groupBoxDeleteRow.Text = "Enter ID of Car to Delete"; + // + // btnRemoveCar + // + this.btnRemoveCar.Location = new System.Drawing.Point(213, 44); + this.btnRemoveCar.Margin = new System.Windows.Forms.Padding(4); + this.btnRemoveCar.Name = "btnRemoveCar"; + this.btnRemoveCar.Size = new System.Drawing.Size(132, 28); + this.btnRemoveCar.TabIndex = 1; + this.btnRemoveCar.Text = "Delete!"; + this.btnRemoveCar.UseVisualStyleBackColor = true; + this.btnRemoveCar.Click += new System.EventHandler(this.btnRemoveCar_Click); + // + // txtCarToRemove + // + this.txtCarToRemove.Location = new System.Drawing.Point(23, 44); + this.txtCarToRemove.Margin = new System.Windows.Forms.Padding(4); + this.txtCarToRemove.Name = "txtCarToRemove"; + this.txtCarToRemove.Size = new System.Drawing.Size(181, 22); + this.txtCarToRemove.TabIndex = 0; + // + // groupBoxViewMakes + // + this.groupBoxViewMakes.Controls.Add(this.btnDisplayMakes); + this.groupBoxViewMakes.Controls.Add(this.txtMakeToView); + this.groupBoxViewMakes.Location = new System.Drawing.Point(381, 321); + this.groupBoxViewMakes.Margin = new System.Windows.Forms.Padding(4); + this.groupBoxViewMakes.Name = "groupBoxViewMakes"; + this.groupBoxViewMakes.Padding = new System.Windows.Forms.Padding(4); + this.groupBoxViewMakes.Size = new System.Drawing.Size(347, 97); + this.groupBoxViewMakes.TabIndex = 4; + this.groupBoxViewMakes.TabStop = false; + this.groupBoxViewMakes.Text = "Enter Make to View"; + // + // btnDisplayMakes + // + this.btnDisplayMakes.Location = new System.Drawing.Point(207, 44); + this.btnDisplayMakes.Margin = new System.Windows.Forms.Padding(4); + this.btnDisplayMakes.Name = "btnDisplayMakes"; + this.btnDisplayMakes.Size = new System.Drawing.Size(132, 28); + this.btnDisplayMakes.TabIndex = 3; + this.btnDisplayMakes.Text = "View!"; + this.btnDisplayMakes.UseVisualStyleBackColor = true; + this.btnDisplayMakes.Click += new System.EventHandler(this.btnDisplayMakes_Click); + // + // txtMakeToView + // + this.txtMakeToView.Location = new System.Drawing.Point(16, 44); + this.txtMakeToView.Margin = new System.Windows.Forms.Padding(4); + this.txtMakeToView.Name = "txtMakeToView"; + this.txtMakeToView.Size = new System.Drawing.Size(181, 22); + this.txtMakeToView.TabIndex = 2; + // + // btnChangeMakes + // + this.btnChangeMakes.Location = new System.Drawing.Point(435, 20); + this.btnChangeMakes.Margin = new System.Windows.Forms.Padding(4); + this.btnChangeMakes.Name = "btnChangeMakes"; + this.btnChangeMakes.Size = new System.Drawing.Size(297, 28); + this.btnChangeMakes.TabIndex = 5; + this.btnChangeMakes.Text = "Change All BMWs to Yugos"; + this.btnChangeMakes.UseVisualStyleBackColor = true; + this.btnChangeMakes.Click += new System.EventHandler(this.btnChangeMakes_Click); + // + // dataGridYugosView + // + this.dataGridYugosView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridYugosView.Location = new System.Drawing.Point(8, 466); + this.dataGridYugosView.Name = "dataGridYugosView"; + this.dataGridYugosView.RowTemplate.Height = 24; + this.dataGridYugosView.Size = new System.Drawing.Size(716, 235); + this.dataGridYugosView.TabIndex = 6; + // + // lblOnlyYugos + // + this.lblOnlyYugos.AutoSize = true; + this.lblOnlyYugos.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblOnlyYugos.Location = new System.Drawing.Point(16, 430); + this.lblOnlyYugos.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.lblOnlyYugos.Name = "lblOnlyYugos"; + this.lblOnlyYugos.Size = new System.Drawing.Size(147, 29); + this.lblOnlyYugos.TabIndex = 7; + this.lblOnlyYugos.Text = "Only Yugos"; + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(740, 710); + this.Controls.Add(this.lblOnlyYugos); + this.Controls.Add(this.dataGridYugosView); + this.Controls.Add(this.btnChangeMakes); + this.Controls.Add(this.groupBoxViewMakes); + this.Controls.Add(this.groupBoxDeleteRow); + this.Controls.Add(this.lblGridInfoMessage); + this.Controls.Add(this.carInventoryGridView); + this.Name = "MainForm"; + this.Text = "Windows Forms Data Binding"; + ((System.ComponentModel.ISupportInitialize)(this.carInventoryGridView)).EndInit(); + this.groupBoxDeleteRow.ResumeLayout(false); + this.groupBoxDeleteRow.PerformLayout(); + this.groupBoxViewMakes.ResumeLayout(false); + this.groupBoxViewMakes.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridYugosView)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.DataGridView carInventoryGridView; + private System.Windows.Forms.Label lblGridInfoMessage; + private System.Windows.Forms.GroupBox groupBoxDeleteRow; + private System.Windows.Forms.Button btnRemoveCar; + private System.Windows.Forms.TextBox txtCarToRemove; + private System.Windows.Forms.GroupBox groupBoxViewMakes; + private System.Windows.Forms.Button btnDisplayMakes; + private System.Windows.Forms.TextBox txtMakeToView; + private System.Windows.Forms.Button btnChangeMakes; + private System.Windows.Forms.DataGridView dataGridYugosView; + private System.Windows.Forms.Label lblOnlyYugos; + } +} + diff --git a/Appendix_A/WindowsFormsDataBinding/MainForm.cs b/Appendix_A/WindowsFormsDataBinding/MainForm.cs new file mode 100644 index 0000000..7bc9cfe --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/MainForm.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace WindowsFormsDataBinding +{ + public partial class MainForm : Form + { + // A collection of Car objects. + private List listCars = new List(); + + // Inventory information + private DataTable inventoryTable = new DataTable(); + + //View of the DataTable + private DataView _yugosOnlyView; + public MainForm() + { + InitializeComponent(); + listCars = new List + { + new Car { Id = 1, PetName = "Chucky", Make = "BMW", Color = "Green" }, + new Car { Id = 2, PetName = "Tiny", Make = "Yugo", Color = "White" }, + new Car { Id = 3, PetName = "Ami", Make = "Jeep", Color = "Tan" }, + new Car { Id = 4, PetName = "Pain Inducer", Make = "Caravan", Color = "Pink" }, + new Car { Id = 5, PetName = "Fred", Make = "BMW", Color = "Green" }, + new Car { Id = 6, PetName = "Sidd", Make = "BMW", Color = "Black" }, + new Car { Id = 7, PetName = "Mel", Make = "Firebird", Color = "Red" }, + new Car { Id = 8, PetName = "Sarah", Make = "Colt", Color = "Black" }, + }; + CreateDataTable(); + //ShowCarsWithIdGreaterThanFive(); + CreateDataView(); + } + + void CreateDataTable() + { + // Create table schema. + var carIDColumn = new DataColumn("Id", typeof(int)); + var carMakeColumn = new DataColumn("Make", typeof(string)); + var carColorColumn = new DataColumn("Color", typeof(string)); + var carPetNameColumn = new DataColumn("PetName", typeof(string)) + { Caption = "Pet Name" }; + inventoryTable.Columns.AddRange( + new[] { carIDColumn, carMakeColumn, carColorColumn, carPetNameColumn }); + + // Iterate over the array list to make rows. + foreach (var c in listCars) + { + var newRow = inventoryTable.NewRow(); + newRow["Id"] = c.Id; + newRow["Make"] = c.Make; + newRow["Color"] = c.Color; + newRow["PetName"] = c.PetName; + inventoryTable.Rows.Add(newRow); + } + // Bind the DataTable to the carInventoryGridView. + carInventoryGridView.DataSource = inventoryTable; + } + private void CreateDataView() + { + // Set the table that is used to construct this view. + _yugosOnlyView = new DataView(inventoryTable); + + // Now configure the views using a filter. + _yugosOnlyView.RowFilter = "Make = 'Yugo'"; + + // Bind to the new grid. + dataGridYugosView.DataSource = _yugosOnlyView; + } + + private void btnRemoveCar_Click(object sender, EventArgs e) + { + try + { + // Find the correct row to delete. + DataRow[] rowToDelete = inventoryTable.Select($"Id={int.Parse(txtCarToRemove.Text)}"); + + // Delete it! + rowToDelete[0].Delete(); + inventoryTable.AcceptChanges(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + } + + } + + private void btnDisplayMakes_Click(object sender, EventArgs e) + { + // Build a filter based on user input. + string filterStr = $"Make='{txtMakeToView.Text}'"; + + // Find all rows matching the filter. + DataRow[] makes = inventoryTable.Select(filterStr, "PetName DESC"); + + // Show what we got! + if (makes.Length == 0) + MessageBox.Show("Sorry, no cars...", "Selection error!"); + else + { + string strMake = null; + for (var i = 0; i < makes.Length; i++) + { + strMake += makes[i]["PetName"] + "\n"; + } + // Now show all matches in a message box. + MessageBox.Show(strMake, $"We have {txtMakeToView.Text}s named:"); + } + } + private void ShowCarsWithIdGreaterThanFive() + { + // Now show the pet names of all cars with ID greater than 5. + DataRow[] properIDs; + string newFilterStr = "Id > 5"; + properIDs = inventoryTable.Select(newFilterStr); + string strIDs = null; + for (int i = 0; i < properIDs.Length; i++) + { + DataRow temp = properIDs[i]; + strIDs += $"{temp["PetName"]} is ID {temp["ID"]}\n"; + } + MessageBox.Show(strIDs, "Pet names of cars where Id > 5"); + } + + private void btnChangeMakes_Click(object sender, EventArgs e) + { + // Make sure user has not lost his or her mind. + if (DialogResult.Yes != + MessageBox.Show("Are you sure?? BMWs are much nicer than Yugos!", + "Please Confirm!", MessageBoxButtons.YesNo)) + return; + // Build a filter. + string filterStr = "Make='BMW'"; + + // Find all rows matching the filter. + DataRow[] makes = inventoryTable.Select(filterStr); + + // Change all Beemers to Yugos! + for (int i = 0; i < makes.Length; i++) + { + makes[i]["Make"] = "Yugo"; + } + } + } +} diff --git a/Appendix_A/WindowsFormsDataBinding/MainForm.resx b/Appendix_A/WindowsFormsDataBinding/MainForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/MainForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_A/WindowsFormsDataBinding/Program.cs b/Appendix_A/WindowsFormsDataBinding/Program.cs new file mode 100644 index 0000000..69badd0 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace WindowsFormsDataBinding +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/Appendix_A/WindowsFormsDataBinding/Properties/AssemblyInfo.cs b/Appendix_A/WindowsFormsDataBinding/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3fe9f76 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("WindowsFormsDataBinding")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WindowsFormsDataBinding")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("23fe9ffd-e2e6-49fe-967f-e8a405e69665")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_A/WindowsFormsDataBinding/Properties/Resources.Designer.cs b/Appendix_A/WindowsFormsDataBinding/Properties/Resources.Designer.cs new file mode 100644 index 0000000..2691c95 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WindowsFormsDataBinding.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsDataBinding.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Appendix_A/WindowsFormsDataBinding/Properties/Resources.resx b/Appendix_A/WindowsFormsDataBinding/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_A/WindowsFormsDataBinding/Properties/Settings.Designer.cs b/Appendix_A/WindowsFormsDataBinding/Properties/Settings.Designer.cs new file mode 100644 index 0000000..5a3ed83 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WindowsFormsDataBinding.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Appendix_A/WindowsFormsDataBinding/Properties/Settings.settings b/Appendix_A/WindowsFormsDataBinding/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Appendix_A/WindowsFormsDataBinding/WindowsFormsDataBinding.csproj b/Appendix_A/WindowsFormsDataBinding/WindowsFormsDataBinding.csproj new file mode 100644 index 0000000..aa54a65 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/WindowsFormsDataBinding.csproj @@ -0,0 +1,91 @@ + + + + + Debug + AnyCPU + {23FE9FFD-E2E6-49FE-967F-E8A405E69665} + WinExe + Properties + WindowsFormsDataBinding + WindowsFormsDataBinding + v4.6 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + Form + + + MainForm.cs + + + + + MainForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + \ No newline at end of file diff --git a/Appendix_A/WindowsFormsDataBinding/WindowsFormsDataBinding.sln b/Appendix_A/WindowsFormsDataBinding/WindowsFormsDataBinding.sln new file mode 100644 index 0000000..1d518e4 --- /dev/null +++ b/Appendix_A/WindowsFormsDataBinding/WindowsFormsDataBinding.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsFormsDataBinding", "WindowsFormsDataBinding.csproj", "{23FE9FFD-E2E6-49FE-967F-E8A405E69665}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {23FE9FFD-E2E6-49FE-967F-E8A405E69665}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {23FE9FFD-E2E6-49FE-967F-E8A405E69665}.Debug|Any CPU.Build.0 = Debug|Any CPU + {23FE9FFD-E2E6-49FE-967F-E8A405E69665}.Release|Any CPU.ActiveCfg = Release|Any CPU + {23FE9FFD-E2E6-49FE-967F-E8A405E69665}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_B/ConstructingXmlDocs/ConstructingXmlDocs.csproj b/Appendix_B/ConstructingXmlDocs/ConstructingXmlDocs.csproj new file mode 100644 index 0000000..6dea4a5 --- /dev/null +++ b/Appendix_B/ConstructingXmlDocs/ConstructingXmlDocs.csproj @@ -0,0 +1,63 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {640DE17A-2943-4644-8244-7BBB33E24BF5} + Exe + Properties + ConstructingXmlDocs + ConstructingXmlDocs + v4.6 + + + 512 + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_B/ConstructingXmlDocs/ConstructingXmlDocs.sln b/Appendix_B/ConstructingXmlDocs/ConstructingXmlDocs.sln new file mode 100644 index 0000000..562bc94 --- /dev/null +++ b/Appendix_B/ConstructingXmlDocs/ConstructingXmlDocs.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConstructingXmlDocs", "ConstructingXmlDocs.csproj", "{640DE17A-2943-4644-8244-7BBB33E24BF5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x86 = Debug|x86 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {640DE17A-2943-4644-8244-7BBB33E24BF5}.Debug|x86.ActiveCfg = Debug|x86 + {640DE17A-2943-4644-8244-7BBB33E24BF5}.Debug|x86.Build.0 = Debug|x86 + {640DE17A-2943-4644-8244-7BBB33E24BF5}.Release|x86.ActiveCfg = Release|x86 + {640DE17A-2943-4644-8244-7BBB33E24BF5}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_B/ConstructingXmlDocs/Program.cs b/Appendix_B/ConstructingXmlDocs/Program.cs new file mode 100644 index 0000000..8ca03e9 --- /dev/null +++ b/Appendix_B/ConstructingXmlDocs/Program.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Xml.Linq; + +namespace ConstructingXmlDocs +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun making XML docs! *****"); + CreateFullXDocument(); + CreateRootAndChildren(); + MakeXElementFromArray(); + Console.WriteLine(); + + ParseAndLoadExistingXml(); + Console.ReadLine(); + } + + #region Create full XDocument + static void CreateFullXDocument() + { + XDocument inventoryDoc = + new XDocument( + new XComment("Current Inventory of cars!"), + new XProcessingInstruction("xml-stylesheet", + "href='MyStyles.css' title='Compact' type='text/css'"), + new XElement("Inventory", + new XElement("Car", new XAttribute("ID", "1"), + new XElement("Color", "Green"), + new XElement("Make", "BMW"), + new XElement("PetName", "Stan") + ), + new XElement("Car", new XAttribute("ID", "2"), + new XElement("Color", "Pink"), + new XElement("Make", "Yugo"), + new XElement("PetName", "Melvin") + ) + ) + ); + // Save to disk. + inventoryDoc.Save("FullXmlDoc.xml"); + + } + #endregion + + #region Make XElement and save to disk. + static void CreateRootAndChildren() + { + XElement inventoryDoc = + new XElement("Inventory", + new XComment("Current Inventory of cars!"), + new XElement("Car", new XAttribute("ID", "1"), + new XElement("Color", "Green"), + new XElement("Make", "BMW"), + new XElement("PetName", "Stan") + ), + new XElement("Car", new XAttribute("ID", "2"), + new XElement("Color", "Pink"), + new XElement("Make", "Yugo"), + new XElement("PetName", "Melvin") + ) + ); + + // Save to disk. + inventoryDoc.Save("SimpleInventory.xml"); + } + #endregion + + #region Map array to XElement + static void MakeXElementFromArray() + { + // Create an anonymous array of anonymous types. + var people = new[] { + new { FirstName = "Mandy", Age = 40}, + new { FirstName = "Andrew", Age = 32 }, + new { FirstName = "Dave", Age = 41 }, + new { FirstName = "Sara", Age = 31} + }; + + //XElement peopleDoc = + // new XElement("People", + // from c in people select + // new XElement("Person", new XAttribute("Age", c.Age), new XElement("FirstName", c.FirstName)) + // ); + + var arrayDataAsXElements = from c in people + select + new XElement("Person", + new XAttribute("Age", c.Age), + new XElement("FirstName", c.FirstName)); + + XElement peopleDoc = new XElement("People", arrayDataAsXElements); + Console.WriteLine(peopleDoc); + } + #endregion + + #region Parse / Load + static void ParseAndLoadExistingXml() + { + // Build an XElement from string. + string myElement = + @" + Yellow + Yugo + "; + XElement newElement = XElement.Parse(myElement); + Console.WriteLine(newElement); + Console.WriteLine(); + + // Load the SimpleInventory.xml file. + XDocument myDoc = XDocument.Load("SimpleInventory.xml"); + Console.WriteLine(myDoc); + } + #endregion + } +} diff --git a/Appendix_B/ConstructingXmlDocs/Properties/AssemblyInfo.cs b/Appendix_B/ConstructingXmlDocs/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4d4712b --- /dev/null +++ b/Appendix_B/ConstructingXmlDocs/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ConstructingXmlDocs")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ConstructingXmlDocs")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("03080d47-c75d-4681-b380-d3f8ee2ca73d")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_B/ConstructingXmlDocs/app.config b/Appendix_B/ConstructingXmlDocs/app.config new file mode 100644 index 0000000..b45f31e --- /dev/null +++ b/Appendix_B/ConstructingXmlDocs/app.config @@ -0,0 +1,3 @@ + + + diff --git a/Appendix_B/LinqToXmlFirstLook/LinqToXmlFirstLook.csproj b/Appendix_B/LinqToXmlFirstLook/LinqToXmlFirstLook.csproj new file mode 100644 index 0000000..1673fc5 --- /dev/null +++ b/Appendix_B/LinqToXmlFirstLook/LinqToXmlFirstLook.csproj @@ -0,0 +1,66 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {3845496E-3EF2-4CF5-9329-22EFC3722670} + Exe + Properties + LinqToXmlFirstLook + LinqToXmlFirstLook + v4.6 + + + 512 + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + + + + + + + + ..\VbXmlLiteralLibrary\bin\Debug\VbXmlLiteralLibrary.dll + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_B/LinqToXmlFirstLook/LinqToXmlFirstLook.sln b/Appendix_B/LinqToXmlFirstLook/LinqToXmlFirstLook.sln new file mode 100644 index 0000000..23859a5 --- /dev/null +++ b/Appendix_B/LinqToXmlFirstLook/LinqToXmlFirstLook.sln @@ -0,0 +1,42 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqToXmlFirstLook", "LinqToXmlFirstLook.csproj", "{3845496E-3EF2-4CF5-9329-22EFC3722670}" +EndProject +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "VbXmlLiteralLibrary", "..\VbXmlLiteralLibrary\VbXmlLiteralLibrary.vbproj", "{2047DCF7-C256-43E8-9174-594868045151}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|Mixed Platforms = Debug|Mixed Platforms + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|Mixed Platforms = Release|Mixed Platforms + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Debug|Any CPU.ActiveCfg = Debug|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Debug|x86.ActiveCfg = Debug|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Debug|x86.Build.0 = Debug|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Release|Any CPU.ActiveCfg = Release|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Release|Mixed Platforms.Build.0 = Release|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Release|x86.ActiveCfg = Release|x86 + {3845496E-3EF2-4CF5-9329-22EFC3722670}.Release|x86.Build.0 = Release|x86 + {2047DCF7-C256-43E8-9174-594868045151}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Debug|x86.ActiveCfg = Debug|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Release|Any CPU.Build.0 = Release|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {2047DCF7-C256-43E8-9174-594868045151}.Release|x86.ActiveCfg = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_B/LinqToXmlFirstLook/Program.cs b/Appendix_B/LinqToXmlFirstLook/Program.cs new file mode 100644 index 0000000..5cddb81 --- /dev/null +++ b/Appendix_B/LinqToXmlFirstLook/Program.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +// For older DOM support. +using System.Xml; + +// For newer LINQ to XML support. +using System.Xml.Linq; + +namespace BuildXmlDocExample +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** A Tale of Two XML APIs *****"); + BuildXmlDocWithDOM(); + BuildXmlDocWithLINQToXml(); + + // Test functionality from the VB library in this solution. + VbXmlLiteralLibrary.XmlLiteralExample vbXml = new VbXmlLiteralLibrary.XmlLiteralExample(); + vbXml.MakeXmlFileUsingLiterals(); + + Console.WriteLine("XML data saved to output directory."); + + // Delete a node. + DeleteNodeFromDoc(); + Console.ReadLine(); + } + + #region Build XML file using System.Xml.dll types. + private static void BuildXmlDocWithDOM() + { + // Make a new XML document in memory. + XmlDocument doc = new XmlDocument(); + + // Fill this document with a root element + // named . + XmlElement inventory = doc.CreateElement("Inventory"); + + // Now, make a sub element named with + // an ID attribute. + XmlElement car = doc.CreateElement("Car"); + car.SetAttribute("ID", "1000"); + + // Build the data within the element. + XmlElement name = doc.CreateElement("PetName"); + name.InnerText = "Jimbo"; + XmlElement color = doc.CreateElement("Color"); + color.InnerText = "Red"; + XmlElement make = doc.CreateElement("Make"); + make.InnerText = "Ford"; + + // Add , and to the + // element. + car.AppendChild(name); + car.AppendChild(color); + car.AppendChild(make); + + // Add the element to the element. + inventory.AppendChild(car); + + // Insert the complete XML into the XmlDocument object, + // and save to file. + doc.AppendChild(inventory); + doc.Save("Inventory.xml"); + } + #endregion + + #region Build XML doc with LINQ to XML + private static void BuildXmlDocWithLINQToXml() + { + // Create a 'functional' XML document. + XElement doc = + new XElement("Inventory", + new XElement("Car", new XAttribute("ID", "1000"), + new XElement("PetName", "Jimbo"), + new XElement("Color", "Red"), + new XElement("Make", "Ford") + ) + ); + + // Save to file. + doc.Save("InventoryWithLINQ.xml"); + } + #endregion + + #region Remove an element. + private static void DeleteNodeFromDoc() + { + // Create a 'functional' XML document. + XElement doc = + new XElement("Inventory", + new XElement("Car", new XAttribute("ID", "1000"), + new XElement("PetName", "Jimbo"), + new XElement("Color", "Red"), + new XElement("Make", "Ford") + ) + ); + + // Delete the PetName element from the tree. + doc.Descendants("PetName").Remove(); + Console.WriteLine(doc); + } + #endregion + } +} diff --git a/Appendix_B/LinqToXmlFirstLook/Properties/AssemblyInfo.cs b/Appendix_B/LinqToXmlFirstLook/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3090566 --- /dev/null +++ b/Appendix_B/LinqToXmlFirstLook/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LinqToXmlFirstLook")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("LinqToXmlFirstLook")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("23b32411-c28b-4e86-8d5f-75a923b3e14c")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_B/LinqToXmlFirstLook/app.config b/Appendix_B/LinqToXmlFirstLook/app.config new file mode 100644 index 0000000..b45f31e --- /dev/null +++ b/Appendix_B/LinqToXmlFirstLook/app.config @@ -0,0 +1,3 @@ + + + diff --git a/Appendix_B/LinqToXmlWinApp/Inventory.xml b/Appendix_B/LinqToXmlWinApp/Inventory.xml new file mode 100644 index 0000000..a338452 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/Inventory.xml @@ -0,0 +1,28 @@ + + + + Ford + Blue + Chuck + + + VW + Silver + Mary + + + Yugo + Pink + Gipper + + + Ford + Yellow + Max + + + BMW + Black + Zippy + + diff --git a/Appendix_B/LinqToXmlWinApp/LinqToXmlObjectModel.cs b/Appendix_B/LinqToXmlWinApp/LinqToXmlObjectModel.cs new file mode 100644 index 0000000..f1df2e2 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/LinqToXmlObjectModel.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Xml.Linq; + +using System.Windows.Forms; + +namespace LinqToXmlWinApp +{ + class LinqToXmlObjectModel + { + #region Load XML doc + public static XDocument GetXmlInventory() + { + try + { + XDocument inventoryDoc = XDocument.Load("Inventory.xml"); + return inventoryDoc; + } + catch (System.IO.FileNotFoundException ex) + { + MessageBox.Show(ex.Message); + return null; + } + } + #endregion + + #region Insert new item + public static void InsertNewElement(string make, string color, string petName) + { + // Load current document. + XDocument inventoryDoc = XDocument.Load("Inventory.xml"); + + // Generate a random number for the ID. + Random r = new Random(); + + // Make new XElement based on incoming parameters. + XElement newElement = new XElement("Car", new XAttribute("ID", r.Next(50000)), + new XElement("Color", color), + new XElement("Make", make), + new XElement("PetName", petName)); + + // Add to in-memory object. + inventoryDoc.Descendants("Inventory").First().Add(newElement); + + // Save changes to disk. + inventoryDoc.Save("Inventory.xml"); + } + #endregion + + #region Query doc + public static void LookUpColorsForMake(string make) + { + // Load current document. + XDocument inventoryDoc = XDocument.Load("Inventory.xml"); + + // Find the colors for a given make. + var makeInfo = from car in inventoryDoc.Descendants("Car") + where (string)car.Element("Make") == make + select car.Element("Color").Value; + + // Build a string representing each color. + string data = string.Empty; + foreach (var item in makeInfo.Distinct()) + { + data += string.Format("- {0}\n", item); + } + + // Show colors. + MessageBox.Show(data, string.Format("{0} colors:", make)); + } + #endregion + } +} diff --git a/Appendix_B/LinqToXmlWinApp/LinqToXmlWinApp.csproj b/Appendix_B/LinqToXmlWinApp/LinqToXmlWinApp.csproj new file mode 100644 index 0000000..cbb1268 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/LinqToXmlWinApp.csproj @@ -0,0 +1,98 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {4653F2CF-3487-4D93-A15A-A2570D83FE79} + WinExe + Properties + LinqToXmlWinApp + LinqToXmlWinApp + v4.6 + + + 512 + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + + + + + + + + + + + + + + Form + + + MainForm.cs + + + + + MainForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + Always + + + + + \ No newline at end of file diff --git a/Appendix_B/LinqToXmlWinApp/LinqToXmlWinApp.sln b/Appendix_B/LinqToXmlWinApp/LinqToXmlWinApp.sln new file mode 100644 index 0000000..68235c1 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/LinqToXmlWinApp.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqToXmlWinApp", "LinqToXmlWinApp.csproj", "{4653F2CF-3487-4D93-A15A-A2570D83FE79}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x86 = Debug|x86 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4653F2CF-3487-4D93-A15A-A2570D83FE79}.Debug|x86.ActiveCfg = Debug|x86 + {4653F2CF-3487-4D93-A15A-A2570D83FE79}.Debug|x86.Build.0 = Debug|x86 + {4653F2CF-3487-4D93-A15A-A2570D83FE79}.Release|x86.ActiveCfg = Release|x86 + {4653F2CF-3487-4D93-A15A-A2570D83FE79}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_B/LinqToXmlWinApp/MainForm.Designer.cs b/Appendix_B/LinqToXmlWinApp/MainForm.Designer.cs new file mode 100644 index 0000000..3c077ee --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/MainForm.Designer.cs @@ -0,0 +1,222 @@ +namespace LinqToXmlWinApp +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.label1 = new System.Windows.Forms.Label(); + this.txtInventory = new System.Windows.Forms.TextBox(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.btnAddNewItem = new System.Windows.Forms.Button(); + this.txtPetName = new System.Windows.Forms.TextBox(); + this.label4 = new System.Windows.Forms.Label(); + this.txtColor = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.txtMake = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.btnLookUpColors = new System.Windows.Forms.Button(); + this.txtMakeToLookUp = new System.Windows.Forms.TextBox(); + this.label5 = new System.Windows.Forms.Label(); + this.groupBox1.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(13, 13); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(88, 13); + this.label1.TabIndex = 0; + this.label1.Text = "Current Inventory"; + // + // txtInventory + // + this.txtInventory.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.txtInventory.Location = new System.Drawing.Point(16, 39); + this.txtInventory.Multiline = true; + this.txtInventory.Name = "txtInventory"; + this.txtInventory.ReadOnly = true; + this.txtInventory.ScrollBars = System.Windows.Forms.ScrollBars.Both; + this.txtInventory.Size = new System.Drawing.Size(255, 195); + this.txtInventory.TabIndex = 1; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.btnAddNewItem); + this.groupBox1.Controls.Add(this.txtPetName); + this.groupBox1.Controls.Add(this.label4); + this.groupBox1.Controls.Add(this.txtColor); + this.groupBox1.Controls.Add(this.label3); + this.groupBox1.Controls.Add(this.txtMake); + this.groupBox1.Controls.Add(this.label2); + this.groupBox1.Location = new System.Drawing.Point(296, 39); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(301, 153); + this.groupBox1.TabIndex = 2; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "Add Inventory Item"; + // + // btnAddNewItem + // + this.btnAddNewItem.Location = new System.Drawing.Point(167, 114); + this.btnAddNewItem.Name = "btnAddNewItem"; + this.btnAddNewItem.Size = new System.Drawing.Size(109, 23); + this.btnAddNewItem.TabIndex = 6; + this.btnAddNewItem.Text = "Add"; + this.btnAddNewItem.UseVisualStyleBackColor = true; + this.btnAddNewItem.Click += new System.EventHandler(this.btnAddNewItem_Click); + // + // txtPetName + // + this.txtPetName.Location = new System.Drawing.Point(77, 88); + this.txtPetName.Name = "txtPetName"; + this.txtPetName.Size = new System.Drawing.Size(200, 20); + this.txtPetName.TabIndex = 5; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(16, 88); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(54, 13); + this.label4.TabIndex = 4; + this.label4.Text = "Pet Name"; + // + // txtColor + // + this.txtColor.Location = new System.Drawing.Point(76, 61); + this.txtColor.Name = "txtColor"; + this.txtColor.Size = new System.Drawing.Size(200, 20); + this.txtColor.TabIndex = 3; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(15, 61); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(31, 13); + this.label3.TabIndex = 2; + this.label3.Text = "Color"; + // + // txtMake + // + this.txtMake.Location = new System.Drawing.Point(76, 35); + this.txtMake.Name = "txtMake"; + this.txtMake.Size = new System.Drawing.Size(200, 20); + this.txtMake.TabIndex = 1; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(15, 35); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(34, 13); + this.label2.TabIndex = 0; + this.label2.Text = "Make"; + // + // groupBox2 + // + this.groupBox2.Controls.Add(this.btnLookUpColors); + this.groupBox2.Controls.Add(this.txtMakeToLookUp); + this.groupBox2.Controls.Add(this.label5); + this.groupBox2.Location = new System.Drawing.Point(296, 211); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(301, 105); + this.groupBox2.TabIndex = 3; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "Look up Colors for Make"; + // + // btnLookUpColors + // + this.btnLookUpColors.Location = new System.Drawing.Point(126, 69); + this.btnLookUpColors.Name = "btnLookUpColors"; + this.btnLookUpColors.Size = new System.Drawing.Size(150, 23); + this.btnLookUpColors.TabIndex = 2; + this.btnLookUpColors.Text = "Look Up Colors"; + this.btnLookUpColors.UseVisualStyleBackColor = true; + this.btnLookUpColors.Click += new System.EventHandler(this.btnLookUpColors_Click); + // + // txtMakeToLookUp + // + this.txtMakeToLookUp.Location = new System.Drawing.Point(126, 36); + this.txtMakeToLookUp.Name = "txtMakeToLookUp"; + this.txtMakeToLookUp.Size = new System.Drawing.Size(150, 20); + this.txtMakeToLookUp.TabIndex = 1; + this.txtMakeToLookUp.Text = "BMW"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(18, 36); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(90, 13); + this.label5.TabIndex = 0; + this.label5.Text = "Make to Look Up"; + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(619, 351); + this.Controls.Add(this.groupBox2); + this.Controls.Add(this.groupBox1); + this.Controls.Add(this.txtInventory); + this.Controls.Add(this.label1); + this.Name = "MainForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Fun with LINQ to XML"; + this.Load += new System.EventHandler(this.MainForm_Load); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.groupBox2.ResumeLayout(false); + this.groupBox2.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox txtInventory; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.TextBox txtPetName; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.TextBox txtColor; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.TextBox txtMake; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Button btnAddNewItem; + private System.Windows.Forms.GroupBox groupBox2; + private System.Windows.Forms.Button btnLookUpColors; + private System.Windows.Forms.TextBox txtMakeToLookUp; + private System.Windows.Forms.Label label5; + } +} + diff --git a/Appendix_B/LinqToXmlWinApp/MainForm.cs b/Appendix_B/LinqToXmlWinApp/MainForm.cs new file mode 100644 index 0000000..a122370 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/MainForm.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace LinqToXmlWinApp +{ + public partial class MainForm : Form + { + public MainForm() + { + InitializeComponent(); + } + + private void MainForm_Load(object sender, EventArgs e) + { + // Display current XML inventory document in TextBox control. + txtInventory.Text = LinqToXmlObjectModel.GetXmlInventory().ToString(); + } + + private void btnAddNewItem_Click(object sender, EventArgs e) + { + // Add new item to doc. + LinqToXmlObjectModel.InsertNewElement(txtMake.Text, txtColor.Text, txtPetName.Text); + + // Display current XML inventory document in TextBox control. + txtInventory.Text = LinqToXmlObjectModel.GetXmlInventory().ToString(); + } + + private void btnLookUpColors_Click(object sender, EventArgs e) + { + LinqToXmlObjectModel.LookUpColorsForMake(txtMakeToLookUp.Text); + } + } +} diff --git a/Appendix_B/LinqToXmlWinApp/MainForm.resx b/Appendix_B/LinqToXmlWinApp/MainForm.resx new file mode 100644 index 0000000..d58980a --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/MainForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_B/LinqToXmlWinApp/Program.cs b/Appendix_B/LinqToXmlWinApp/Program.cs new file mode 100644 index 0000000..16c13ab --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; + +namespace LinqToXmlWinApp +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/Appendix_B/LinqToXmlWinApp/Properties/AssemblyInfo.cs b/Appendix_B/LinqToXmlWinApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0199398 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LinqToXmlWinApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("LinqToXmlWinApp")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b7c723a2-064a-434f-952c-be574efd60c6")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_B/LinqToXmlWinApp/Properties/Resources.Designer.cs b/Appendix_B/LinqToXmlWinApp/Properties/Resources.Designer.cs new file mode 100644 index 0000000..41533b8 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace LinqToXmlWinApp.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LinqToXmlWinApp.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/Appendix_B/LinqToXmlWinApp/Properties/Resources.resx b/Appendix_B/LinqToXmlWinApp/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_B/LinqToXmlWinApp/Properties/Settings.Designer.cs b/Appendix_B/LinqToXmlWinApp/Properties/Settings.Designer.cs new file mode 100644 index 0000000..29feb29 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace LinqToXmlWinApp.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/Appendix_B/LinqToXmlWinApp/Properties/Settings.settings b/Appendix_B/LinqToXmlWinApp/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Appendix_B/LinqToXmlWinApp/app.config b/Appendix_B/LinqToXmlWinApp/app.config new file mode 100644 index 0000000..b45f31e --- /dev/null +++ b/Appendix_B/LinqToXmlWinApp/app.config @@ -0,0 +1,3 @@ + + + diff --git a/Appendix_B/VbXmlLiteralLibrary/My Project/Application.Designer.vb b/Appendix_B/VbXmlLiteralLibrary/My Project/Application.Designer.vb new file mode 100644 index 0000000..88dd01c --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/My Project/Application.Designer.vb @@ -0,0 +1,13 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + diff --git a/Appendix_B/VbXmlLiteralLibrary/My Project/Application.myapp b/Appendix_B/VbXmlLiteralLibrary/My Project/Application.myapp new file mode 100644 index 0000000..758895d --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/My Project/Application.myapp @@ -0,0 +1,10 @@ + + + false + false + 0 + true + 0 + 1 + true + diff --git a/Appendix_B/VbXmlLiteralLibrary/My Project/AssemblyInfo.vb b/Appendix_B/VbXmlLiteralLibrary/My Project/AssemblyInfo.vb new file mode 100644 index 0000000..7946b2f --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/My Project/AssemblyInfo.vb @@ -0,0 +1,35 @@ +Imports System +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/Appendix_B/VbXmlLiteralLibrary/My Project/Resources.Designer.vb b/Appendix_B/VbXmlLiteralLibrary/My Project/Resources.Designer.vb new file mode 100644 index 0000000..e55d593 --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/My Project/Resources.Designer.vb @@ -0,0 +1,63 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + +Imports System + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ''' + ''' A strongly-typed resource class, for looking up localized strings, etc. + ''' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ''' + ''' Returns the cached ResourceManager instance used by this class. + ''' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("VbXmlLiteralLibrary.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ''' + ''' Overrides the current thread's CurrentUICulture property for all + ''' resource lookups using this strongly typed resource class. + ''' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/Appendix_B/VbXmlLiteralLibrary/My Project/Resources.resx b/Appendix_B/VbXmlLiteralLibrary/My Project/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Appendix_B/VbXmlLiteralLibrary/My Project/Settings.Designer.vb b/Appendix_B/VbXmlLiteralLibrary/My Project/Settings.Designer.vb new file mode 100644 index 0000000..f3c4edd --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.VbXmlLiteralLibrary.My.MySettings + Get + Return Global.VbXmlLiteralLibrary.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/Appendix_B/VbXmlLiteralLibrary/My Project/Settings.settings b/Appendix_B/VbXmlLiteralLibrary/My Project/Settings.settings new file mode 100644 index 0000000..85b890b --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Appendix_B/VbXmlLiteralLibrary/VbXmlLiteralLibrary.vbproj b/Appendix_B/VbXmlLiteralLibrary/VbXmlLiteralLibrary.vbproj new file mode 100644 index 0000000..a72a820 --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/VbXmlLiteralLibrary.vbproj @@ -0,0 +1,106 @@ + + + + Debug + AnyCPU + + + + + {2047DCF7-C256-43E8-9174-594868045151} + Library + VbXmlLiteralLibrary + VbXmlLiteralLibrary + 512 + Windows + v4.6 + On + Binary + Off + On + + + + true + full + true + true + bin\Debug\ + VbXmlLiteralLibrary.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + false + + + pdbonly + false + true + true + bin\Release\ + VbXmlLiteralLibrary.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + false + + + + + + + + + + + + + + + + + + + + + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + \ No newline at end of file diff --git a/Appendix_B/VbXmlLiteralLibrary/XmlLiteralExample.vb b/Appendix_B/VbXmlLiteralLibrary/XmlLiteralExample.vb new file mode 100644 index 0000000..ac50a08 --- /dev/null +++ b/Appendix_B/VbXmlLiteralLibrary/XmlLiteralExample.vb @@ -0,0 +1,19 @@ +Public Class XmlLiteralExample + Public Sub MakeXmlFileUsingLiterals() + ' Notice that we can inline XML data + ' to an XElement. + Dim doc As XElement = + + + Jimbo + Red + Ford + + + Yugo + + + + doc.Save("InventoryVBStyle.xml") + End Sub +End Class diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel.sln b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel.sln new file mode 100644 index 0000000..8ca4561 --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeBehindPageModel", "CodeBehindPageModel\CodeBehindPageModel.csproj", "{CE5D2AB5-42BF-4421-8134-26548B9ABF47}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CE5D2AB5-42BF-4421-8134-26548B9ABF47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CE5D2AB5-42BF-4421-8134-26548B9ABF47}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CE5D2AB5-42BF-4421-8134-26548B9ABF47}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CE5D2AB5-42BF-4421-8134-26548B9ABF47}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/CodeBehindPageModel.csproj b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/CodeBehindPageModel.csproj new file mode 100644 index 0000000..f214153 --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/CodeBehindPageModel.csproj @@ -0,0 +1,141 @@ + + + + + + + Debug + AnyCPU + + + 2.0 + {CE5D2AB5-42BF-4421-8134-26548B9ABF47} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + CodeBehindPageModel + CodeBehindPageModel + v4.6 + true + + + + + + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + + + + ..\References\AutoLotDAL.dll + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + True + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + True + + + ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll + True + + + + + + + + + + + + + + + + + + + + + + + Web.config + + + Web.config + + + + + + + + + Default.aspx + ASPXCodeBehind + + + Default.aspx + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + True + True + 49842 + / + http://localhost:49842/ + False + False + + + False + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx new file mode 100644 index 0000000..9019dc3 --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx @@ -0,0 +1,29 @@ +<%@ Page Language="C#" AutoEventWireup="true" + CodeBehind="Default.aspx.cs" Inherits="CodeBehindPageModel.Default" + Trace="true" %> + + + + + + + + +
+ + + + + + + + + + + + +
+ + diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx.cs b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx.cs new file mode 100644 index 0000000..7627172 --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Web.UI; +using AutoLotDAL.Models; +using AutoLotDAL.Repos; + +namespace CodeBehindPageModel +{ + public partial class Default : Page + { + protected void Page_Load(object sender, EventArgs e) + { + + } + + public IEnumerable GetData() + { + Trace.Write("Default.aspx","Getting Data"); + return new InventoryRepo().GetAll(); + } + } +} \ No newline at end of file diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx.designer.cs b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx.designer.cs new file mode 100644 index 0000000..d6080e5 --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Default.aspx.designer.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace CodeBehindPageModel { + + + public partial class Default { + + /// + /// form1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlForm form1; + + /// + /// carsGridView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.GridView carsGridView; + } +} diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Properties/AssemblyInfo.cs b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d2d77eb --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CodeBehindPageModel")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CodeBehindPageModel")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ce5d2ab5-42bf-4421-8134-26548b9abf47")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.Debug.config b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.Debug.config new file mode 100644 index 0000000..2e302f9 --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.Debug.config @@ -0,0 +1,30 @@ + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.Release.config b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.Release.config new file mode 100644 index 0000000..c358444 --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.Release.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.config b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.config new file mode 100644 index 0000000..fa2828b --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/Web.config @@ -0,0 +1,36 @@ + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/packages.config b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/packages.config new file mode 100644 index 0000000..702ba1d --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/sqllog.txt b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/sqllog.txt new file mode 100644 index 0000000..80de6cf --- /dev/null +++ b/Appendix_C/CodeBehindPageModel/CodeBehindPageModel/sqllog.txt @@ -0,0 +1,67 @@ +Opened connection at 10/15/2015 11:51:07 PM -04:00 +select cast(serverproperty('EngineEdition') as int) +-- Executing at 10/15/2015 11:51:07 PM -04:00 +-- Completed in 34 ms with result: SqlDataReader + +Closed connection at 10/15/2015 11:51:07 PM -04:00 +Opened connection at 10/15/2015 11:51:07 PM -04:00 +IF db_id(N'AutoLot') IS NOT NULL SELECT 1 ELSE SELECT Count(*) FROM sys.databases WHERE [name]=N'AutoLot' +-- Executing at 10/15/2015 11:51:07 PM -04:00 +-- Completed in 60 ms with result: 1 + +Closed connection at 10/15/2015 11:51:07 PM -04:00 +Opened connection at 10/15/2015 11:51:07 PM -04:00 + +SELECT Count(*) +FROM INFORMATION_SCHEMA.TABLES AS t +WHERE t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN ('dbo.CreditRisks','dbo.Customers','dbo.Orders','dbo.Inventory') + OR t.TABLE_NAME = 'EdmMetadata' +-- Executing at 10/15/2015 11:51:07 PM -04:00 +-- Completed in 78 ms with result: 4 + +Closed connection at 10/15/2015 11:51:07 PM -04:00 +Opened connection at 10/15/2015 11:51:07 PM -04:00 +SELECT + [GroupBy1].[A1] AS [C1] + FROM ( SELECT + COUNT(1) AS [A1] + FROM [dbo].[__MigrationHistory] AS [Extent1] + WHERE [Extent1].[ContextKey] = @p__linq__0 + ) AS [GroupBy1] +-- p__linq__0: 'AutoLotDAL.Migrations.Configuration' (Type = String, Size = 4000) +-- Executing at 10/15/2015 11:51:07 PM -04:00 +-- Completed in 39 ms with result: SqlDataReader + +Closed connection at 10/15/2015 11:51:07 PM -04:00 +Opened connection at 10/15/2015 11:51:07 PM -04:00 +SELECT TOP (1) + [Project1].[C1] AS [C1], + [Project1].[MigrationId] AS [MigrationId], + [Project1].[Model] AS [Model], + [Project1].[ProductVersion] AS [ProductVersion] + FROM ( SELECT + [Extent1].[MigrationId] AS [MigrationId], + [Extent1].[Model] AS [Model], + [Extent1].[ProductVersion] AS [ProductVersion], + 1 AS [C1] + FROM [dbo].[__MigrationHistory] AS [Extent1] + WHERE [Extent1].[ContextKey] = @p__linq__0 + ) AS [Project1] + ORDER BY [Project1].[MigrationId] DESC +-- p__linq__0: 'AutoLotDAL.Migrations.Configuration' (Type = String, Size = 4000) +-- Executing at 10/15/2015 11:51:07 PM -04:00 +-- Completed in 22 ms with result: SqlDataReader + +Closed connection at 10/15/2015 11:51:07 PM -04:00 +Opened connection at 10/15/2015 11:51:07 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 10/15/2015 11:51:08 PM -04:00 +-- Completed in 14 ms with result: SqlDataReader + +Closed connection at 10/15/2015 11:51:08 PM -04:00 diff --git a/Appendix_C/FunWithPageMembers/Default.aspx b/Appendix_C/FunWithPageMembers/Default.aspx new file mode 100644 index 0000000..acec259 --- /dev/null +++ b/Appendix_C/FunWithPageMembers/Default.aspx @@ -0,0 +1,32 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %> + + + + + + + + +
+
+ + Basic Request / Response Info
+
+ +
+
+ +
+
+ + + +
+ +
+
+ + diff --git a/Appendix_C/FunWithPageMembers/Default.aspx.cs b/Appendix_C/FunWithPageMembers/Default.aspx.cs new file mode 100644 index 0000000..d343f0d --- /dev/null +++ b/Appendix_C/FunWithPageMembers/Default.aspx.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class Default : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } + + protected void btnGetBrowserStats_Click(object sender, EventArgs e) + { + string theInfo = ""; + theInfo += $"
  • Is the client AOL? {Request.Browser.AOL}
  • "; + theInfo += $"
  • Does the client support ActiveX? {Request.Browser.ActiveXControls}
  • "; + theInfo += $"
  • Is the client a Beta? {Request.Browser.Beta}
  • "; + theInfo += $"
  • Does the client support Java Applets? {Request.Browser.JavaApplets}
  • "; + theInfo += $"
  • Does the client support Cookies? {Request.Browser.Cookies}
  • "; + theInfo += $"
  • Does the client support VBScript? {Request.Browser.VBScript}
  • "; + lblOutput.Text = theInfo; + } + + protected void btnGetFormData_Click(object sender, System.EventArgs e) + { + // Get value for a widget with ID txtFirstName. + string firstName = txtFirstName.Text; + // Use this value in your page... + lblOutput.Text = firstName; + } + protected void btnHttpResponse_Click(object sender, EventArgs e) + { + Response.Write("My name is:
    "); + Response.Write(this.ToString()); + } + +} \ No newline at end of file diff --git a/Appendix_C/FunWithPageMembers/FunWithPageMembers.sln b/Appendix_C/FunWithPageMembers/FunWithPageMembers.sln new file mode 100644 index 0000000..f6e0e93 --- /dev/null +++ b/Appendix_C/FunWithPageMembers/FunWithPageMembers.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "FunWithPageMembers(1)", ".", "{8166E220-4D9C-4C4D-A4C4-E94254B9028B}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.6" + Debug.AspNetCompiler.VirtualPath = "/localhost_52705" + Debug.AspNetCompiler.PhysicalPath = "..\FunWithPageMembers\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_52705\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_52705" + Release.AspNetCompiler.PhysicalPath = "..\FunWithPageMembers\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_52705\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "52705" + SlnRelativePath = "..\FunWithPageMembers\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8166E220-4D9C-4C4D-A4C4-E94254B9028B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8166E220-4D9C-4C4D-A4C4-E94254B9028B}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_C/FunWithPageMembers/Web.Debug.config b/Appendix_C/FunWithPageMembers/Web.Debug.config new file mode 100644 index 0000000..c358444 --- /dev/null +++ b/Appendix_C/FunWithPageMembers/Web.Debug.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/FunWithPageMembers/Web.config b/Appendix_C/FunWithPageMembers/Web.config new file mode 100644 index 0000000..4aac24b --- /dev/null +++ b/Appendix_C/FunWithPageMembers/Web.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/FunWithPageMembers/packages.config b/Appendix_C/FunWithPageMembers/packages.config new file mode 100644 index 0000000..9e7e9fa --- /dev/null +++ b/Appendix_C/FunWithPageMembers/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_C/PageLifeCycle/Default.aspx b/Appendix_C/PageLifeCycle/Default.aspx new file mode 100644 index 0000000..986c799 --- /dev/null +++ b/Appendix_C/PageLifeCycle/Default.aspx @@ -0,0 +1,20 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + + + +
    +
    +
    +
    + +
    +
    +  
    +
    + + diff --git a/Appendix_C/PageLifeCycle/Default.aspx.cs b/Appendix_C/PageLifeCycle/Default.aspx.cs new file mode 100644 index 0000000..a79891b --- /dev/null +++ b/Appendix_C/PageLifeCycle/Default.aspx.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using static System.IO.File; + +public partial class _Default : System.Web.UI.Page +{ + public _Default() + { + // Explicitly hook into the Load and Unload events. + Load += Page_Load; + Unload += Page_Unload; + Error += _Default_Error; + } + + void _Default_Error(object sender, EventArgs e) + { + Response.Clear(); + Response.Write("I am sorry...I can't find a required file.
    "); + Response.Write($"The error was: {Server.GetLastError().Message}"); + Server.ClearError(); + } + + protected void Page_Load(object sender, EventArgs e) + { + Response.Write("Load event fired!"); + } + + protected void Page_Unload(object sender, EventArgs e) + { + // No longer possible to emit data to the HTTP + // response, so we will write to a local file. + WriteAllText(@"C:\MyLog.txt", "Page unloading!"); + } + + protected void btnPostback_Click(object sender, EventArgs e) + { + // Nothing happens here, this is just to ensure a + // postback to the page. + } + protected void btnTriggerError_Click(object sender, EventArgs e) + { + ReadAllText(@"C:\IDontExist.txt"); + } +} \ No newline at end of file diff --git a/Appendix_C/PageLifeCycle/PageLifeCycle.sln b/Appendix_C/PageLifeCycle/PageLifeCycle.sln new file mode 100644 index 0000000..60fc842 --- /dev/null +++ b/Appendix_C/PageLifeCycle/PageLifeCycle.sln @@ -0,0 +1,39 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "PageLifeCycle", "C:\Users\Japikse\OneDrive\Book\Troelsen\Chapters\C#_6\Chapter31\PageLifeCycle\", "{CBC5EA54-169B-4A27-B5F9-043365A7D792}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.6" + Debug.AspNetCompiler.VirtualPath = "/localhost_34466" + Debug.AspNetCompiler.PhysicalPath = "C:\Users\Japikse\OneDrive\Book\Troelsen\Chapters\C#_6\Chapter31\PageLifeCycle\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_34466\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_34466" + Release.AspNetCompiler.PhysicalPath = "C:\Users\Japikse\OneDrive\Book\Troelsen\Chapters\C#_6\Chapter31\PageLifeCycle\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_34466\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "34466" + SlnRelativePath = "C:\Users\Japikse\OneDrive\Book\Troelsen\Chapters\C#_6\Chapter31\PageLifeCycle\" + DefaultWebSiteLanguage = "Visual C#" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CBC5EA54-169B-4A27-B5F9-043365A7D792}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CBC5EA54-169B-4A27-B5F9-043365A7D792}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_C/PageLifeCycle/Web.Debug.config b/Appendix_C/PageLifeCycle/Web.Debug.config new file mode 100644 index 0000000..c358444 --- /dev/null +++ b/Appendix_C/PageLifeCycle/Web.Debug.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/PageLifeCycle/Web.config b/Appendix_C/PageLifeCycle/Web.config new file mode 100644 index 0000000..1387ada --- /dev/null +++ b/Appendix_C/PageLifeCycle/Web.config @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + diff --git a/Appendix_C/PageLifeCycle/packages.config b/Appendix_C/PageLifeCycle/packages.config new file mode 100644 index 0000000..9e7e9fa --- /dev/null +++ b/Appendix_C/PageLifeCycle/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_C/SimpleWebPage/HtmlPage1.html b/Appendix_C/SimpleWebPage/HtmlPage1.html new file mode 100644 index 0000000..f32c965 --- /dev/null +++ b/Appendix_C/SimpleWebPage/HtmlPage1.html @@ -0,0 +1,38 @@ + + + + + + + + + This is my simple web page + + + +

    Simple HTML Page

    +

    +
    + Please enter a message. +

    + + +
    +

    + Your Message: +

    +

    + + +

    +
    + + + + diff --git a/Appendix_C/SimpleWebPage/SimpleWebPage.sln b/Appendix_C/SimpleWebPage/SimpleWebPage.sln new file mode 100644 index 0000000..3255e8d --- /dev/null +++ b/Appendix_C/SimpleWebPage/SimpleWebPage.sln @@ -0,0 +1,15 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8F800354-45D7-4E10-A394-6B8C415684C9}" + ProjectSection(SolutionItems) = preProject + HtmlPage1.html = HtmlPage1.html + EndProjectSection +EndProject +Global + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/App.config b/Appendix_C/SinglePageModel/AutoLotDAL/App.config new file mode 100644 index 0000000..505e8eb --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/App.config @@ -0,0 +1,20 @@ + + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/AutoLotDAL.csproj b/Appendix_C/SinglePageModel/AutoLotDAL/AutoLotDAL.csproj new file mode 100644 index 0000000..8f61282 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/AutoLotDAL.csproj @@ -0,0 +1,99 @@ + + + + + Debug + AnyCPU + {29C6F0F4-94E3-4C30-9DB9-02D340ACE46A} + Library + Properties + AutoLotDAL + AutoLotDAL + v4.6 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + True + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + True + + + + + + + + + + + + + + + + + + + + 201508040328457_Initial.cs + + + + 201508040354323_TimeStamp.cs + + + + + + + + + + + + + + + + + + 201508040328457_Initial.cs + + + 201508040354323_TimeStamp.cs + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/EF/AutoLotEntities.cs b/Appendix_C/SinglePageModel/AutoLotDAL/EF/AutoLotEntities.cs new file mode 100644 index 0000000..40160e4 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/EF/AutoLotEntities.cs @@ -0,0 +1,66 @@ +using System; +using System.Data.Entity.Core.Objects; +using System.Data.Entity.Infrastructure; +using System.Data.Entity.Infrastructure.Interception; +using System.Linq; +using System.Web; +using AutoLotDAL.Models; + +namespace AutoLotDAL.EF +{ + using System.Data.Entity; + + public class AutoLotEntities : DbContext + { + static readonly DatabaseLogger DatabaseLogger = + new DatabaseLogger($"{HttpRuntime.AppDomainAppPath}/sqllog.txt"); + public AutoLotEntities() + : base("name=AutoLotConnection") + { + //DbInterception.Add(new ConsoleWriterInterceptor()); + DatabaseLogger.StartLogging(); + DbInterception.Add(DatabaseLogger); + var context = (this as IObjectContextAdapter).ObjectContext; + context.ObjectMaterialized += OnObjectMaterialized; + context.SavingChanges += OnSavingChanges; + } + + private void OnSavingChanges(object sender, EventArgs eventArgs) + { + //Sender is of type ObjectContext. Can get current and original values, and + //cancel/modify the save operation as desired. + //var context = sender as ObjectContext; + //if (context == null) return; + //foreach (ObjectStateEntry item in + // context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added)) + //{ + // //Do something important here + // if ((item.Entity as Inventory)!=null) + // { + // var entity = (Inventory) item.Entity; + // if (entity.Color == "Red") + // { + // item.RejectPropertyChanges(nameof(entity.Color)); + // } + // } + //} + + } + + private void OnObjectMaterialized(object sender, System.Data.Entity.Core.Objects.ObjectMaterializedEventArgs e) + { + } + + public virtual DbSet CreditRisks { get; set; } + public virtual DbSet Customers { get; set; } + public virtual DbSet Inventory { get; set; } + public virtual DbSet Orders { get; set; } + protected override void Dispose(bool disposing) + { + DbInterception.Remove(DatabaseLogger); + DatabaseLogger.StopLogging(); + base.Dispose(disposing); + } + } + +} \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs new file mode 100644 index 0000000..91ad0db --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Data.Entity.Infrastructure.Interception; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using static System.Console; + +namespace AutoLotDAL.Interception +{ + public class ConsoleWriterInterceptor : IDbCommandInterceptor + { + private void WriteInfo(bool isAsync, string commandText) + { + WriteLine($"IsAsync: {isAsync}, Command Text: {commandText}"); + } + public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync,command.CommandText); + } + + public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.Designer.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.Designer.cs new file mode 100644 index 0000000..439cd88 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.Designer.cs @@ -0,0 +1,29 @@ +// +namespace AutoLotDAL.Migrations +{ + using System.CodeDom.Compiler; + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] + public sealed partial class Initial : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(Initial)); + + string IMigrationMetadata.Id + { + get { return "201508040328457_Initial"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.cs new file mode 100644 index 0000000..b92eea2 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.cs @@ -0,0 +1,16 @@ +namespace AutoLotDAL.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class Initial : DbMigration + { + public override void Up() + { + } + + public override void Down() + { + } + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.resx b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.resx new file mode 100644 index 0000000..a484e61 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040328457_Initial.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + H4sIAAAAAAAEAO1azW7jNhC+F+g7CDoWWSvJokAb2LtInaQwmj/EyaK3gJHGDrEUpZJUEKPok/XQR+ordPRHSZRkS44dZ4sgl5jk/HDmmyE5o3///mf4+dln1hMISQM+sg8G+7YF3A08yucjO1KzDz/Znz99/93w1POfrS/5uo/xOqTkcmQ/KhUeOY50H8EncuBTVwQymKmBG/gO8QLncH//Z+fgwAFkYSMvyxreRFxRH5If+HMccBdCFRF2EXjAZDaOM9OEq3VJfJAhcWFkH0cqOA/UyfH54PTMto4ZJajEFNjMtgjngSIKVTy6kzBVIuDzaYgDhN0uQsB1M8IkZKofFcu77mL/MN6FUxDmrNxIqsDvyfDgY2YWxyRfy7i2Nhsa7hQNrBbxrhPjjeyxAI+qGyq/2pYp7mjMRLy0Yt3UFYOCbs8qZvc0FhAy8d+eNY6YigSMOERKELZnXUcPjLq/weI2+Ap8xCPGyiqikjhXGcChaxGEINTiBma54qjsxLMtp0rrmMSa1KBLNzbh6uOhbV2iEuSBgUZCyQhTFQj4FTgIosC7JkqBQEdOPEhsWdPAkHdGhVTxv7lIxB9GkW1dkOdz4HP1OLJ/xLA5o8/g5QOZFnecYswhjRIRrBJ0TrYhZ+gUkFkOpAQ8IHrCKKN6B9H/GUQo55I80XliC0PilfDQ27Z1AyyZlo80TBP3IJm6L4B1JgL/JmA5kZ65vyViDgp1Dhqnp0Ek3HVxnfDqB+qEZEeITmSvA2lN+FqY7hZDK3iQDip3RSIya4ThhD/hjgKxuM+xWgDRnKtBsbagCYxLtdLwf0mE5FJbIiTXeq0I0VvsFyWabFe5n6wVJ50gt7kouSBft570xwELxLaFXMPbOVh6RbQZOq0h3yV4jqUMXJroY0ZPrkt1e6fcs1Yplhq0sjE0LIYNDTFQUAt8wdlmQFzxE2CgwDp205fJmEiXeHUD4068zjrp9FfolB2gVX1+qInBwAQRxwRh+O6TGOqUq3oUU+7SkLAVNjHousd/vF8txJw5gRB4HLcrdv8i6VqI4YVV9hk6JWwth5xxarQ5t+0I6e3aVpYNaCnOsi0CeC2sNeveydeNr4xeUGv2xcuEbxxpacpDGoUUIDIFssM9maQgGy4JdxKye4LMkryJn5jvFFStZoHcijybI6hU0agB0WCU2bORjQbiCib5EVLjkEXHCvJSyq5xKM0ZXEoeaGClj7XSsrajz4RFhwNHb6GifQ1gHY6JEqdcZTN4qzvtYAXzTly3wbL81yUDrtS6S84rMSnBsPPu8wuGjraiOOqk1dG8iuq0lFGHFyQM8Q5WKqtmI9Y0ramOP0z7Vxz9lIfjyobCo9ZWS0JUkDkYs/GV1IOk6HFCFHkg8TVw7Pm1ZWZuaQm1XFo9fdTdlodgThP/X0lkaYm5nGbqaTgjPsO9+XESTx4BZY8vIU7K24QR0fJextt65PPlyb2dS6mSVGZUGu7OqygWlVkVo3VOQ8ewTO1QqjmgdpZXfdrN4zrAXuDvlnTRxdutpO++3rivW4+1ro5Oj+3+Xm6hazOorreV7dlSvds+VLLnSIVJ8wtlZ44trhrr+7aVRwf/LqHdhFXbeKQFoDKLdKSHb9PyTkWLdKg7D129KXPRg6+Mkdrdx1yipes7kHHXGWb3jtV95dpFJF1iW2igJ+rFl5DpQirwB/GCwfQPNmYU91ssuCCczkCqtFppH+4fHBr96bfTK3ak9FjnhvHOGm40tu/KwmrPXkKtx8afiHAf46aAUaQsGK/TUluLbf827Ltz3p5zGq4Ir9vV24pvGtxfK/FMuAfPI/vPhOTImvx+n1LtWYmGR9a+9dfLun+d5cZEPcSu0QbbUTNqK84t9582FHOVdtOGeBrdpY2G8SZ6Njvt0mSFyNfuybxSF6btvfZN9lyKsuVr90R2BZcldZXtdVK+jc5JvQjatS+yoi2SvmFGtvcQoJ/TfFhpqnTsmyxtmzQKaa10N3ZV2psqTcxbOghrNlyaJLyRfswaHZiKOUvlqjfVbjFhVS2ebnd7Pfop9doBRn7py3VMOZLOCxbxd+wc3ErM6zUTPgvy1GNolC8xb2SgiIcJ4VgoOiOuwmkXpEy+pvlCWIRLTv0H8Cb8KlJhpHDL4D+wCj7iFLZMftI0quo8vAqTr2g2sQVUk+IW4Ir/ElHmab3PGq7fLSzi3Jhdc2Nfqvi6O19oTpcB78goM59O6bfghwyZySs+JU+wjm53Es5hTtxFXgJqZ7LaEVWzD08omQviy4xHQY8/EcOe//zpP02XrKrAMQAA + + + dbo + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.Designer.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.Designer.cs new file mode 100644 index 0000000..ce84541 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.Designer.cs @@ -0,0 +1,29 @@ +// +namespace AutoLotDAL.Migrations +{ + using System.CodeDom.Compiler; + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] + public sealed partial class TimeStamp : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(TimeStamp)); + + string IMigrationMetadata.Id + { + get { return "201508040354323_TimeStamp"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.cs new file mode 100644 index 0000000..83f199e --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.cs @@ -0,0 +1,26 @@ +namespace AutoLotDAL.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class TimeStamp : DbMigration + { + public override void Up() + { + AddColumn("dbo.CreditRisks", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.Customers", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.Orders", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.Inventory", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + CreateIndex("dbo.CreditRisks", new[] { "LastName", "FirstName" }, unique: true, name: "IDX_CreditRisk_Name"); + } + + public override void Down() + { + DropIndex("dbo.CreditRisks", "IDX_CreditRisk_Name"); + DropColumn("dbo.Inventory", "Timestamp"); + DropColumn("dbo.Orders", "Timestamp"); + DropColumn("dbo.Customers", "Timestamp"); + DropColumn("dbo.CreditRisks", "Timestamp"); + } + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.resx b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.resx new file mode 100644 index 0000000..465847c --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/201508040354323_TimeStamp.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + H4sIAAAAAAAEAO1b227jNhB9L9B/EPRYpFacRYFtYO8i6ySF0dwQJ4t9Cxhp7BArkVqSSmMU/bI+9JP6Cx3dKImSbNmxc9kGeUlIzoXDM8PRDPPv3/8MPj4EvnUPQlLOhna/t2tbwFzuUTYb2pGa/vze/vjhxx8GR17wYH3O172L1yElk0P7Tqlw33GkewcBkb2AuoJLPlU9lwcO8bizt7v7q9PvO4AsbORlWYPLiCkaQPIH/jnizIVQRcQ/5R74MhvHmUnC1TojAciQuDC0DyLFT7g6PDjpHR3b1oFPCSoxAX9qW4QxrohCFfevJUyU4Gw2CXGA+FfzEHDdlPgSMtX3i+Vdd7G7F+/CKQhzVm4kFQ9WZNh/l5nFMcnXMq6tzYaGO0IDq3m868R4Q3skwKPqksqvtmWK2x/5Il5asW56FL2CbscqZnc0FhAy8c+ONYp8FQkYMoiUIP6OdRHd+tT9HeZX/CuwIYt8v6wiKolzlQEcuhA8BKHmlzDNFUdlx55tOVVaxyTWpAZdurExU+/2bOsMlSC3PmgklIwwUVzAb8BAEAXeBVEKBB7k2IPEljUNDHnHVEgV/5qLRPyhF9nWKXk4ATZTd0P7F3SbY/oAXj6QaXHNKPoc0igRwTJBJ+Rp5Fyhh0pFgjAX9IkyItAOsbtGQmCcmJ8m3BJRFQXeN8tfw/wjHoSRAgMAA6cA+GLYJ1AHsSLoM6o3yL9B/qVAHrU9I/d0lpAaep8LD7FpW5fgJ9PyjobppdhLpm4KNzgWPLjkfk6kZ26uiJiBwo3zxukJj4QLa3phwms1F0xInsn/EtnrOKAmfCoP7ObxS3iQDip/n36DW290mjG7R/tzMb/JPatwG3Ou5ji1BU2us1Ar7ayP8edcaos/51qv5c96i6v5tCZ7rnuVrOXVnRxkcz59Sr5u/aIbcZ+LbQu5gLdLe71Le6X4Yzp6a4Dq4uoHUnKXJvqYvp7rUt3eEfOsZYqlx1/ZGJ4COjkN0a1Ri6Hdt033PWeH4IMC68BNv6hHRLrEq8MBd+J11kkH60KnLDmp6vNTTQyGERCxBxMfgSUxMFGm6jGHMpeGxF9iE4Oue7SK96uFmDOHEAKLo8yS3T9KuhZinMIy+wycErYWQ86449oOt+3CW/loW1k2oKW4ebcI4LWw1qx7p7Nu/N5cCWrNZ/E44RtHWhrykEYhBYhMgSwVSSYpyIaU5lpCltXI7Eoy8RPznYCq1dqQWxFncwSVKnE1IBqMMns2stFAXMIkv0JqHDLvWEJeCtk1DqU5g0vpBBpY6WuttKzt6jNh0eHC0VuoaF8DWIdrosQpV9l03upOO1jBzODrNlgU/7pEwKVad4l5JSYlGHbefZ5gaG8rivpOWtXPq/9OS/l/cErCEDPGUjsgG7EmaS9g9PNk9Up5kPJwXNlQMNfaakmICjIDYzZO9zxIyl+HRJFbEueIIy+oLTNjS4ur5dLq4aN+bLkL5jTx75VAlrZGymGmHoYz4mPcWxAH8SSpLZ/4AuKkLUN8IlpqEfhtEQVscXBv51KqKZYZlYa78yrKhmVWxWh3TqVvjDKr0nCd18AxrFy74GqHWcsLqvjohh7trI/ATkvo6YKcVtI33Lxo3LRet11Bk6YTqyOmha7NpLrGWjZoS8V2EZ/NwC77TKowaf5y+i5AUqRT6+OklUcHrCyg3eYJpSW5Mot0ZAWcpAW3ihbpUHceup5W5qIHXzHearmiuURL1zmjkRsOsjxt+fuRWuKWLrEtNNI99eKkbTKXCoJevKA3+eaPfIr7LRacEkanaKm0Fm3v7fb3jHcoL+dNiCOl53d+GPJsrWoa23dp2XzFplStO83uiXDvSFMjcsw8eBjafyak+9b48MtNYZebeHDHSu6YfWtvxxrLa0a/RbjwSkRg/VWraReartPd3oye/Y3rWSu0C/5H9nSs9fSKsvjC01v9Pcf/BqtbgtarR0JD2vi03f2tAKEBa0uDwJeblEq7/m7s6o95BdBZbkz0KLEvAUktSeXT9ZS3gqRyG3lDbl/pGm+Ip9Ekfr0BahOd02ftlWbtgKfujD5RL7StOvEqO59F8+CpO5PPBZcFFcnt9TNfR/+y3opY3NAr9x8XNifTL+Oh7d1yPOc0IFZamx27lwubl41CWvtNjb3N9tZmE/OWPt6abc8mCS+kK7pGH7RizlJx9kU1PU1YVdsO293eCl3NekUKPb/0f08YciSdFSzi/4Ji4FZ8Xq8ZsynPQ4+hUb7ETP9AEQ8DwoFQdEpchdMuSJm8wPtM/AiXHAW34I3ZeaQw78EtQ3DrV/ARh7BF8pPWbVXnwXmYvGXbxBZQTYpbgHP2KaK+p/U+bkjKWljEsTHL9OKzVHHGN5trTmecdWSUmU+H9CsIQh+ZyXM2Ifewjm7XEk5gRtx5XlhsZ7L8IKpmHxxSMhMkkBmPgh7/RAx7wcOH/wBn2awt/jcAAA== + + + dbo + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/Configuration.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/Configuration.cs new file mode 100644 index 0000000..03a7261 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Migrations/Configuration.cs @@ -0,0 +1,31 @@ +namespace AutoLotDAL.Migrations +{ + using System; + using System.Data.Entity; + using System.Data.Entity.Migrations; + using System.Linq; + + internal sealed class Configuration : DbMigrationsConfiguration + { + public Configuration() + { + AutomaticMigrationsEnabled = false; + } + + protected override void Seed(AutoLotDAL.EF.AutoLotEntities context) + { + // This method will be called after migrating to the latest version. + + // You can use the DbSet.AddOrUpdate() helper extension method + // to avoid creating duplicate seed data. E.g. + // + // context.People.AddOrUpdate( + // p => p.FullName, + // new Person { FullName = "Andrew Peters" }, + // new Person { FullName = "Brice Lambson" }, + // new Person { FullName = "Rowan Miller" } + // ); + // + } + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Models/CreditRisk.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Models/CreditRisk.cs new file mode 100644 index 0000000..7f728e5 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Models/CreditRisk.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace AutoLotDAL.Models +{ + public partial class CreditRisk + { + [Key] + public int CustId { get; set; } + + [StringLength(50)] + [Index("IDX_CreditRisk_Name",IsUnique = true,Order=2)] + public string FirstName { get; set; } + + [StringLength(50)] + [Index("IDX_CreditRisk_Name", IsUnique = true, Order = 1)] + public string LastName { get; set; } + + [Timestamp] + public byte[] Timestamp { get; set; } + + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Models/Customer.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Models/Customer.cs new file mode 100644 index 0000000..2b4c04a --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Models/Customer.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace AutoLotDAL.Models +{ + public partial class Customer + { + [Key] + public int CustId { get; set; } + + [StringLength(50)] + public string FirstName { get; set; } + + [StringLength(50)] + public string LastName { get; set; } + + [Timestamp] + public byte[] Timestamp { get; set; } + + [NotMapped] + public string FullName => FirstName + " " + LastName; + + public virtual ICollection Orders { get; set; } = new HashSet(); + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Models/Inventory.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Models/Inventory.cs new file mode 100644 index 0000000..1c8322e --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Models/Inventory.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace AutoLotDAL.Models +{ + [Table("Inventory")] + public partial class Inventory + { + [Key] + public int CarId { get; set; } + + [StringLength(50)] + public string Make { get; set; } + + [StringLength(50)] + public string Color { get; set; } + + [StringLength(50)] + public string PetName { get; set; } + + [Timestamp] + public byte[] Timestamp { get; set; } + + public virtual ICollection Orders + { get; set; } = new HashSet(); + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Models/Order.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Models/Order.cs new file mode 100644 index 0000000..bf092d5 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Models/Order.cs @@ -0,0 +1,26 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace AutoLotDAL.Models +{ + public partial class Order + { + [Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int OrderId { get; set; } + + [Required] + public int CustId { get; set; } + + [Required] + public int CarId { get; set; } + + [Timestamp] + public byte[] Timestamp { get; set; } + + [ForeignKey("CustId")] + public virtual Customer Customer { get; set; } + + [ForeignKey("CarId")] + public virtual Inventory Car { get; set; } + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Models/Partials/InventoryPartial.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Models/Partials/InventoryPartial.cs new file mode 100644 index 0000000..7cc6b15 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Models/Partials/InventoryPartial.cs @@ -0,0 +1,8 @@ +namespace AutoLotDAL.Models +{ + public partial class Inventory + { + public override string ToString() => + $"{this.PetName ?? "**No Name**"} is a {this.Color} {this.Make} with ID {this.CarId}."; + } +} \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Properties/AssemblyInfo.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9742f90 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDAL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDAL")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("29c6f0f4-94e3-4c30-9db9-02d340ace46a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Repos/BaseRepo.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/BaseRepo.cs new file mode 100644 index 0000000..8275a9e --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/BaseRepo.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity.Infrastructure; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.EF; + +namespace AutoLotDAL.Repos +{ + public abstract class BaseRepo: IDisposable + { + public AutoLotEntities Context { get; } + = new AutoLotEntities(); + + internal int SaveChanges() + { + try + { + return Context.SaveChanges(); + } + catch (DbUpdateConcurrencyException ex) + { + //Thrown when there is a concurrency errors + //If Entries propery is null, no records were modified + //entities in Entries threw error due to timestamp/conncurrency + //for now, just rethrow the exception + throw; + } + catch (DbUpdateException ex) + { + //Thrown when database update fails + //Examine the inner execption(s) for additional + //details and affected objects + //for now, just rethrow the exception + throw; + } + catch (CommitFailedException ex) + { + //handle transaction failures here + //for now, just rethrow the exception + throw; + } + catch (Exception ex) + { + //some other exception happened and should be handled + throw; + } + } + internal async Task SaveChangesAsync() + { + try + { + return await Context.SaveChangesAsync(); + } + catch (DbUpdateConcurrencyException ex) + { + //Thrown when there is a concurrency errors + //for now, just rethrow the exception + throw; + } + catch (DbUpdateException ex) + { + //Thrown when database update fails + //Examine the inner execption(s) for additional + //details and affected objects + //for now, just rethrow the exception + throw; + } + catch (CommitFailedException ex) + { + //handle transaction failures here + //for now, just rethrow the exception + throw; + } + catch (Exception ex) + { + //some other exception happened and should be handled + throw; + } + } + + bool disposed = false; + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + protected virtual void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + Context.Dispose(); + // Free any managed objects here. + // + } + + // Free any unmanaged objects here. + // + disposed = true; + } + } + +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Repos/CreditRiskRepo.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/CreditRiskRepo.cs new file mode 100644 index 0000000..af70f6b --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/CreditRiskRepo.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.Repos +{ + public class CreditRiskRepo:BaseRepo,IRepo + { + public int Add(CreditRisk entity) + { + Context.CreditRisks.Add(entity); + return SaveChanges(); + } + + public Task AddAsync(CreditRisk entity) + { + Context.CreditRisks.Add(entity); + return SaveChangesAsync(); + } + + public int AddRange(IList entities) + { + Context.CreditRisks.AddRange(entities); + return SaveChanges(); + } + public Task AddRangeAsync(IList entities) + { + Context.CreditRisks.AddRange(entities); + return SaveChangesAsync(); + } + public int Save(CreditRisk entity) + { + Context.Entry(entity).State = EntityState.Modified; + return SaveChanges(); + } + + public Task SaveAsync(CreditRisk entity) + { + Context.Entry(entity).State = EntityState.Modified; + return SaveChangesAsync(); + } + + public int Delete(int id, byte[] timeStamp) + { + Context.Entry(new CreditRisk() + { + CustId = id, + Timestamp = timeStamp + }).State = EntityState.Deleted; + return SaveChanges(); + } + + public Task DeleteAsync(int id, byte[] timeStamp) + { + Context.Entry(new CreditRisk() + { + CustId = id, + Timestamp = timeStamp + }).State = EntityState.Deleted; + return SaveChangesAsync(); + } + public int Delete(CreditRisk entity) + { + Context.Entry(entity).State = EntityState.Deleted; + return SaveChanges(); + } + + public Task DeleteAsync(CreditRisk entity) + { + Context.Entry(entity).State = EntityState.Deleted; + return SaveChangesAsync(); + } + + public CreditRisk GetOne(int? id) + => Context.CreditRisks.Find(id); + + public Task GetOneAsync(int? id) + => Context.CreditRisks.FindAsync(id); + + public List GetAll() + => Context.CreditRisks.ToList(); + + public Task> GetAllAsync() + => Context.CreditRisks.ToListAsync(); + + public List ExecuteQuery(string sql) + => Context.CreditRisks.SqlQuery(sql).ToList(); + + public Task> ExecuteQueryAsync(string sql) + => Context.CreditRisks.SqlQuery(sql).ToListAsync(); + public List ExecuteQuery( + string sql, object[] sqlParametersObjects) + => Context.CreditRisks.SqlQuery(sql, sqlParametersObjects).ToList(); + public Task> ExecuteQueryAsync( + string sql, object[] sqlParametersObjects) + => Context.CreditRisks.SqlQuery(sql).ToListAsync(); + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Repos/CustomerRepo.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/CustomerRepo.cs new file mode 100644 index 0000000..f5888ac --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/CustomerRepo.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.Repos +{ + public class CustomerRepo:BaseRepo,IRepo + { + public int Add(Customer entity) + { + Context.Customers.Add(entity); + return SaveChanges(); + } + + public Task AddAsync(Customer entity) + { + Context.Customers.Add(entity); + return SaveChangesAsync(); + } + + public int AddRange(IList entities) + { + Context.Customers.AddRange(entities); + return SaveChanges(); + } + public Task AddRangeAsync(IList entities) + { + Context.Customers.AddRange(entities); + return SaveChangesAsync(); + } + public int Save(Customer entity) + { + Context.Entry(entity).State = EntityState.Modified; + return SaveChanges(); + } + + public Task SaveAsync(Customer entity) + { + Context.Entry(entity).State = EntityState.Modified; + return SaveChangesAsync(); + } + + public int Delete(int id, byte[] timeStamp) + { + Context.Entry(new Customer() + { + CustId = id, + Timestamp = timeStamp + }).State = EntityState.Deleted; + return SaveChanges(); + } + + public Task DeleteAsync(int id, byte[] timeStamp) + { + Context.Entry(new Customer() + { + CustId = id, + Timestamp = timeStamp + }).State = EntityState.Deleted; + return SaveChangesAsync(); + } + public int Delete(Customer entity) + { + Context.Entry(entity).State = EntityState.Deleted; + return SaveChanges(); + } + + public Task DeleteAsync(Customer entity) + { + Context.Entry(entity).State = EntityState.Deleted; + return SaveChangesAsync(); + } + + public Customer GetOne(int? id) + => Context.Customers.Find(id); + + public Task GetOneAsync(int? id) + => Context.Customers.FindAsync(id); + + public List GetAll() + => Context.Customers.ToList(); + + public Task> GetAllAsync() + => Context.Customers.ToListAsync(); + + public List ExecuteQuery(string sql) + => Context.Customers.SqlQuery(sql).ToList(); + + public Task> ExecuteQueryAsync(string sql) + => Context.Customers.SqlQuery(sql).ToListAsync(); + public List ExecuteQuery( + string sql, object[] sqlParametersObjects) + => Context.Customers.SqlQuery(sql, sqlParametersObjects).ToList(); + public Task> ExecuteQueryAsync( + string sql, object[] sqlParametersObjects) + => Context.Customers.SqlQuery(sql).ToListAsync(); + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Repos/IRepo.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/IRepo.cs new file mode 100644 index 0000000..8d2d2e7 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/IRepo.cs @@ -0,0 +1,29 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.Repos +{ + public interface IRepo + { + int Add(T entity); + Task AddAsync(T entity); + int AddRange(IList entities); + Task AddRangeAsync(IList entities); + int Save(T entity); + Task SaveAsync(T entity); + int Delete(int id, byte[] timeStamp); + Task DeleteAsync(int id, byte[] timeStamp); + int Delete(T entity); + Task DeleteAsync(T entity); + T GetOne(int? id); + Task GetOneAsync(int? id); + List GetAll(); + Task> GetAllAsync(); + + List ExecuteQuery(string sql); + Task> ExecuteQueryAsync(string sql); + List ExecuteQuery(string sql,object[] sqlParametersObjects ); + Task> ExecuteQueryAsync(string sql, object[] sqlParametersObjects); + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Repos/InventoryRepo.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/InventoryRepo.cs new file mode 100644 index 0000000..990b3d0 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/InventoryRepo.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.Repos +{ + public class InventoryRepo : BaseRepo, IRepo + { + public int Add(Inventory entity) + { + Context.Inventory.Add(entity); + return SaveChanges(); + } + + public Task AddAsync(Inventory entity) + { + Context.Inventory.Add(entity); + return SaveChangesAsync(); + } + + public int AddRange(IList entities) + { + Context.Inventory.AddRange(entities); + return SaveChanges(); + } + public Task AddRangeAsync(IList entities) + { + Context.Inventory.AddRange(entities); + return SaveChangesAsync(); + } + public int Save(Inventory entity) + { + Context.Entry(entity).State = EntityState.Modified; + return SaveChanges(); + } + + public Task SaveAsync(Inventory entity) + { + Context.Entry(entity).State = EntityState.Modified; + return SaveChangesAsync(); + } + + public int Delete(int id, byte[] timeStamp) + { + Context.Entry(new Inventory() + { + CarId=id, + Timestamp = timeStamp + }).State = EntityState.Deleted; + return SaveChanges(); + } + + public Task DeleteAsync(int id, byte[] timeStamp) + { + Context.Entry(new Inventory() + { + CarId = id, + Timestamp = timeStamp + }).State = EntityState.Deleted; + return SaveChangesAsync(); + } + + public int Delete(Inventory entity) + { + Context.Entry(entity).State = EntityState.Deleted; + return SaveChanges(); + } + + public Task DeleteAsync(Inventory entity) + { + Context.Entry(entity).State = EntityState.Deleted; + return SaveChangesAsync(); + } + + public Inventory GetOne(int? id) + => Context.Inventory.Find(id); + + public Task GetOneAsync(int? id) + => Context.Inventory.FindAsync(id); + + public List GetAll() + => Context.Inventory.ToList(); + + public Task> GetAllAsync() + => Context.Inventory.ToListAsync(); + + public List ExecuteQuery(string sql) + => Context.Inventory.SqlQuery(sql).ToList(); + + public Task> ExecuteQueryAsync(string sql) + => Context.Inventory.SqlQuery(sql).ToListAsync(); + public List ExecuteQuery( + string sql, object[] sqlParametersObjects) + => Context.Inventory.SqlQuery(sql, sqlParametersObjects).ToList(); + public Task> ExecuteQueryAsync( + string sql, object[] sqlParametersObjects) + => Context.Inventory.SqlQuery(sql).ToListAsync(); + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/Repos/OrderRepo.cs b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/OrderRepo.cs new file mode 100644 index 0000000..fa05f65 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/Repos/OrderRepo.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.Repos +{ + public class OrderRepo:BaseRepo,IRepo + { + public int Add(Order entity) + { + Context.Orders.Add(entity); + return SaveChanges(); + } + + public Task AddAsync(Order entity) + { + Context.Orders.Add(entity); + return SaveChangesAsync(); + } + + public int AddRange(IList entities) + { + Context.Orders.AddRange(entities); + return SaveChanges(); + } + public Task AddRangeAsync(IList entities) + { + Context.Orders.AddRange(entities); + return SaveChangesAsync(); + } + public int Save(Order entity) + { + Context.Entry(entity).State = EntityState.Modified; + return SaveChanges(); + } + + public Task SaveAsync(Order entity) + { + Context.Entry(entity).State = EntityState.Modified; + return SaveChangesAsync(); + } + + public int Delete(int id, byte[] timeStamp) + { + Context.Entry(new Order() + { + OrderId = id, + Timestamp = timeStamp + }).State = EntityState.Deleted; + return SaveChanges(); + } + + public Task DeleteAsync(int id, byte[] timeStamp) + { + Context.Entry(new Order() + { + OrderId = id, + Timestamp = timeStamp + }).State = EntityState.Deleted; + return SaveChangesAsync(); + } + public int Delete(Order entity) + { + Context.Entry(entity).State = EntityState.Deleted; + return SaveChanges(); + } + + public Task DeleteAsync(Order entity) + { + Context.Entry(entity).State = EntityState.Deleted; + return SaveChangesAsync(); + } + + public Order GetOne(int? id) + => Context.Orders.Find(id); + + public Task GetOneAsync(int? id) + => Context.Orders.FindAsync(id); + + public List GetAll() + => Context.Orders.ToList(); + + public Task> GetAllAsync() + => Context.Orders.ToListAsync(); + + public List ExecuteQuery(string sql) + => Context.Orders.SqlQuery(sql).ToList(); + + public Task> ExecuteQueryAsync(string sql) + => Context.Orders.SqlQuery(sql).ToListAsync(); + public List ExecuteQuery( + string sql, object[] sqlParametersObjects) + => Context.Orders.SqlQuery(sql, sqlParametersObjects).ToList(); + public Task> ExecuteQueryAsync( + string sql, object[] sqlParametersObjects) + => Context.Orders.SqlQuery(sql).ToListAsync(); + } +} diff --git a/Appendix_C/SinglePageModel/AutoLotDAL/packages.config b/Appendix_C/SinglePageModel/AutoLotDAL/packages.config new file mode 100644 index 0000000..c089e85 --- /dev/null +++ b/Appendix_C/SinglePageModel/AutoLotDAL/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/SinglePageModel.sln b/Appendix_C/SinglePageModel/SinglePageModel.sln new file mode 100644 index 0000000..64a253e --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SinglePageModel", "SinglePageModel\SinglePageModel.csproj", "{419CE338-C91B-402B-8FE3-65838EB4EEAC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL", "AutoLotDAL\AutoLotDAL.csproj", "{29C6F0F4-94E3-4C30-9DB9-02D340ACE46A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {419CE338-C91B-402B-8FE3-65838EB4EEAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {419CE338-C91B-402B-8FE3-65838EB4EEAC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {419CE338-C91B-402B-8FE3-65838EB4EEAC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {419CE338-C91B-402B-8FE3-65838EB4EEAC}.Release|Any CPU.Build.0 = Release|Any CPU + {29C6F0F4-94E3-4C30-9DB9-02D340ACE46A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {29C6F0F4-94E3-4C30-9DB9-02D340ACE46A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {29C6F0F4-94E3-4C30-9DB9-02D340ACE46A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {29C6F0F4-94E3-4C30-9DB9-02D340ACE46A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx b/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx new file mode 100644 index 0000000..9161b02 --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx @@ -0,0 +1,35 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SinglePageModel.Default" %> +<%@ Import Namespace="AutoLotDAL.Models" %> +<%@ Import Namespace="AutoLotDAL.Repos" %> + + + + Fun with Web Pages! + + + +
    +
    + + + + + + + + + + + + +
    +
    + + diff --git a/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx.cs b/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx.cs new file mode 100644 index 0000000..fdcda5c --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using AutoLotDAL.Models; +using AutoLotDAL.Repos; + +namespace SinglePageModel +{ + public partial class Default : System.Web.UI.Page + { + protected void Page_Load(object sender, EventArgs e) + { + + } + + //public IEnumerable GetData() => new InventoryRepo().GetAll(); + } +} \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx.designer.cs b/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx.designer.cs new file mode 100644 index 0000000..3d0c0d8 --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/Default.aspx.designer.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace SinglePageModel { + + + public partial class Default { + + /// + /// form1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlForm form1; + + /// + /// carsGridView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.GridView carsGridView; + } +} diff --git a/Appendix_C/SinglePageModel/SinglePageModel/Properties/AssemblyInfo.cs b/Appendix_C/SinglePageModel/SinglePageModel/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1f88827 --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SinglePageModel")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SinglePageModel")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("419ce338-c91b-402b-8fe3-65838eb4eeac")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Appendix_C/SinglePageModel/SinglePageModel/SinglePageModel.csproj b/Appendix_C/SinglePageModel/SinglePageModel/SinglePageModel.csproj new file mode 100644 index 0000000..ba1f1c3 --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/SinglePageModel.csproj @@ -0,0 +1,131 @@ + + + + + Debug + AnyCPU + + + 2.0 + {419CE338-C91B-402B-8FE3-65838EB4EEAC} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + SinglePageModel + SinglePageModel + v4.6 + true + + + + + + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + True + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + True + + + + + + + + + + + + + + + + + + + + + + + + Web.config + + + Web.config + + + + + + + + Default.aspx + ASPXCodeBehind + + + Default.aspx + + + + + + {29c6f0f4-94e3-4c30-9db9-02d340ace46a} + AutoLotDAL + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + True + True + 22542 + / + http://localhost:22542/ + False + False + + + False + + + + + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/SinglePageModel/Web.Debug.config b/Appendix_C/SinglePageModel/SinglePageModel/Web.Debug.config new file mode 100644 index 0000000..2e302f9 --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/Web.Debug.config @@ -0,0 +1,30 @@ + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/SinglePageModel/Web.Release.config b/Appendix_C/SinglePageModel/SinglePageModel/Web.Release.config new file mode 100644 index 0000000..c358444 --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/Web.Release.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/SinglePageModel/Web.config b/Appendix_C/SinglePageModel/SinglePageModel/Web.config new file mode 100644 index 0000000..5128cfd --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/Web.config @@ -0,0 +1,33 @@ + + + + + +
    + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/SinglePageModel/packages.config b/Appendix_C/SinglePageModel/SinglePageModel/packages.config new file mode 100644 index 0000000..c089e85 --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Appendix_C/SinglePageModel/SinglePageModel/sqllog.txt b/Appendix_C/SinglePageModel/SinglePageModel/sqllog.txt new file mode 100644 index 0000000..9f7204c --- /dev/null +++ b/Appendix_C/SinglePageModel/SinglePageModel/sqllog.txt @@ -0,0 +1,67 @@ +Opened connection at 10/15/2015 10:43:16 PM -04:00 +select cast(serverproperty('EngineEdition') as int) +-- Executing at 10/15/2015 10:43:16 PM -04:00 +-- Completed in 74 ms with result: SqlDataReader + +Closed connection at 10/15/2015 10:43:16 PM -04:00 +Opened connection at 10/15/2015 10:43:16 PM -04:00 +IF db_id(N'AutoLot') IS NOT NULL SELECT 1 ELSE SELECT Count(*) FROM sys.databases WHERE [name]=N'AutoLot' +-- Executing at 10/15/2015 10:43:16 PM -04:00 +-- Completed in 122 ms with result: 1 + +Closed connection at 10/15/2015 10:43:16 PM -04:00 +Opened connection at 10/15/2015 10:43:16 PM -04:00 + +SELECT Count(*) +FROM INFORMATION_SCHEMA.TABLES AS t +WHERE t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN ('dbo.CreditRisks','dbo.Customers','dbo.Orders','dbo.Inventory') + OR t.TABLE_NAME = 'EdmMetadata' +-- Executing at 10/15/2015 10:43:16 PM -04:00 +-- Completed in 66 ms with result: 4 + +Closed connection at 10/15/2015 10:43:16 PM -04:00 +Opened connection at 10/15/2015 10:43:16 PM -04:00 +SELECT + [GroupBy1].[A1] AS [C1] + FROM ( SELECT + COUNT(1) AS [A1] + FROM [dbo].[__MigrationHistory] AS [Extent1] + WHERE [Extent1].[ContextKey] = @p__linq__0 + ) AS [GroupBy1] +-- p__linq__0: 'AutoLotDAL.Migrations.Configuration' (Type = String, Size = 4000) +-- Executing at 10/15/2015 10:43:16 PM -04:00 +-- Completed in 92 ms with result: SqlDataReader + +Closed connection at 10/15/2015 10:43:16 PM -04:00 +Opened connection at 10/15/2015 10:43:16 PM -04:00 +SELECT TOP (1) + [Project1].[C1] AS [C1], + [Project1].[MigrationId] AS [MigrationId], + [Project1].[Model] AS [Model], + [Project1].[ProductVersion] AS [ProductVersion] + FROM ( SELECT + [Extent1].[MigrationId] AS [MigrationId], + [Extent1].[Model] AS [Model], + [Extent1].[ProductVersion] AS [ProductVersion], + 1 AS [C1] + FROM [dbo].[__MigrationHistory] AS [Extent1] + WHERE [Extent1].[ContextKey] = @p__linq__0 + ) AS [Project1] + ORDER BY [Project1].[MigrationId] DESC +-- p__linq__0: 'AutoLotDAL.Migrations.Configuration' (Type = String, Size = 4000) +-- Executing at 10/15/2015 10:43:16 PM -04:00 +-- Completed in 21 ms with result: SqlDataReader + +Closed connection at 10/15/2015 10:43:16 PM -04:00 +Opened connection at 10/15/2015 10:43:16 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 10/15/2015 10:43:16 PM -04:00 +-- Completed in 15 ms with result: SqlDataReader + +Closed connection at 10/15/2015 10:43:16 PM -04:00 diff --git a/Appendix_D/AspNetCarsSite/Ads.xml b/Appendix_D/AspNetCarsSite/Ads.xml new file mode 100644 index 0000000..2ef6afa --- /dev/null +++ b/Appendix_D/AspNetCarsSite/Ads.xml @@ -0,0 +1,15 @@ + + + + SlugBug.jpg + http://www.Cars.com + Your new Car? + 80 + + + car.gif + http://www.CarSuperSite.com + Like this Car? + 80 + + diff --git a/Appendix_D/AspNetCarsSite/AspNetCarsSite.sln b/Appendix_D/AspNetCarsSite/AspNetCarsSite.sln new file mode 100644 index 0000000..0c2c3fd --- /dev/null +++ b/Appendix_D/AspNetCarsSite/AspNetCarsSite.sln @@ -0,0 +1,39 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "AspNetCarsSite", ".", "{7E4991BE-20E6-4122-BF32-63C4C15496A3}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.6" + Debug.AspNetCompiler.VirtualPath = "/localhost_37076" + Debug.AspNetCompiler.PhysicalPath = "..\AspNetCarsSite\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_37076\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_37076" + Release.AspNetCompiler.PhysicalPath = "..\AspNetCarsSite\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_37076\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "37076" + SlnRelativePath = "..\AspNetCarsSite\" + DefaultWebSiteLanguage = "Visual C#" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7E4991BE-20E6-4122-BF32-63C4C15496A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7E4991BE-20E6-4122-BF32-63C4C15496A3}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_D/AspNetCarsSite/BuildCar.aspx b/Appendix_D/AspNetCarsSite/BuildCar.aspx new file mode 100644 index 0000000..ed2b4bd --- /dev/null +++ b/Appendix_D/AspNetCarsSite/BuildCar.aspx @@ -0,0 +1,69 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="BuildCar.aspx.cs" Inherits="Default2" %> + + + + + +
    +
    + + + + + + + + + + + + + Purple + Green + Red + Yellow + Pea Soup Green + Black + Lime Green + + + + + + + + + + + + + + + + + + + + + + +
    + +
    +
    + diff --git a/Appendix_D/AspNetCarsSite/BuildCar.aspx.cs b/Appendix_D/AspNetCarsSite/BuildCar.aspx.cs new file mode 100644 index 0000000..79fa744 --- /dev/null +++ b/Appendix_D/AspNetCarsSite/BuildCar.aspx.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class Default2 : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + } + + protected void carWizard_FinishButtonClick(object sender, + WizardNavigationEventArgs e) + { + // Get each value. + string order = + $"{txtCarPetName.Text}, your {ListBoxColors.SelectedValue} {txtCarModel.Text} will arrive on {carCalendar.SelectedDate.ToShortDateString()}."; + + // Assign to label + lblOrder.Text = order; + } +} diff --git a/Appendix_D/AspNetCarsSite/CAR.GIF b/Appendix_D/AspNetCarsSite/CAR.GIF new file mode 100644 index 0000000..b973fdd Binary files /dev/null and b/Appendix_D/AspNetCarsSite/CAR.GIF differ diff --git a/Appendix_D/AspNetCarsSite/Default.aspx b/Appendix_D/AspNetCarsSite/Default.aspx new file mode 100644 index 0000000..67d5ee8 --- /dev/null +++ b/Appendix_D/AspNetCarsSite/Default.aspx @@ -0,0 +1,11 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + +

    + Welcome to our site.  Here you can purchase a new car or build your dream + car. +

    +
    + diff --git a/Appendix_D/AspNetCarsSite/Default.aspx.cs b/Appendix_D/AspNetCarsSite/Default.aspx.cs new file mode 100644 index 0000000..c6c0ae5 --- /dev/null +++ b/Appendix_D/AspNetCarsSite/Default.aspx.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class _Default : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } +} \ No newline at end of file diff --git a/Appendix_D/AspNetCarsSite/Inventory.aspx b/Appendix_D/AspNetCarsSite/Inventory.aspx new file mode 100644 index 0000000..b60187e --- /dev/null +++ b/Appendix_D/AspNetCarsSite/Inventory.aspx @@ -0,0 +1,51 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" + AutoEventWireup="true" CodeFile="Inventory.aspx.cs" Inherits="InventoryPage" + Async="true" %> + + + + +

    + Here is our current Inventory! +

    +

    + Filter Model Type: + + + + +

    +

    + + + + + + + + + + + + + + + + + + + + + + diff --git a/Appendix_D/AspNetCarsSite/Inventory.aspx.cs b/Appendix_D/AspNetCarsSite/Inventory.aspx.cs new file mode 100644 index 0000000..5195371 --- /dev/null +++ b/Appendix_D/AspNetCarsSite/Inventory.aspx.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Web.ModelBinding; +using System.Web.UI; +using AutoLotDAL.Models; +using AutoLotDAL.Repos; + +public partial class InventoryPage : Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } + + public IQueryable GetData2([Control("cboMake")]string make) + { + var inventoryRepo = new InventoryRepo(); + return string.IsNullOrEmpty(make) ? + inventoryRepo.GetAll().AsQueryable() : + inventoryRepo.GetAll().Where(x => x.Make == make).AsQueryable(); + } + + public void Delete(int carId, byte[] timeStamp) + { + new InventoryRepo().Delete(carId, timeStamp); + } + + public async void Update(Inventory inventory) + { + if (ModelState.IsValid) + { + await new InventoryRepo().SaveAsync(inventory); + } + } + public IQueryable GetData([Control("cboMake")]string make="") => + string.IsNullOrEmpty(make) ? + new InventoryRepo().GetAll().AsQueryable() : + new InventoryRepo().GetAll().Where(x => x.Make == make).AsQueryable(); + + public IEnumerable GetMakes() => + new InventoryRepo().GetAll().Select(x => new {x.Make}).Distinct(); +} \ No newline at end of file diff --git a/Appendix_D/AspNetCarsSite/MasterPage.master b/Appendix_D/AspNetCarsSite/MasterPage.master new file mode 100644 index 0000000..0a8a62a --- /dev/null +++ b/Appendix_D/AspNetCarsSite/MasterPage.master @@ -0,0 +1,49 @@ +<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" + Inherits="MasterPage" %> + + + + + + Untitled Page + + + + +

    +
    +
    + +
    + +  
    +
    + + + + + + + +
    + + + + + + +
    +
    + + +
    +
    + + + diff --git a/Appendix_D/AspNetCarsSite/MasterPage.master.cs b/Appendix_D/AspNetCarsSite/MasterPage.master.cs new file mode 100644 index 0000000..2367f2c --- /dev/null +++ b/Appendix_D/AspNetCarsSite/MasterPage.master.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class MasterPage : System.Web.UI.MasterPage +{ + protected void Page_Load(object sender, EventArgs e) + { + + } +} diff --git a/Appendix_D/AspNetCarsSite/SlugBug.jpg b/Appendix_D/AspNetCarsSite/SlugBug.jpg new file mode 100644 index 0000000..c2cccc7 Binary files /dev/null and b/Appendix_D/AspNetCarsSite/SlugBug.jpg differ diff --git a/Appendix_D/AspNetCarsSite/Web.Debug.config b/Appendix_D/AspNetCarsSite/Web.Debug.config new file mode 100644 index 0000000..c358444 --- /dev/null +++ b/Appendix_D/AspNetCarsSite/Web.Debug.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_D/AspNetCarsSite/Web.config b/Appendix_D/AspNetCarsSite/Web.config new file mode 100644 index 0000000..ed16dba --- /dev/null +++ b/Appendix_D/AspNetCarsSite/Web.config @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Appendix_D/AspNetCarsSite/Web.sitemap b/Appendix_D/AspNetCarsSite/Web.sitemap new file mode 100644 index 0000000..a66d05b --- /dev/null +++ b/Appendix_D/AspNetCarsSite/Web.sitemap @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/Appendix_D/AspNetCarsSite/packages.config b/Appendix_D/AspNetCarsSite/packages.config new file mode 100644 index 0000000..3be3d2b --- /dev/null +++ b/Appendix_D/AspNetCarsSite/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_D/AspNetCarsSite/sqllog.txt b/Appendix_D/AspNetCarsSite/sqllog.txt new file mode 100644 index 0000000..5050e5b --- /dev/null +++ b/Appendix_D/AspNetCarsSite/sqllog.txt @@ -0,0 +1,247 @@ +Opened connection at 9/12/2015 4:42:22 PM -04:00 +select cast(serverproperty('EngineEdition') as int) +-- Executing at 9/12/2015 4:42:22 PM -04:00 +-- Completed in 35 ms with result: SqlDataReader + +Closed connection at 9/12/2015 4:42:23 PM -04:00 +Opened connection at 9/12/2015 4:42:23 PM -04:00 +IF db_id(N'AutoLot') IS NOT NULL SELECT 1 ELSE SELECT Count(*) FROM sys.databases WHERE [name]=N'AutoLot' +-- Executing at 9/12/2015 4:42:23 PM -04:00 +-- Completed in 19 ms with result: 1 + +Closed connection at 9/12/2015 4:42:23 PM -04:00 +Opened connection at 9/12/2015 4:42:23 PM -04:00 + +SELECT Count(*) +FROM INFORMATION_SCHEMA.TABLES AS t +WHERE t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN ('dbo.CreditRisks','dbo.Customers','dbo.Orders','dbo.Inventory') + OR t.TABLE_NAME = 'EdmMetadata' +-- Executing at 9/12/2015 4:42:23 PM -04:00 +-- Completed in 24 ms with result: 4 + +Closed connection at 9/12/2015 4:42:23 PM -04:00 +Opened connection at 9/12/2015 4:42:23 PM -04:00 +SELECT + [GroupBy1].[A1] AS [C1] + FROM ( SELECT + COUNT(1) AS [A1] + FROM [dbo].[__MigrationHistory] AS [Extent1] + WHERE [Extent1].[ContextKey] = @p__linq__0 + ) AS [GroupBy1] +-- p__linq__0: 'AutoLotDAL.Migrations.Configuration' (Type = String, Size = 4000) +-- Executing at 9/12/2015 4:42:23 PM -04:00 +-- Completed in 66 ms with result: SqlDataReader + +Closed connection at 9/12/2015 4:42:23 PM -04:00 +Opened connection at 9/12/2015 4:42:23 PM -04:00 +SELECT TOP (1) + [Project1].[C1] AS [C1], + [Project1].[MigrationId] AS [MigrationId], + [Project1].[Model] AS [Model], + [Project1].[ProductVersion] AS [ProductVersion] + FROM ( SELECT + [Extent1].[MigrationId] AS [MigrationId], + [Extent1].[Model] AS [Model], + [Extent1].[ProductVersion] AS [ProductVersion], + 1 AS [C1] + FROM [dbo].[__MigrationHistory] AS [Extent1] + WHERE [Extent1].[ContextKey] = @p__linq__0 + ) AS [Project1] + ORDER BY [Project1].[MigrationId] DESC +-- p__linq__0: 'AutoLotDAL.Migrations.Configuration' (Type = String, Size = 4000) +-- Executing at 9/12/2015 4:42:23 PM -04:00 +-- Completed in 18 ms with result: SqlDataReader + +Closed connection at 9/12/2015 4:42:23 PM -04:00 +Opened connection at 9/12/2015 4:42:23 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 4:42:23 PM -04:00 +-- Completed in 14 ms with result: SqlDataReader + +Closed connection at 9/12/2015 4:42:23 PM -04:00 +Opened connection at 9/12/2015 4:42:23 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 4:42:23 PM -04:00 +-- Completed in 15 ms with result: SqlDataReader + +Closed connection at 9/12/2015 4:42:23 PM -04:00 +Opened connection at 9/12/2015 4:42:27 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 4:42:27 PM -04:00 +-- Completed in 11 ms with result: SqlDataReader + +Closed connection at 9/12/2015 4:42:27 PM -04:00 +Opened connection at 9/12/2015 4:51:53 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 4:51:53 PM -04:00 +-- Completed in 34 ms with result: SqlDataReader + +Closed connection at 9/12/2015 4:51:53 PM -04:00 +Opened connection at 9/12/2015 4:55:57 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 4:55:57 PM -04:00 +-- Completed in 60 ms with result: SqlDataReader + +Closed connection at 9/12/2015 4:55:57 PM -04:00 +Opened connection at 9/12/2015 5:00:53 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 5:00:53 PM -04:00 +-- Completed in 27 ms with result: SqlDataReader + +Closed connection at 9/12/2015 5:00:53 PM -04:00 +Opened connection at 9/12/2015 5:01:38 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 5:01:38 PM -04:00 +-- Completed in 46 ms with result: SqlDataReader + +Closed connection at 9/12/2015 5:01:38 PM -04:00 +Opened connection at 9/12/2015 5:01:38 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 5:01:38 PM -04:00 +-- Completed in 12 ms with result: SqlDataReader + +Closed connection at 9/12/2015 5:01:38 PM -04:00 +Opened connection at 9/12/2015 5:01:44 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 5:01:44 PM -04:00 +-- Completed in 12 ms with result: SqlDataReader + +Closed connection at 9/12/2015 5:01:44 PM -04:00 +Opened connection at 9/12/2015 5:01:45 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 5:01:45 PM -04:00 +-- Completed in 17 ms with result: SqlDataReader + +Closed connection at 9/12/2015 5:01:45 PM -04:00 +Opened connection at 9/12/2015 5:09:21 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 5:09:21 PM -04:00 +-- Completed in 11 ms with result: SqlDataReader + +Closed connection at 9/12/2015 5:09:21 PM -04:00 +Opened connection at 9/12/2015 6:07:24 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 6:07:24 PM -04:00 +-- Completed in 27 ms with result: SqlDataReader + +Closed connection at 9/12/2015 6:07:24 PM -04:00 +Opened connection at 9/12/2015 6:07:24 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 6:07:24 PM -04:00 +-- Completed in 13 ms with result: SqlDataReader + +Closed connection at 9/12/2015 6:07:24 PM -04:00 +Opened connection at 9/12/2015 6:15:41 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 6:15:41 PM -04:00 +-- Completed in 57 ms with result: SqlDataReader + +Closed connection at 9/12/2015 6:15:41 PM -04:00 +Opened connection at 9/12/2015 6:15:41 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 6:15:41 PM -04:00 +-- Completed in 59 ms with result: SqlDataReader + +Closed connection at 9/12/2015 6:15:41 PM -04:00 +Opened connection at 9/12/2015 6:15:48 PM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 9/12/2015 6:15:48 PM -04:00 +-- Completed in 13 ms with result: SqlDataReader + +Closed connection at 9/12/2015 6:15:48 PM -04:00 diff --git a/Appendix_D/DynamicCtrls/Default.aspx b/Appendix_D/DynamicCtrls/Default.aspx new file mode 100644 index 0000000..ce64b5d --- /dev/null +++ b/Appendix_D/DynamicCtrls/Default.aspx @@ -0,0 +1,44 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Dynamic Control Test + + +
    +
    +
    +

    Dynamic Controls

    +

    + + +

    +

    + +

    +

    + +

    + +
    +
    + + + +
    +
    + HyperLink + +
    +
    +
    + +
    + + diff --git a/Appendix_D/DynamicCtrls/Default.aspx.cs b/Appendix_D/DynamicCtrls/Default.aspx.cs new file mode 100644 index 0000000..315099e --- /dev/null +++ b/Appendix_D/DynamicCtrls/Default.aspx.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class _Default : System.Web.UI.Page +{ + protected void Page_Load(object sender, System.EventArgs e) + { + ListControlsInPanel(); + } + private void ListControlsInPanel() + { + var theInfo = ""; + theInfo = $"Does the panel have controls? {myPanel.HasControls()}
    "; + + // Get all controls in the panel. + foreach (Control c in myPanel.Controls) + { + if (!object.ReferenceEquals(c.GetType(), + typeof(System.Web.UI.LiteralControl))) + { + theInfo += "***************************
    "; + theInfo += $"Control Name? {c}
    "; + theInfo += $"ID? {c.ID}
    "; + theInfo += $"Control Visible? {c.Visible}
    "; + theInfo += $"ViewState? {c.EnableViewState}
    "; + } + } + lblControlInfo.Text = theInfo; + } + + protected void btnAddWidgets_Click(object sender, EventArgs e) + { + for (int i = 0; i < 3; i++) + { + // Assign an ID so we can get + // the text value out later + // using the incoming form data. + TextBox t = new TextBox {ID = $"newTextBox{i}"}; + myPanel.Controls.Add(t); + ListControlsInPanel(); + } + } + + protected void btnClearPanel_Click(object sender, EventArgs e) + { + // Clear all content from the panel, then re-list items. + myPanel.Controls.Clear(); + ListControlsInPanel(); + } + + protected void btnGetTextData_Click(object sender, EventArgs e) + { + // Get teach text box by name. + string lableData = $"
  • {Request.Form.Get("newTextBox0")}

  • "; + lableData += $"
  • {Request.Form.Get("newTextBox1")}

  • "; + lableData += $"
  • {Request.Form.Get("newTextBox2")}

  • "; + lblTextBoxData.Text = lableData; + } +} \ No newline at end of file diff --git a/Appendix_D/DynamicCtrls/DynamicCtrls.sln b/Appendix_D/DynamicCtrls/DynamicCtrls.sln new file mode 100644 index 0000000..752b857 --- /dev/null +++ b/Appendix_D/DynamicCtrls/DynamicCtrls.sln @@ -0,0 +1,39 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "DynamicCtrls", ".", "{0193183A-DB1C-4E07-998A-25D54656B72B}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.6" + Debug.AspNetCompiler.VirtualPath = "/localhost_35873" + Debug.AspNetCompiler.PhysicalPath = "..\DynamicCtrls\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_35873\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_35873" + Release.AspNetCompiler.PhysicalPath = "..\DynamicCtrls\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_35873\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "35873" + SlnRelativePath = "..\DynamicCtrls\" + DefaultWebSiteLanguage = "Visual C#" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0193183A-DB1C-4E07-998A-25D54656B72B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0193183A-DB1C-4E07-998A-25D54656B72B}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_D/DynamicCtrls/Web.Debug.config b/Appendix_D/DynamicCtrls/Web.Debug.config new file mode 100644 index 0000000..c358444 --- /dev/null +++ b/Appendix_D/DynamicCtrls/Web.Debug.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_D/DynamicCtrls/Web.config b/Appendix_D/DynamicCtrls/Web.config new file mode 100644 index 0000000..1387ada --- /dev/null +++ b/Appendix_D/DynamicCtrls/Web.config @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + diff --git a/Appendix_D/DynamicCtrls/packages.config b/Appendix_D/DynamicCtrls/packages.config new file mode 100644 index 0000000..9e7e9fa --- /dev/null +++ b/Appendix_D/DynamicCtrls/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_D/FunWithThemes/App_Themes/BasicGreen/BasicGreen.skin b/Appendix_D/FunWithThemes/App_Themes/BasicGreen/BasicGreen.skin new file mode 100644 index 0000000..27cd646 --- /dev/null +++ b/Appendix_D/FunWithThemes/App_Themes/BasicGreen/BasicGreen.skin @@ -0,0 +1,19 @@ +<%-- +Default skin template. The following skins are provided as examples only. + +1. Named control skin. The SkinId should be uniquely defined because + duplicate SkinId's per control type are not allowed in the same theme. + + + + + +2. Default skin. The SkinId is not defined. Only one default + control skin per control type is allowed in the same theme. + + +--%> + + + + diff --git a/Appendix_D/FunWithThemes/App_Themes/CrazyOrange/CrazyOrange.skin b/Appendix_D/FunWithThemes/App_Themes/CrazyOrange/CrazyOrange.skin new file mode 100644 index 0000000..2e2b2c7 --- /dev/null +++ b/Appendix_D/FunWithThemes/App_Themes/CrazyOrange/CrazyOrange.skin @@ -0,0 +1,33 @@ +<%-- +Default skin template. The following skins are provided as examples only. + +1. Named control skin. The SkinId should be uniquely defined because + duplicate SkinId's per control type are not allowed in the same theme. + + + + + +2. Default skin. The SkinId is not defined. Only one default + control skin per control type is allowed in the same theme. + + +--%> + + + + + + + + + + + + diff --git a/Appendix_D/FunWithThemes/Default.aspx b/Appendix_D/FunWithThemes/Default.aspx new file mode 100644 index 0000000..88a072c --- /dev/null +++ b/Appendix_D/FunWithThemes/Default.aspx @@ -0,0 +1,43 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    + +

    + Fun with Themes

    +
    +
    + +
    +
    +
    + + Here are the controls which will be themed.
    +
    + +
    + +
    +
    + +
    +
    +
    + +
    +
    + + diff --git a/Appendix_D/FunWithThemes/Default.aspx.cs b/Appendix_D/FunWithThemes/Default.aspx.cs new file mode 100644 index 0000000..9d30abc --- /dev/null +++ b/Appendix_D/FunWithThemes/Default.aspx.cs @@ -0,0 +1,50 @@ +using System; +using System.Data; +using System.Configuration; +using System.Linq; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; +using System.Xml.Linq; + +partial class _Default : System.Web.UI.Page +{ + + protected void btnNoTheme_Click(object sender, System.EventArgs e) + { + // Empty strings result in no theme being applied. + Session["UserTheme"] = ""; + // Trigger the PreInit event again. + Server.Transfer(Request.FilePath); + } + + protected void btnGreenTheme_Click(object sender, System.EventArgs e) + { + Session["UserTheme"] = "BasicGreen"; + // Trigger the PreInit event again. + Server.Transfer(Request.FilePath); + } + + protected void btnOrangeTheme_Click(object sender, System.EventArgs e) + { + Session["UserTheme"] = "CrazyOrange"; + // Trigger the PreInit event again. + Server.Transfer(Request.FilePath); + } + + protected void Page_PreInit(object sender, System.EventArgs e) + { + try + { + Theme = Session["UserTheme"].ToString(); + } + catch + { + // Empty strings result in no theme being applied. + Theme = ""; + } + } +} diff --git a/Appendix_D/FunWithThemes/FunWithThemes.sln b/Appendix_D/FunWithThemes/FunWithThemes.sln new file mode 100644 index 0000000..a55be34 --- /dev/null +++ b/Appendix_D/FunWithThemes/FunWithThemes.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "FunWithThemes", ".", "{7A1DAD85-6905-4EA9-924D-8C013AAE0B3C}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" + Debug.AspNetCompiler.VirtualPath = "/localhost_54357" + Debug.AspNetCompiler.PhysicalPath = "..\FunWithThemes\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_54357\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_54357" + Release.AspNetCompiler.PhysicalPath = "..\FunWithThemes\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_54357\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "54357" + SlnRelativePath = "..\FunWithThemes\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7A1DAD85-6905-4EA9-924D-8C013AAE0B3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7A1DAD85-6905-4EA9-924D-8C013AAE0B3C}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_D/FunWithThemes/Web.config b/Appendix_D/FunWithThemes/Web.config new file mode 100644 index 0000000..f5a9260 --- /dev/null +++ b/Appendix_D/FunWithThemes/Web.config @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Appendix_D/FunWithThemes/packages.config b/Appendix_D/FunWithThemes/packages.config new file mode 100644 index 0000000..45401d0 --- /dev/null +++ b/Appendix_D/FunWithThemes/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_D/ValidatorCtrls/Annotations.aspx b/Appendix_D/ValidatorCtrls/Annotations.aspx new file mode 100644 index 0000000..4d48bca --- /dev/null +++ b/Appendix_D/ValidatorCtrls/Annotations.aspx @@ -0,0 +1,123 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Annotations.aspx.cs" Inherits="Annotations" %> + + + + + + + + +
    + + + + + + + + + + + + + + + + + + +
    + Make: + +
    + Color: +
    + Pet Name: +
    +   +
    +
    + + + + + + + + + + + + + + + + + + +
    + Make: + + + +
    + Color: + + + +
    + Pet Name: + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + +
    + Make: + + + +
    + Color: + + + +
    + Pet Name: + + + +
    + +
    +
    +
    + + + + diff --git a/Appendix_D/ValidatorCtrls/Annotations.aspx.cs b/Appendix_D/ValidatorCtrls/Annotations.aspx.cs new file mode 100644 index 0000000..40293d0 --- /dev/null +++ b/Appendix_D/ValidatorCtrls/Annotations.aspx.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class Annotations : System.Web.UI.Page +{ + private Inventory _model = null; + public void SaveCar(Inventory car) + { + if (ModelState.IsValid) + { + _model = car; + //Add new record here + } + } + + public void UpdateCar(int carID) + { + Inventory car = new Inventory(); + if (TryUpdateModel(car)) + { + _model = car; + //Update record here + } + } + + public Inventory GetCar() => _model; +} \ No newline at end of file diff --git a/Appendix_D/ValidatorCtrls/App_Code/Inventory.cs b/Appendix_D/ValidatorCtrls/App_Code/Inventory.cs new file mode 100644 index 0000000..0bad4a2 --- /dev/null +++ b/Appendix_D/ValidatorCtrls/App_Code/Inventory.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.ServiceModel.Channels; +using System.Web; + +/// +/// Summary description for Inventory +/// +public class Inventory +{ + [Key,Required] + public int CarID { get; set; } + + [Required(ErrorMessage="Make is required."),StringLength(30,ErrorMessage="Make can only be 30 charaters or less")] + public string Make { get; set; } + + [Required, StringLength(30)] + public string Color { get; set; } + + [StringLength(30, ErrorMessage = "Pet Name can only be 30 charaters or less")] + public string PetName { get; set; } +} \ No newline at end of file diff --git a/Appendix_D/ValidatorCtrls/Default.aspx b/Appendix_D/ValidatorCtrls/Default.aspx new file mode 100644 index 0000000..f34a7a0 --- /dev/null +++ b/Appendix_D/ValidatorCtrls/Default.aspx @@ -0,0 +1,64 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    + +
    +
    + Please enter your name +  
    +
    +
    +
    + +   +
    +
    +
    +
    + +   +
    +
    +
    +
    + +   +
    +
    +
    + +   + + +
    + + + + +
    +
    +
    +
    +
    +
    +
    + + diff --git a/Appendix_D/ValidatorCtrls/Default.aspx.cs b/Appendix_D/ValidatorCtrls/Default.aspx.cs new file mode 100644 index 0000000..d45fbb1 --- /dev/null +++ b/Appendix_D/ValidatorCtrls/Default.aspx.cs @@ -0,0 +1,23 @@ +using System; +using System.Data; +using System.Configuration; +using System.Linq; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; +using System.Xml.Linq; + +public partial class _Default : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } + protected void btnPostback_Click(object sender, EventArgs e) + { + lblValidationComplete.Text = "You passed validation!"; + } +} diff --git a/Appendix_D/ValidatorCtrls/ValidationGroups.aspx b/Appendix_D/ValidatorCtrls/ValidationGroups.aspx new file mode 100644 index 0000000..94c6936 --- /dev/null +++ b/Appendix_D/ValidatorCtrls/ValidationGroups.aspx @@ -0,0 +1,39 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidationGroups.aspx.cs" Inherits="ValidationGroups" %> + + + + + + Untitled Page + + +
    + + + + + + + + + + +   + + + +
    + + + diff --git a/Appendix_D/ValidatorCtrls/ValidationGroups.aspx.cs b/Appendix_D/ValidatorCtrls/ValidationGroups.aspx.cs new file mode 100644 index 0000000..2f8d1ef --- /dev/null +++ b/Appendix_D/ValidatorCtrls/ValidationGroups.aspx.cs @@ -0,0 +1,28 @@ +using System; +using System.Data; +using System.Configuration; +using System.Collections; +using System.Linq; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; +using System.Xml.Linq; + +public partial class ValidationGroups : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } + protected void bntValidateRequired_Click(object sender, EventArgs e) + { + + } + protected void btnValidateSSN_Click(object sender, EventArgs e) + { + + } +} diff --git a/Appendix_D/ValidatorCtrls/ValidatorCtrls.sln b/Appendix_D/ValidatorCtrls/ValidatorCtrls.sln new file mode 100644 index 0000000..79542c7 --- /dev/null +++ b/Appendix_D/ValidatorCtrls/ValidatorCtrls.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "ValidatorCtrls", ".", "{F897B501-A380-4F97-AC9E-757A80DCECE2}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" + Debug.AspNetCompiler.VirtualPath = "/localhost_15150" + Debug.AspNetCompiler.PhysicalPath = "..\ValidatorCtrls\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_15150\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_15150" + Release.AspNetCompiler.PhysicalPath = "..\ValidatorCtrls\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_15150\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "15150" + SlnRelativePath = "..\ValidatorCtrls\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F897B501-A380-4F97-AC9E-757A80DCECE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F897B501-A380-4F97-AC9E-757A80DCECE2}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_D/ValidatorCtrls/Web.config b/Appendix_D/ValidatorCtrls/Web.config new file mode 100644 index 0000000..dc747ba --- /dev/null +++ b/Appendix_D/ValidatorCtrls/Web.config @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_D/ValidatorCtrls/packages.config b/Appendix_D/ValidatorCtrls/packages.config new file mode 100644 index 0000000..45401d0 --- /dev/null +++ b/Appendix_D/ValidatorCtrls/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_E/AppState/AppState.sln b/Appendix_E/AppState/AppState.sln new file mode 100644 index 0000000..77f52ef --- /dev/null +++ b/Appendix_E/AppState/AppState.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "AppState", ".", "{79A9AD52-4040-4430-9E2A-FA0B03CB000C}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" + Debug.AspNetCompiler.VirtualPath = "/localhost_8900" + Debug.AspNetCompiler.PhysicalPath = "..\AppState\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_8900\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_8900" + Release.AspNetCompiler.PhysicalPath = "..\AppState\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_8900\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "8900" + SlnRelativePath = "..\AppState\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {79A9AD52-4040-4430-9E2A-FA0B03CB000C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {79A9AD52-4040-4430-9E2A-FA0B03CB000C}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_E/AppState/App_Code/CarLotInfo.cs b/Appendix_E/AppState/App_Code/CarLotInfo.cs new file mode 100644 index 0000000..6c6ca8e --- /dev/null +++ b/Appendix_E/AppState/App_Code/CarLotInfo.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; + +/// +/// Summary description for Class1 +/// +public class CarLotInfo +{ + public CarLotInfo(string salesPerson, string currentCar, string mostPopular) + { + SalesPersonOfTheMonth = salesPerson; + CurrentCarOnSale = currentCar; + MostPopularColorOnLot = mostPopular; + } + public string SalesPersonOfTheMonth { get; set; } + public string CurrentCarOnSale { get; set; } + public string MostPopularColorOnLot { get; set; } +} diff --git a/Appendix_E/AppState/Default.aspx b/Appendix_E/AppState/Default.aspx new file mode 100644 index 0000000..6987130 --- /dev/null +++ b/Appendix_E/AppState/Default.aspx @@ -0,0 +1,28 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +
    +
    + + diff --git a/Appendix_E/AppState/Default.aspx.cs b/Appendix_E/AppState/Default.aspx.cs new file mode 100644 index 0000000..4118abb --- /dev/null +++ b/Appendix_E/AppState/Default.aspx.cs @@ -0,0 +1,42 @@ +using System; +using System.Data; +using System.Configuration; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; + +public partial class _Default : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } + + private void CleanAppData() + { + // Remove a single item via string name. + Application.Remove("SomeItemIDontNeed"); + + // Destroy all application data! + Application.RemoveAll(); + } + + protected void btnShowAppVariables_Click(object sender, EventArgs e) + { + CarLotInfo appVars = ((CarLotInfo)Application["CarSiteInfo"]); + string appState = $"
  • Car on sale: {appVars.CurrentCarOnSale}
  • "; + appState += $"
  • Most popular color: {appVars.MostPopularColorOnLot}
  • "; + appState += $"
  • Big shot SalesPerson: {appVars.SalesPersonOfTheMonth}
  • "; + lblAppVariables.Text = appState; + } + + protected void btnSetNewSP_Click(object sender, EventArgs e) + { + // Set the new Salesperson. + ((CarLotInfo)Application["CarSiteInfo"]).SalesPersonOfTheMonth + = txtNewSP.Text; + } +} \ No newline at end of file diff --git a/Appendix_E/AppState/Global.asax b/Appendix_E/AppState/Global.asax new file mode 100644 index 0000000..a4974aa --- /dev/null +++ b/Appendix_E/AppState/Global.asax @@ -0,0 +1,34 @@ +<%@ Application Language="C#" %> + + diff --git a/Appendix_E/AppState/Web.config b/Appendix_E/AppState/Web.config new file mode 100644 index 0000000..93b683f --- /dev/null +++ b/Appendix_E/AppState/Web.config @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_E/AppState/packages.config b/Appendix_E/AppState/packages.config new file mode 100644 index 0000000..45401d0 --- /dev/null +++ b/Appendix_E/AppState/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_E/CacheState/CacheState.sln b/Appendix_E/CacheState/CacheState.sln new file mode 100644 index 0000000..4821bc6 --- /dev/null +++ b/Appendix_E/CacheState/CacheState.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "CacheState", ".", "{7E6195C0-DF3D-4E4B-BBCB-95C0DA289F73}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" + Debug.AspNetCompiler.VirtualPath = "/localhost_9457" + Debug.AspNetCompiler.PhysicalPath = "..\CacheState\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_9457\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_9457" + Release.AspNetCompiler.PhysicalPath = "..\CacheState\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_9457\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "9457" + SlnRelativePath = "..\CacheState\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7E6195C0-DF3D-4E4B-BBCB-95C0DA289F73}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7E6195C0-DF3D-4E4B-BBCB-95C0DA289F73}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_E/CacheState/Default.aspx b/Appendix_E/CacheState/Default.aspx new file mode 100644 index 0000000..bd86ae6 --- /dev/null +++ b/Appendix_E/CacheState/Default.aspx @@ -0,0 +1,41 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    +
    +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +  
    + + + + + + + +
    +
    + + diff --git a/Appendix_E/CacheState/Default.aspx.cs b/Appendix_E/CacheState/Default.aspx.cs new file mode 100644 index 0000000..d1dc3ad --- /dev/null +++ b/Appendix_E/CacheState/Default.aspx.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Web.UI; +using AutoLotDAL.Models; +using AutoLotDAL.Repos; + +public partial class _Default : Page +{ + protected void Page_Load(object sender, EventArgs e) + { + if (!IsPostBack) + { + carsGridView.DataSource = (IList)Cache["CarList"]; + carsGridView.DataBind(); + } + } + protected void btnAddCar_Click(object sender, EventArgs e) + { + // Update the Inventory table + // and call RefreshGrid(). + new InventoryRepo().Add(new Inventory() + { + Color = txtCarColor.Text, + Make = txtCarMake.Text, + PetName = txtCarPetName.Text + }); + RefreshGrid(); + + } + private void RefreshGrid() + { + carsGridView.DataSource = new InventoryRepo().GetAll(); + carsGridView.DataBind(); + } +} \ No newline at end of file diff --git a/Appendix_E/CacheState/Global.asax b/Appendix_E/CacheState/Global.asax new file mode 100644 index 0000000..20a1d59 --- /dev/null +++ b/Appendix_E/CacheState/Global.asax @@ -0,0 +1,64 @@ +<%@ Application Language="C#" %> +<%@ Import Namespace="AutoLotDAL.Repos" %> + + diff --git a/Appendix_E/CacheState/Web.config b/Appendix_E/CacheState/Web.config new file mode 100644 index 0000000..38cbaac --- /dev/null +++ b/Appendix_E/CacheState/Web.config @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_E/CacheState/packages.config b/Appendix_E/CacheState/packages.config new file mode 100644 index 0000000..bddc74a --- /dev/null +++ b/Appendix_E/CacheState/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Appendix_E/CacheState/sqllog.txt b/Appendix_E/CacheState/sqllog.txt new file mode 100644 index 0000000..60a0915 --- /dev/null +++ b/Appendix_E/CacheState/sqllog.txt @@ -0,0 +1,67 @@ +Opened connection at 10/17/2015 9:38:43 AM -04:00 +select cast(serverproperty('EngineEdition') as int) +-- Executing at 10/17/2015 9:38:43 AM -04:00 +-- Completed in 30 ms with result: SqlDataReader + +Closed connection at 10/17/2015 9:38:43 AM -04:00 +Opened connection at 10/17/2015 9:38:44 AM -04:00 +IF db_id(N'AutoLot') IS NOT NULL SELECT 1 ELSE SELECT Count(*) FROM sys.databases WHERE [name]=N'AutoLot' +-- Executing at 10/17/2015 9:38:44 AM -04:00 +-- Completed in 101 ms with result: 1 + +Closed connection at 10/17/2015 9:38:44 AM -04:00 +Opened connection at 10/17/2015 9:38:44 AM -04:00 + +SELECT Count(*) +FROM INFORMATION_SCHEMA.TABLES AS t +WHERE t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN ('dbo.CreditRisks','dbo.Customers','dbo.Orders','dbo.Inventory') + OR t.TABLE_NAME = 'EdmMetadata' +-- Executing at 10/17/2015 9:38:44 AM -04:00 +-- Completed in 56 ms with result: 4 + +Closed connection at 10/17/2015 9:38:44 AM -04:00 +Opened connection at 10/17/2015 9:38:45 AM -04:00 +SELECT + [GroupBy1].[A1] AS [C1] + FROM ( SELECT + COUNT(1) AS [A1] + FROM [dbo].[__MigrationHistory] AS [Extent1] + WHERE [Extent1].[ContextKey] = @p__linq__0 + ) AS [GroupBy1] +-- p__linq__0: 'AutoLotDAL.Migrations.Configuration' (Type = String, Size = 4000) +-- Executing at 10/17/2015 9:38:46 AM -04:00 +-- Completed in 32 ms with result: SqlDataReader + +Closed connection at 10/17/2015 9:38:46 AM -04:00 +Opened connection at 10/17/2015 9:38:46 AM -04:00 +SELECT TOP (1) + [Project1].[C1] AS [C1], + [Project1].[MigrationId] AS [MigrationId], + [Project1].[Model] AS [Model], + [Project1].[ProductVersion] AS [ProductVersion] + FROM ( SELECT + [Extent1].[MigrationId] AS [MigrationId], + [Extent1].[Model] AS [Model], + [Extent1].[ProductVersion] AS [ProductVersion], + 1 AS [C1] + FROM [dbo].[__MigrationHistory] AS [Extent1] + WHERE [Extent1].[ContextKey] = @p__linq__0 + ) AS [Project1] + ORDER BY [Project1].[MigrationId] DESC +-- p__linq__0: 'AutoLotDAL.Migrations.Configuration' (Type = String, Size = 4000) +-- Executing at 10/17/2015 9:38:46 AM -04:00 +-- Completed in 17 ms with result: SqlDataReader + +Closed connection at 10/17/2015 9:38:46 AM -04:00 +Opened connection at 10/17/2015 9:38:46 AM -04:00 +SELECT + [Extent1].[CarId] AS [CarId], + [Extent1].[Make] AS [Make], + [Extent1].[Color] AS [Color], + [Extent1].[PetName] AS [PetName], + [Extent1].[Timestamp] AS [Timestamp] + FROM [dbo].[Inventory] AS [Extent1] +-- Executing at 10/17/2015 9:38:46 AM -04:00 +-- Completed in 12 ms with result: SqlDataReader + +Closed connection at 10/17/2015 9:38:46 AM -04:00 diff --git a/Appendix_E/CookieStateApp/CookieStateApp.sln b/Appendix_E/CookieStateApp/CookieStateApp.sln new file mode 100644 index 0000000..41eeb8f --- /dev/null +++ b/Appendix_E/CookieStateApp/CookieStateApp.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "CookieStateApp", ".", "{306CB8AB-2F88-4D41-BF00-A968F8B11E7D}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" + Debug.AspNetCompiler.VirtualPath = "/localhost_15788" + Debug.AspNetCompiler.PhysicalPath = "..\CookieStateApp\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_15788\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_15788" + Release.AspNetCompiler.PhysicalPath = "..\CookieStateApp\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_15788\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "15788" + SlnRelativePath = "..\CookieStateApp\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {306CB8AB-2F88-4D41-BF00-A968F8B11E7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {306CB8AB-2F88-4D41-BF00-A968F8B11E7D}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_E/CookieStateApp/Default.aspx b/Appendix_E/CookieStateApp/Default.aspx new file mode 100644 index 0000000..fadb58a --- /dev/null +++ b/Appendix_E/CookieStateApp/Default.aspx @@ -0,0 +1,32 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +
    +
    + + diff --git a/Appendix_E/CookieStateApp/Default.aspx.cs b/Appendix_E/CookieStateApp/Default.aspx.cs new file mode 100644 index 0000000..26643c4 --- /dev/null +++ b/Appendix_E/CookieStateApp/Default.aspx.cs @@ -0,0 +1,28 @@ +using System; +using System.Web; +using System.Web.UI; + +public partial class _Default : Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } + protected void btnCookie_Click(object sender, EventArgs e) + { + // Make a new (temp) cookie. + HttpCookie theCookie = new HttpCookie(txtCookieName.Text,txtCookieValue.Text) + { Expires = DateTime.Parse("12/31/2015")}; + Response.Cookies.Add(theCookie); + } + + protected void btnShowCookie_Click(object sender, EventArgs e) + { + string cookieData = ""; + foreach (string s in Request.Cookies) + { + cookieData += $"
  • Name: {s}, Value: {Request.Cookies[s]?.Value}
  • "; + } + lblCookieData.Text = cookieData; + } +} \ No newline at end of file diff --git a/Appendix_E/CookieStateApp/Web.config b/Appendix_E/CookieStateApp/Web.config new file mode 100644 index 0000000..93b683f --- /dev/null +++ b/Appendix_E/CookieStateApp/Web.config @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_E/CookieStateApp/packages.config b/Appendix_E/CookieStateApp/packages.config new file mode 100644 index 0000000..45401d0 --- /dev/null +++ b/Appendix_E/CookieStateApp/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_E/FunWithProfiles/App_Code/UserAddress.cs b/Appendix_E/FunWithProfiles/App_Code/UserAddress.cs new file mode 100644 index 0000000..8a14569 --- /dev/null +++ b/Appendix_E/FunWithProfiles/App_Code/UserAddress.cs @@ -0,0 +1,22 @@ +using System; +using System.Data; +using System.Configuration; +using System.Linq; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; +using System.Xml.Linq; + +/// +/// Summary description for UserAddress +/// +[Serializable] +public class UserAddress +{ + public string Street = string.Empty; + public string City = string.Empty; + public string State = string.Empty; +} diff --git a/Appendix_E/FunWithProfiles/Default.aspx b/Appendix_E/FunWithProfiles/Default.aspx new file mode 100644 index 0000000..f0dc624 --- /dev/null +++ b/Appendix_E/FunWithProfiles/Default.aspx @@ -0,0 +1,35 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    +
    + +
    +
    +
    +
    + +
    +
    + +                 +
    +
    + +               +
    +
    +
    +
    + + + + diff --git a/Appendix_E/FunWithProfiles/Default.aspx.cs b/Appendix_E/FunWithProfiles/Default.aspx.cs new file mode 100644 index 0000000..67e75a7 --- /dev/null +++ b/Appendix_E/FunWithProfiles/Default.aspx.cs @@ -0,0 +1,37 @@ +using System; +using System.Data; +using System.Configuration; +using System.Linq; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; +using System.Xml.Linq; + +public partial class _Default : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + GetUserAddress(); + } + protected void btnSubmit_Click(object sender, EventArgs e) + { + // Database writes happening here! + Profile.AddressInfo.City = txtCity.Text; + Profile.AddressInfo.Street = txtStreetAddress.Text; + Profile.AddressInfo.State = txtState.Text; + + // Get settings from database. + GetUserAddress(); + } + + private void GetUserAddress() + { + // Database reads happening here! + lblUserData.Text = + $"You live here: {Profile.AddressInfo.Street}, {Profile.AddressInfo.City}, " + + $"{Profile.AddressInfo.State}"; + } +} diff --git a/Appendix_E/FunWithProfiles/FunWithProfiles.sln b/Appendix_E/FunWithProfiles/FunWithProfiles.sln new file mode 100644 index 0000000..016179b --- /dev/null +++ b/Appendix_E/FunWithProfiles/FunWithProfiles.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "FunWithProfiles", ".", "{33E521F3-E876-44A6-B7CE-CC31CA1BCADA}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.0" + Debug.AspNetCompiler.VirtualPath = "/localhost_16422" + Debug.AspNetCompiler.PhysicalPath = "..\FunWithProfiles\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_16422\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_16422" + Release.AspNetCompiler.PhysicalPath = "..\FunWithProfiles\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_16422\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "16422" + SlnRelativePath = "..\FunWithProfiles\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {33E521F3-E876-44A6-B7CE-CC31CA1BCADA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33E521F3-E876-44A6-B7CE-CC31CA1BCADA}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_E/FunWithProfiles/Web.config b/Appendix_E/FunWithProfiles/Web.config new file mode 100644 index 0000000..46107e5 --- /dev/null +++ b/Appendix_E/FunWithProfiles/Web.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + diff --git a/Appendix_E/FunWithProfiles/packages.config b/Appendix_E/FunWithProfiles/packages.config new file mode 100644 index 0000000..e5fae81 --- /dev/null +++ b/Appendix_E/FunWithProfiles/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_E/SessionState/App_Code/UserShoppingCart.cs b/Appendix_E/SessionState/App_Code/UserShoppingCart.cs new file mode 100644 index 0000000..73c29c6 --- /dev/null +++ b/Appendix_E/SessionState/App_Code/UserShoppingCart.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; + +/// +/// Summary description for UserShoppingCart +/// +public class UserShoppingCart +{ + public string DesiredCar { get; set; } + public string DesiredCarColor { get; set; } + public float DownPayment { get; set; } + public bool IsLeasing { get; set; } + public DateTime DateOfPickUp { get; set; } + + public override string ToString() => + $"Car: {DesiredCar}
    Color: {DesiredCarColor}
    $ Down: {DownPayment}" + + $"
    Lease: {IsLeasing}
    Pick-up Date: {DateOfPickUp.ToShortDateString()}"; +} diff --git a/Appendix_E/SessionState/Default.aspx b/Appendix_E/SessionState/Default.aspx new file mode 100644 index 0000000..9e9f45f --- /dev/null +++ b/Appendix_E/SessionState/Default.aspx @@ -0,0 +1,50 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + +
    +
    + + + + + + + + + + +
    +
    +
    +
    + + +
    +
    + + diff --git a/Appendix_E/SessionState/Default.aspx.cs b/Appendix_E/SessionState/Default.aspx.cs new file mode 100644 index 0000000..297fc13 --- /dev/null +++ b/Appendix_E/SessionState/Default.aspx.cs @@ -0,0 +1,29 @@ +using System; +using System.Data; +using System.Configuration; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; + +public partial class _Default : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } + protected void btnSubmit_Click(object sender, EventArgs e) + { + // Set current user prefs. + var cart = (UserShoppingCart)Session["UserShoppingCartInfo"]; + cart.DateOfPickUp = myCalendar.SelectedDate; + cart.DesiredCar = txtCarMake.Text; + cart.DesiredCarColor = txtCarColor.Text; + cart.DownPayment = float.Parse(txtDownPayment.Text); + cart.IsLeasing = chkIsLeasing.Checked; + lblUserInfo.Text = cart.ToString(); + Session["UserShoppingCartInfo"] = cart; + } +} \ No newline at end of file diff --git a/Appendix_E/SessionState/Global.asax b/Appendix_E/SessionState/Global.asax new file mode 100644 index 0000000..0f91fb3 --- /dev/null +++ b/Appendix_E/SessionState/Global.asax @@ -0,0 +1,38 @@ +<%@ Application Language="C#" %> + + diff --git a/Appendix_E/SessionState/SessionState.sln b/Appendix_E/SessionState/SessionState.sln new file mode 100644 index 0000000..2ed6ed6 --- /dev/null +++ b/Appendix_E/SessionState/SessionState.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "SessionState", ".", "{22DF6D18-C31A-4585-906C-B4253A73344E}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" + Debug.AspNetCompiler.VirtualPath = "/localhost_15216" + Debug.AspNetCompiler.PhysicalPath = "..\SessionState\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_15216\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_15216" + Release.AspNetCompiler.PhysicalPath = "..\SessionState\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_15216\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "15216" + SlnRelativePath = "..\SessionState\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {22DF6D18-C31A-4585-906C-B4253A73344E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {22DF6D18-C31A-4585-906C-B4253A73344E}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_E/SessionState/Web.config b/Appendix_E/SessionState/Web.config new file mode 100644 index 0000000..93b683f --- /dev/null +++ b/Appendix_E/SessionState/Web.config @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_E/SessionState/packages.config b/Appendix_E/SessionState/packages.config new file mode 100644 index 0000000..45401d0 --- /dev/null +++ b/Appendix_E/SessionState/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_E/SimpleStateExample/Default.aspx b/Appendix_E/SimpleStateExample/Default.aspx new file mode 100644 index 0000000..9de478c --- /dev/null +++ b/Appendix_E/SimpleStateExample/Default.aspx @@ -0,0 +1,23 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    + +
    + +
    + +
    +
    +   + + + + diff --git a/Appendix_E/SimpleStateExample/Default.aspx.cs b/Appendix_E/SimpleStateExample/Default.aspx.cs new file mode 100644 index 0000000..cbd09ed --- /dev/null +++ b/Appendix_E/SimpleStateExample/Default.aspx.cs @@ -0,0 +1,32 @@ +using System; +using System.Data; +using System.Configuration; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; + +public partial class _Default : System.Web.UI.Page +{ + // State data? + // private string userFavoriteCar; + + protected void Page_Load(object sender, EventArgs e) + { + + } + protected void btnSetCar_Click(object sender, EventArgs e) + { + // Store fav car in member variable. + // userFavoriteCar = txtFavCar.Text; + Session["UserFavCar"] = txtFavCar.Text; + } + protected void btnGetCar_Click(object sender, EventArgs e) + { + // Show value of member variable. + // lblFavCar.Text = userFavoriteCar; + lblFavCar.Text = (string)Session["UserFavCar"]; + } +} \ No newline at end of file diff --git a/Appendix_E/SimpleStateExample/SimpleStateExample.sln b/Appendix_E/SimpleStateExample/SimpleStateExample.sln new file mode 100644 index 0000000..11f9216 --- /dev/null +++ b/Appendix_E/SimpleStateExample/SimpleStateExample.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "SimpleStateExample", ".", "{107DEF2D-308D-40BD-A1A3-3E91BD8342A7}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" + Debug.AspNetCompiler.VirtualPath = "/localhost_8022" + Debug.AspNetCompiler.PhysicalPath = "..\SimpleStateExample\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_8022\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_8022" + Release.AspNetCompiler.PhysicalPath = "..\SimpleStateExample\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_8022\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "8022" + SlnRelativePath = "..\SimpleStateExample\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {107DEF2D-308D-40BD-A1A3-3E91BD8342A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {107DEF2D-308D-40BD-A1A3-3E91BD8342A7}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_E/SimpleStateExample/Web.config b/Appendix_E/SimpleStateExample/Web.config new file mode 100644 index 0000000..93b683f --- /dev/null +++ b/Appendix_E/SimpleStateExample/Web.config @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_E/SimpleStateExample/packages.config b/Appendix_E/SimpleStateExample/packages.config new file mode 100644 index 0000000..45401d0 --- /dev/null +++ b/Appendix_E/SimpleStateExample/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Appendix_E/ViewStateApp/Default.aspx b/Appendix_E/ViewStateApp/Default.aspx new file mode 100644 index 0000000..8a2861e --- /dev/null +++ b/Appendix_E/ViewStateApp/Default.aspx @@ -0,0 +1,25 @@ +<%@ Page EnableViewState ="false" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> + + + + + + Untitled Page + + +
    +
    +
    +
    +  
    + +
    +
    +  
    +
    +
    +
    + + + + diff --git a/Appendix_E/ViewStateApp/Default.aspx.cs b/Appendix_E/ViewStateApp/Default.aspx.cs new file mode 100644 index 0000000..4555a10 --- /dev/null +++ b/Appendix_E/ViewStateApp/Default.aspx.cs @@ -0,0 +1,26 @@ +using System; +using System.Web.UI; + +public partial class _Default : Page +{ + protected void Page_Load(object sender, EventArgs e) + { + if (!IsPostBack) + { + // Fill ListBox dynamically! + myListBox.Items.Add("Item One"); + myListBox.Items.Add("Item Two"); + myListBox.Items.Add("Item Three"); + myListBox.Items.Add("Item Four"); + } + } + protected void btnPostback_Click(object sender, EventArgs e) + { + // No-op. This is just here to allow a post back. + } + protected void btnAddToVS_Click(object sender, EventArgs e) + { + ViewState["CustomViewStateItem"] = "Some user data"; + lblVSValue.Text = (string)ViewState["CustomViewStateItem"]; + } +} \ No newline at end of file diff --git a/Appendix_E/ViewStateApp/ViewStateApp.sln b/Appendix_E/ViewStateApp/ViewStateApp.sln new file mode 100644 index 0000000..b87389a --- /dev/null +++ b/Appendix_E/ViewStateApp/ViewStateApp.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "ViewStateApp", ".", "{C35D97AE-09C3-4579-9762-8E5F37F7C5BB}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" + Debug.AspNetCompiler.VirtualPath = "/localhost_8388" + Debug.AspNetCompiler.PhysicalPath = "..\ViewStateApp\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_8388\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_8388" + Release.AspNetCompiler.PhysicalPath = "..\ViewStateApp\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_8388\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "8388" + SlnRelativePath = "..\ViewStateApp\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C35D97AE-09C3-4579-9762-8E5F37F7C5BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C35D97AE-09C3-4579-9762-8E5F37F7C5BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Appendix_E/ViewStateApp/Web.config b/Appendix_E/ViewStateApp/Web.config new file mode 100644 index 0000000..93b683f --- /dev/null +++ b/Appendix_E/ViewStateApp/Web.config @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Appendix_E/ViewStateApp/packages.config b/Appendix_E/ViewStateApp/packages.config new file mode 100644 index 0000000..45401d0 --- /dev/null +++ b/Appendix_E/ViewStateApp/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Chapter_1/Calc.cs b/Chapter_1/Calc.cs new file mode 100644 index 0000000..7800211 --- /dev/null +++ b/Chapter_1/Calc.cs @@ -0,0 +1,24 @@ +// Calc.cs +using System; +namespace CalculatorExample +{ + // This class contains the app's entry point. + class Program + { + static void Main() + { + Calc c = new Calc(); + int ans = c.Add(10, 84); + Console.WriteLine("10 + 84 is {0}.", ans); + // Wait for user to press the Enter key before shutting down. + Console.ReadLine(); + } + } + + // The C# calculator. + class Calc + { + public int Add(int x, int y) + { return x + y; } + } +} diff --git a/Chapter_1/Calc.vb b/Chapter_1/Calc.vb new file mode 100644 index 0000000..508ed63 --- /dev/null +++ b/Chapter_1/Calc.vb @@ -0,0 +1,21 @@ +' Calc.vb +Imports System + +Namespace CalculatorExample + ' A VB "Module" is a class that contains only + ' static members. + Module Program + Sub Main() + Dim c As New Calc + Dim ans As Integer = c.Add(10, 84) + Console.WriteLine("10 + 84 is {0}.", ans) + Console.ReadLine() + End Sub + End Module + + Class Calc + Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer + Return x + y + End Function + End Class +End Namespace diff --git a/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates.sln b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates.sln new file mode 100644 index 0000000..b99a557 --- /dev/null +++ b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ActionAndFuncDelegates", "ActionAndFuncDelegates\ActionAndFuncDelegates.csproj", "{6B2E5ED7-287A-4626-8C74-1E1E9FA11B80}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6B2E5ED7-287A-4626-8C74-1E1E9FA11B80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6B2E5ED7-287A-4626-8C74-1E1E9FA11B80}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6B2E5ED7-287A-4626-8C74-1E1E9FA11B80}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6B2E5ED7-287A-4626-8C74-1E1E9FA11B80}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/ActionAndFuncDelegates.csproj b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/ActionAndFuncDelegates.csproj new file mode 100644 index 0000000..b4be6bf --- /dev/null +++ b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/ActionAndFuncDelegates.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {6B2E5ED7-287A-4626-8C74-1E1E9FA11B80} + Exe + ActionAndFuncDelegates + ActionAndFuncDelegates + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/App.config b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/Program.cs b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/Program.cs new file mode 100644 index 0000000..95ae41a --- /dev/null +++ b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/Program.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ActionAndFuncDelegates +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Action and Func *****\n"); + + // Use the Action<> delegate to point to DisplayMessage. + Action actionTarget = new Action(DisplayMessage); + actionTarget("Action Message!", ConsoleColor.Yellow, 5); + + /* + Func funcTarget = new Func(Add); + int result = funcTarget.Invoke(40, 40); + Console.WriteLine("40 + 40 = {0}", result); + + Func funcTarget2 = new Func(SumToString); + string sum = funcTarget2(90, 300); + Console.WriteLine(sum); + */ + + Func funcTarget = Add; + int result = funcTarget.Invoke(40, 40); + Console.WriteLine("40 + 40 = {0}", result); + + Func funcTarget2 = SumToString; + string sum = funcTarget2(90, 300); + Console.WriteLine(sum); + + Console.ReadLine(); + } + + // This is a target for the Action<> delegate. + static void DisplayMessage(string msg, ConsoleColor txtColor, int printCount) + { + // Set color of console text. + ConsoleColor previous = Console.ForegroundColor; + Console.ForegroundColor = txtColor; + + for (int i = 0; i < printCount; i++) + { + Console.WriteLine(msg); + } + + // Restore color. + Console.ForegroundColor = previous; + } + + // Targets for the Func<> delegate. + static int Add(int x, int y) + { + return x + y; + } + + static string SumToString(int x, int y) + { + return (x + y).ToString(); + } + } +} diff --git a/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/Properties/AssemblyInfo.cs b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6128918 --- /dev/null +++ b/Chapter_10/ActionAndFuncDelegates/ActionAndFuncDelegates/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ActionAndFuncDelegates")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ActionAndFuncDelegates")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6b2e5ed7-287a-4626-8c74-1e1e9fa11b80")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/AnonymousMethods/AnonymousMethods.sln b/Chapter_10/AnonymousMethods/AnonymousMethods.sln new file mode 100644 index 0000000..42aed9f --- /dev/null +++ b/Chapter_10/AnonymousMethods/AnonymousMethods.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnonymousMethods", "AnonymousMethods\AnonymousMethods.csproj", "{61F4890A-6914-4924-949E-35A2BF4B36A0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {61F4890A-6914-4924-949E-35A2BF4B36A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {61F4890A-6914-4924-949E-35A2BF4B36A0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {61F4890A-6914-4924-949E-35A2BF4B36A0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {61F4890A-6914-4924-949E-35A2BF4B36A0}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/AnonymousMethods/AnonymousMethods/AnonymousMethods.csproj b/Chapter_10/AnonymousMethods/AnonymousMethods/AnonymousMethods.csproj new file mode 100644 index 0000000..c70cce5 --- /dev/null +++ b/Chapter_10/AnonymousMethods/AnonymousMethods/AnonymousMethods.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {61F4890A-6914-4924-949E-35A2BF4B36A0} + Exe + AnonymousMethods + AnonymousMethods + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/AnonymousMethods/AnonymousMethods/App.config b/Chapter_10/AnonymousMethods/AnonymousMethods/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/AnonymousMethods/AnonymousMethods/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/AnonymousMethods/AnonymousMethods/Car.cs b/Chapter_10/AnonymousMethods/AnonymousMethods/Car.cs new file mode 100644 index 0000000..4caa605 --- /dev/null +++ b/Chapter_10/AnonymousMethods/AnonymousMethods/Car.cs @@ -0,0 +1,63 @@ +#region Using directives + +using System; +using System.Collections.Generic; +using System.Text; + +#endregion + +namespace AnonymousMethods +{ + public class Car + { + #region Basic Car state data / constructors + // Internal state data. + public int CurrentSpeed { get; set; } + public int MaxSpeed { get; set; } + public string PetName { get; set; } + + // Is the car alive or dead? + private bool carIsDead; + + public Car() + { + MaxSpeed = 100; + } + + public Car(string name, int maxSp, int currSp) + { + CurrentSpeed = currSp; + MaxSpeed = maxSp; + PetName = name; + } + #endregion + + public event EventHandler Exploded; + public event EventHandler AboutToBlow; + + public void Accelerate(int delta) + { + // If the car is dead, fire Exploded event. + if (carIsDead) + { + Exploded?.Invoke(this, new CarEventArgs("Sorry, this car is dead...")); + } + else + { + CurrentSpeed += delta; + + // Almost dead? + if (10 == MaxSpeed - CurrentSpeed) + { + AboutToBlow?.Invoke(this, new CarEventArgs("Careful buddy! Gonna blow!")); + } + + // Still OK! + if (CurrentSpeed >= MaxSpeed) + carIsDead = true; + else + Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed); + } + } + } +} diff --git a/Chapter_10/AnonymousMethods/AnonymousMethods/CarEventArgs.cs b/Chapter_10/AnonymousMethods/AnonymousMethods/CarEventArgs.cs new file mode 100644 index 0000000..516c618 --- /dev/null +++ b/Chapter_10/AnonymousMethods/AnonymousMethods/CarEventArgs.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace AnonymousMethods +{ + public class CarEventArgs : EventArgs + { + public readonly string msg; + public CarEventArgs(string message) + { + msg = message; + } + } +} diff --git a/Chapter_10/AnonymousMethods/AnonymousMethods/Program.cs b/Chapter_10/AnonymousMethods/AnonymousMethods/Program.cs new file mode 100644 index 0000000..bac1a01 --- /dev/null +++ b/Chapter_10/AnonymousMethods/AnonymousMethods/Program.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace AnonymousMethods +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Anonymous Methods *****\n"); + Car c1 = new Car("SlugBug", 100, 10); + + int aboutToBlowCounter = 0; + + // Register event handlers as anonymous methods. + c1.AboutToBlow += delegate + { + aboutToBlowCounter++; + Console.WriteLine("Eek! Going too fast!"); + }; + + c1.AboutToBlow += delegate(object sender, CarEventArgs e) + { + aboutToBlowCounter++; + Console.WriteLine("Message from Car: {0}", e.msg); + }; + + c1.Exploded += delegate(object sender, CarEventArgs e) + { + Console.WriteLine("Fatal Message from Car: {0}", e.msg); + }; + + // This will eventually trigger the events. + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + Console.WriteLine("AboutToBlow event was fired {0} times.", aboutToBlowCounter); + Console.ReadLine(); + } + } +} diff --git a/Chapter_10/AnonymousMethods/AnonymousMethods/Properties/AssemblyInfo.cs b/Chapter_10/AnonymousMethods/AnonymousMethods/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ea53fdd --- /dev/null +++ b/Chapter_10/AnonymousMethods/AnonymousMethods/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AnonymousMethods")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AnonymousMethods")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("61f4890a-6914-4924-949e-35a2bf4b36a0")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/CarDelegate/CarDelegate.sln b/Chapter_10/CarDelegate/CarDelegate.sln new file mode 100644 index 0000000..94089d0 --- /dev/null +++ b/Chapter_10/CarDelegate/CarDelegate.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarDelegate", "CarDelegate\CarDelegate.csproj", "{FC975DDE-A0BE-4968-83FD-507B59319EDF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FC975DDE-A0BE-4968-83FD-507B59319EDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FC975DDE-A0BE-4968-83FD-507B59319EDF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FC975DDE-A0BE-4968-83FD-507B59319EDF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FC975DDE-A0BE-4968-83FD-507B59319EDF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/CarDelegate/CarDelegate/App.config b/Chapter_10/CarDelegate/CarDelegate/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/CarDelegate/CarDelegate/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarDelegate/CarDelegate/Car.cs b/Chapter_10/CarDelegate/CarDelegate/Car.cs new file mode 100644 index 0000000..fdcf102 --- /dev/null +++ b/Chapter_10/CarDelegate/CarDelegate/Car.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarDelegate +{ + public class Car + { + // Internal state data. + public int CurrentSpeed { get; set; } + public int MaxSpeed { get; set; } = 100; + public string PetName { get; set; } + + // Is the car alive or dead? + private bool carIsDead; + + // Class constructors. + public Car() {} + public Car( string name, int maxSp, int currSp ) + { + CurrentSpeed = currSp; + MaxSpeed = maxSp; + PetName = name; + } + + #region Delegate infrastructure + // 1) Define a delegate type. + public delegate void CarEngineHandler( string msgForCaller ); + + // 2) Define a member variable of this delegate. + private CarEngineHandler listOfHandlers; + + // 3) Add registration function for the caller. + public void RegisterWithCarEngine( CarEngineHandler methodToCall ) + { + // listOfHandlers = methodToCall; + // listOfHandlers += methodToCall; + // listOfHandlers += methodToCall; + if (listOfHandlers == null) + listOfHandlers = methodToCall; + else + listOfHandlers = Delegate.Combine(listOfHandlers, methodToCall) as CarEngineHandler; + } + + public void UnRegisterWithCarEngine( CarEngineHandler methodToCall ) + { + listOfHandlers -= methodToCall; + } + + // 4) Implement the Accelerate() method to invoke the delegate’s + // invocation list under the correct circumstances. + public void Accelerate( int delta ) + { + // If this car is 'dead', send dead message. + if (carIsDead) + { + if (listOfHandlers != null) + listOfHandlers("Sorry, this car is dead..."); + } + else + { + CurrentSpeed += delta; + + // Is this car 'almost dead'? + if (10 == (MaxSpeed - CurrentSpeed) && listOfHandlers != null) + { + listOfHandlers("Careful buddy! Gonna blow!"); + } + + if (CurrentSpeed >= MaxSpeed) + carIsDead = true; + else + Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed); + } + } + #endregion + } +} diff --git a/Chapter_10/CarDelegate/CarDelegate/CarDelegate.csproj b/Chapter_10/CarDelegate/CarDelegate/CarDelegate.csproj new file mode 100644 index 0000000..da47fda --- /dev/null +++ b/Chapter_10/CarDelegate/CarDelegate/CarDelegate.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {FC975DDE-A0BE-4968-83FD-507B59319EDF} + Exe + CarDelegate + CarDelegate + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarDelegate/CarDelegate/Program.cs b/Chapter_10/CarDelegate/CarDelegate/Program.cs new file mode 100644 index 0000000..6169cbf --- /dev/null +++ b/Chapter_10/CarDelegate/CarDelegate/Program.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarDelegate +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Delegates as event enablers *****\n"); + + // First, make a Car object. + Car c1 = new Car("SlugBug", 100, 10); + c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent)); + + // This time, hold onto the delegate object, + // so we can unregister later. + Car.CarEngineHandler handler2 = new Car.CarEngineHandler(OnCarEngineEvent2); + c1.RegisterWithCarEngine(handler2); + + // Speed up (this will trigger the events). + Console.WriteLine("***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + // Unregister from the second handler. + c1.UnRegisterWithCarEngine(handler2); + + // We won't see the 'uppercase' message anymore! + Console.WriteLine("***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + Console.ReadLine(); + } + + #region Delegate targets + // We now have TWO methods that will be called by the Car + // when sending notifications. + public static void OnCarEngineEvent( string msg ) + { + Console.WriteLine("\n***** Message From Car Object *****"); + Console.WriteLine("=> {0}", msg); + Console.WriteLine("***********************************\n"); + } + + public static void OnCarEngineEvent2( string msg ) + { + Console.WriteLine("=> {0}", msg.ToUpper()); + } + #endregion + } +} diff --git a/Chapter_10/CarDelegate/CarDelegate/Properties/AssemblyInfo.cs b/Chapter_10/CarDelegate/CarDelegate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..706c3f5 --- /dev/null +++ b/Chapter_10/CarDelegate/CarDelegate/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CarDelegate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CarDelegate")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("fc975dde-a0be-4968-83fd-507b59319edf")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion.sln b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion.sln new file mode 100644 index 0000000..d037c51 --- /dev/null +++ b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarDelegateMethodGroupConversion", "CarDelegateMethodGroupConversion\CarDelegateMethodGroupConversion.csproj", "{5327213A-3D9B-4019-9B72-C050DD787FB7}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5327213A-3D9B-4019-9B72-C050DD787FB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5327213A-3D9B-4019-9B72-C050DD787FB7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5327213A-3D9B-4019-9B72-C050DD787FB7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5327213A-3D9B-4019-9B72-C050DD787FB7}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/App.config b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Car.cs b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Car.cs new file mode 100644 index 0000000..56f3168 --- /dev/null +++ b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Car.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarDelegateMethodGroupConversion +{ + public class Car + { + // Internal state data. + public int CurrentSpeed { get; set; } + public int MaxSpeed { get; set; } = 100; + public string PetName { get; set; } + + // Is the car alive or dead? + private bool carIsDead; + + // Class constructors. + public Car() {} + public Car( string name, int maxSp, int currSp ) + { + CurrentSpeed = currSp; + MaxSpeed = maxSp; + PetName = name; + } + + #region Delegate infrastructure + // 1) Define a delegate type. + public delegate void CarEngineHandler( string msgForCaller ); + + // 2) Define a member variable of this delegate. + private CarEngineHandler listOfHandlers; + + // 3) Add registration function for the caller. + public void RegisterWithCarEngine( CarEngineHandler methodToCall ) + { + // listOfHandlers = methodToCall; + // listOfHandlers += methodToCall; + // listOfHandlers += methodToCall; + if (listOfHandlers == null) + listOfHandlers = methodToCall; + else + Delegate.Combine(listOfHandlers, methodToCall); + } + + public void UnRegisterWithCarEngine( CarEngineHandler methodToCall ) + { + listOfHandlers -= methodToCall; + } + + // 4) Implement the Accelerate() method to invoke the delegate’s + // invocation list under the correct circumstances. + public void Accelerate( int delta ) + { + // If this car is 'dead', send dead message. + if (carIsDead) + { + if (listOfHandlers != null) + listOfHandlers("Sorry, this car is dead..."); + } + else + { + CurrentSpeed += delta; + + // Is this car 'almost dead'? + if (10 == (MaxSpeed - CurrentSpeed) && listOfHandlers != null) + { + listOfHandlers("Careful buddy! Gonna blow!"); + } + + if (CurrentSpeed >= MaxSpeed) + carIsDead = true; + else + Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed); + } + } + #endregion + } +} diff --git a/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion.csproj b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion.csproj new file mode 100644 index 0000000..4ad858c --- /dev/null +++ b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {5327213A-3D9B-4019-9B72-C050DD787FB7} + Exe + CarDelegateMethodGroupConversion + CarDelegateMethodGroupConversion + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Program.cs b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Program.cs new file mode 100644 index 0000000..930c2ce --- /dev/null +++ b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Program.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarDelegateMethodGroupConversion +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Method Group Conversion *****\n"); + Car c1 = new Car(); + + // Register the simple method name. + c1.RegisterWithCarEngine(CallMeHere); + + Console.WriteLine("***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + // Unregister the simple method name. + c1.UnRegisterWithCarEngine(CallMeHere); + + // No more notifications! + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + Console.ReadLine(); + } + + static void CallMeHere( string msg ) + { + Console.WriteLine("=> Message from Car: {0}", msg); + } + } +} diff --git a/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Properties/AssemblyInfo.cs b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d86c5e7 --- /dev/null +++ b/Chapter_10/CarDelegateMethodGroupConversion/CarDelegateMethodGroupConversion/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CarDelegateMethodGroupConversion")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CarDelegateMethodGroupConversion")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5327213a-3d9b-4019-9b72-c050dd787fb7")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/CarEventArgs/CarEventArgs.sln b/Chapter_10/CarEventArgs/CarEventArgs.sln new file mode 100644 index 0000000..6e57432 --- /dev/null +++ b/Chapter_10/CarEventArgs/CarEventArgs.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarEventArgs", "CarEventArgs\CarEventArgs.csproj", "{C4627215-62E1-4EAB-9FA7-336F496414FD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C4627215-62E1-4EAB-9FA7-336F496414FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C4627215-62E1-4EAB-9FA7-336F496414FD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C4627215-62E1-4EAB-9FA7-336F496414FD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C4627215-62E1-4EAB-9FA7-336F496414FD}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/CarEventArgs/CarEventArgs/App.config b/Chapter_10/CarEventArgs/CarEventArgs/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/CarEventArgs/CarEventArgs/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarEventArgs/CarEventArgs/Car.cs b/Chapter_10/CarEventArgs/CarEventArgs/Car.cs new file mode 100644 index 0000000..27203ba --- /dev/null +++ b/Chapter_10/CarEventArgs/CarEventArgs/Car.cs @@ -0,0 +1,69 @@ +#region Using directives + +using System; +using System.Collections.Generic; +using System.Text; + +#endregion + +namespace CarEventArgs +{ + public class Car + { + #region Basic Car state data / constructors + // Internal state data. + public int CurrentSpeed { get; set; } + public int MaxSpeed { get; set; } + public string PetName { get; set; } + + // Is the car alive or dead? + private bool carIsDead; + + public Car() + { + MaxSpeed = 100; + } + + public Car(string name, int maxSp, int currSp) + { + CurrentSpeed = currSp; + MaxSpeed = maxSp; + PetName = name; + } + #endregion + + // This delegate works in conjunction with the + // Car's events. + public delegate void CarEngineHandler(object sender, CarEventArgs e); + + // This car can send these events. + public event CarEngineHandler Exploded; + public event CarEngineHandler AboutToBlow; + + public void Accelerate(int delta) + { + // If the car is dead, fire Exploded event. + if (carIsDead) + { + Exploded?.Invoke(this, new CarEventArgs("Sorry, this car is dead...")); + } + else + { + CurrentSpeed += delta; + + // Almost dead? + if (10 == MaxSpeed - CurrentSpeed + && AboutToBlow != null) + { + AboutToBlow(this, new CarEventArgs("Careful buddy! Gonna blow!")); + } + + // Still OK! + if (CurrentSpeed >= MaxSpeed) + carIsDead = true; + else + Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed); + } + } + } +} diff --git a/Chapter_10/CarEventArgs/CarEventArgs/CarEventArgs.cs b/Chapter_10/CarEventArgs/CarEventArgs/CarEventArgs.cs new file mode 100644 index 0000000..7331c5a --- /dev/null +++ b/Chapter_10/CarEventArgs/CarEventArgs/CarEventArgs.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace CarEventArgs +{ + public class CarEventArgs : EventArgs + { + public readonly string msg; + public CarEventArgs(string message) + { + msg = message; + } + } + +} diff --git a/Chapter_10/CarEventArgs/CarEventArgs/CarEventArgs.csproj b/Chapter_10/CarEventArgs/CarEventArgs/CarEventArgs.csproj new file mode 100644 index 0000000..dd7f5a3 --- /dev/null +++ b/Chapter_10/CarEventArgs/CarEventArgs/CarEventArgs.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {C4627215-62E1-4EAB-9FA7-336F496414FD} + Exe + CarEventArgs + CarEventArgs + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarEventArgs/CarEventArgs/Program.cs b/Chapter_10/CarEventArgs/CarEventArgs/Program.cs new file mode 100644 index 0000000..b7e54e7 --- /dev/null +++ b/Chapter_10/CarEventArgs/CarEventArgs/Program.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace CarEventArgs +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Events *****\n"); + Car c1 = new Car("SlugBug", 100, 10); + + // Register event handlers. + c1.AboutToBlow += CarAboutToBlow; + c1.Exploded += CarExploded; + + Console.WriteLine("***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + c1.Exploded -= CarExploded; + + Console.WriteLine("\n***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + Console.ReadLine(); + } + + #region Targets for events + public static void CarAboutToBlow(object sender, CarEventArgs e) + { + // Just to be safe, perform a + // runtime check before casting. + if (sender is Car c) + { + Console.WriteLine("Critical Message from {0}: {1}", c.PetName, e.msg); + } + } + + public static void CarExploded(object sender, CarEventArgs e) + { Console.WriteLine(e.msg); } + #endregion + } +} diff --git a/Chapter_10/CarEventArgs/CarEventArgs/Properties/AssemblyInfo.cs b/Chapter_10/CarEventArgs/CarEventArgs/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2f238c8 --- /dev/null +++ b/Chapter_10/CarEventArgs/CarEventArgs/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CarEventArgs")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CarEventArgs")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c4627215-62e1-4eab-9fa7-336f496414fd")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/CarEvents/CarEvents.sln b/Chapter_10/CarEvents/CarEvents.sln new file mode 100644 index 0000000..831b9e1 --- /dev/null +++ b/Chapter_10/CarEvents/CarEvents.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarEvents", "CarEvents\CarEvents.csproj", "{6EFF1B91-B28B-43C5-8EDB-11FB489A10D9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6EFF1B91-B28B-43C5-8EDB-11FB489A10D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6EFF1B91-B28B-43C5-8EDB-11FB489A10D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6EFF1B91-B28B-43C5-8EDB-11FB489A10D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6EFF1B91-B28B-43C5-8EDB-11FB489A10D9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/CarEvents/CarEvents/App.config b/Chapter_10/CarEvents/CarEvents/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/CarEvents/CarEvents/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarEvents/CarEvents/Car.cs b/Chapter_10/CarEvents/CarEvents/Car.cs new file mode 100644 index 0000000..62449b8 --- /dev/null +++ b/Chapter_10/CarEvents/CarEvents/Car.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarEvents +{ + public class Car + { + // Internal state data. + public int CurrentSpeed { get; set; } + public int MaxSpeed { get; set; } + public string PetName { get; set; } + + // Is the car alive or dead? + private bool carIsDead; + + // Class constructors. + public Car() { MaxSpeed = 100; } + public Car( string name, int maxSp, int currSp ) + { + CurrentSpeed = currSp; + MaxSpeed = maxSp; + PetName = name; + } + + #region Delegate / Event infrastructure + // 1) Define a delegate type. + public delegate void CarEngineHandler( string msgForCaller ); + + // This car can send these events. + public event CarEngineHandler Exploded; + public event CarEngineHandler AboutToBlow; + + public void Accelerate( int delta ) + { + // If the car is dead, fire Exploded event. + if (carIsDead) + { + Exploded?.Invoke("Sorry, this car is dead..."); + } + else + { + CurrentSpeed += delta; + + // Almost dead? + if (10 == MaxSpeed - CurrentSpeed) + { + AboutToBlow?.Invoke("Careful buddy! Gonna blow!"); + } + + // Still OK! + if (CurrentSpeed >= MaxSpeed) + carIsDead = true; + else + Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed); + } + } + #endregion + } +} diff --git a/Chapter_10/CarEvents/CarEvents/CarEvents.csproj b/Chapter_10/CarEvents/CarEvents/CarEvents.csproj new file mode 100644 index 0000000..381aa97 --- /dev/null +++ b/Chapter_10/CarEvents/CarEvents/CarEvents.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {6EFF1B91-B28B-43C5-8EDB-11FB489A10D9} + Exe + CarEvents + CarEvents + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarEvents/CarEvents/Program.cs b/Chapter_10/CarEvents/CarEvents/Program.cs new file mode 100644 index 0000000..f290a27 --- /dev/null +++ b/Chapter_10/CarEvents/CarEvents/Program.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarEvents +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Fun with Events *****\n"); + Car c1 = new Car("SlugBug", 100, 10); + + // Register event handlers. + c1.AboutToBlow += CarIsAlmostDoomed; + c1.AboutToBlow += CarAboutToBlow; + c1.Exploded += CarExploded; + + Console.WriteLine("***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + c1.Exploded -= CarExploded; + + Console.WriteLine("\n***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + Console.ReadLine(); + } + + #region Event handlers + public static void CarAboutToBlow( string msg ) + { Console.WriteLine(msg); } + + public static void CarIsAlmostDoomed( string msg ) + { Console.WriteLine("=> Critical Message from Car: {0}", msg); } + + public static void CarExploded( string msg ) + { Console.WriteLine(msg); } + #endregion + + public static void HookIntoEvents() + { + Car newCar = new Car(); + newCar.AboutToBlow += NewCar_AboutToBlow; + } + + private static void NewCar_AboutToBlow(string msgForCaller) + { + //Delete the following line and add your code! + throw new NotImplementedException(); + } + } +} diff --git a/Chapter_10/CarEvents/CarEvents/Properties/AssemblyInfo.cs b/Chapter_10/CarEvents/CarEvents/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8a588fe --- /dev/null +++ b/Chapter_10/CarEvents/CarEvents/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CarEvents")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CarEvents")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6eff1b91-b28b-43c5-8edb-11fb489a10d9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas.sln b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas.sln new file mode 100644 index 0000000..1cba078 --- /dev/null +++ b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarEventsWithLambdas", "CarEventsWithLambdas\CarEventsWithLambdas.csproj", "{A6EB61F6-238D-4481-8BDD-707824675B45}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A6EB61F6-238D-4481-8BDD-707824675B45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A6EB61F6-238D-4481-8BDD-707824675B45}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A6EB61F6-238D-4481-8BDD-707824675B45}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A6EB61F6-238D-4481-8BDD-707824675B45}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/App.config b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Car.cs b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Car.cs new file mode 100644 index 0000000..a14d99f --- /dev/null +++ b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Car.cs @@ -0,0 +1,68 @@ +#region Using directives + +using System; +using System.Collections.Generic; +using System.Text; + +#endregion + +namespace CarEventsWithLambdas +{ + public class Car + { + #region Basic Car state data / constructors + // Internal state data. + public int CurrentSpeed { get; set; } + public int MaxSpeed { get; set; } + public string PetName { get; set; } + + // Is the car alive or dead? + private bool carIsDead; + + public Car() + { + MaxSpeed = 100; + } + + public Car(string name, int maxSp, int currSp) + { + CurrentSpeed = currSp; + MaxSpeed = maxSp; + PetName = name; + } + #endregion + + // This delegate works in conjunction with the + // Car's events. + public delegate void CarEngineHandler(object sender, CarEventArgs e); + + // This car can send these events. + public event CarEngineHandler Exploded; + public event CarEngineHandler AboutToBlow; + + public void Accelerate(int delta) + { + // If the car is dead, fire Exploded event. + if (carIsDead) + { + Exploded?.Invoke(this, new CarEventArgs("Sorry, this car is dead...")); + } + else + { + CurrentSpeed += delta; + + // Almost dead? + if (10 == MaxSpeed - CurrentSpeed ) + { + AboutToBlow?.Invoke(this, new CarEventArgs("Careful buddy! Gonna blow!")); + } + + // Still OK! + if (CurrentSpeed >= MaxSpeed) + carIsDead = true; + else + Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed); + } + } + } +} diff --git a/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/CarEventArgs.cs b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/CarEventArgs.cs new file mode 100644 index 0000000..e424b67 --- /dev/null +++ b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/CarEventArgs.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace CarEventsWithLambdas +{ + public class CarEventArgs : EventArgs + { + public readonly string msg; + public CarEventArgs(string message) + { + msg = message; + } + } + +} diff --git a/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/CarEventsWithLambdas.csproj b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/CarEventsWithLambdas.csproj new file mode 100644 index 0000000..bbfefac --- /dev/null +++ b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/CarEventsWithLambdas.csproj @@ -0,0 +1,55 @@ + + + + + Debug + AnyCPU + {A6EB61F6-238D-4481-8BDD-707824675B45} + Exe + CarEventsWithLambdas + CarEventsWithLambdas + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Program.cs b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Program.cs new file mode 100644 index 0000000..4ff9e81 --- /dev/null +++ b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Program.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace CarEventsWithLambdas +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** More Fun with Lambdas *****\n"); + + // Make a car as usual. + Car c1 = new Car("SlugBug", 100, 10); + + // Hook into events with lambdas! + c1.AboutToBlow += (sender, e) => Console.WriteLine(e.msg); + c1.Exploded += (sender, e) => Console.WriteLine(e.msg); + + // Speed up (this will generate the events). + Console.WriteLine("\n***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + Console.ReadLine(); + } + } +} diff --git a/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Properties/AssemblyInfo.cs b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9b99588 --- /dev/null +++ b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CarEventsWithLambda")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CarEventsWithLambda")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a6eb61f6-238d-4481-8bdd-707824675b45")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/SimpleMath.cs b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/SimpleMath.cs new file mode 100644 index 0000000..96d0c6e --- /dev/null +++ b/Chapter_10/CarEventsWithLambdas/CarEventsWithLambdas/SimpleMath.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarEventsWithLambdas +{ + class SimpleMath + { + public int Add(int x, int y) => x + y; + public void PrintSum(int x, int y) => Console.WriteLine(x + y); + } +} diff --git a/Chapter_10/GenericCarEventArgs/GenericCarEventArgs.sln b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs.sln new file mode 100644 index 0000000..dcadd15 --- /dev/null +++ b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GenericCarEventArgs", "GenericCarEventArgs\GenericCarEventArgs.csproj", "{8334A56E-22D0-4872-886D-38D255E08C2B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8334A56E-22D0-4872-886D-38D255E08C2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8334A56E-22D0-4872-886D-38D255E08C2B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8334A56E-22D0-4872-886D-38D255E08C2B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8334A56E-22D0-4872-886D-38D255E08C2B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/App.config b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Car.cs b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Car.cs new file mode 100644 index 0000000..128f05a --- /dev/null +++ b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Car.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace GenericCarEventArgs +{ + public class Car + { + #region Basic Car state data / constructors + // Internal state data. + public int CurrentSpeed { get; set; } + public int MaxSpeed { get; set; } + public string PetName { get; set; } + + // Is the car alive or dead? + private bool carIsDead; + + public Car() + { + MaxSpeed = 100; + } + + public Car(string name, int maxSp, int currSp) + { + CurrentSpeed = currSp; + MaxSpeed = maxSp; + PetName = name; + } + #endregion + + // This delegate works in conjunction with the + // Car's events. + //public delegate void CarEngineHandler(object sender, CarEventArgs e); + + // This car can send these events. + public event EventHandler Exploded; + public event EventHandler AboutToBlow; + + + public void Accelerate(int delta) + { + // If the car is dead, fire Exploded event. + if (carIsDead) + { + Exploded?.Invoke(this, new CarEventArgs("Sorry, this car is dead...")); + } + else + { + CurrentSpeed += delta; + + // Almost dead? + if (10 == MaxSpeed - CurrentSpeed) + { + AboutToBlow?.Invoke(this, new CarEventArgs("Careful buddy! Gonna blow!")); + } + + // Still OK! + if (CurrentSpeed >= MaxSpeed) + carIsDead = true; + else + Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed); + } + } + } +} diff --git a/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/CarEventArgs.cs b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/CarEventArgs.cs new file mode 100644 index 0000000..888c102 --- /dev/null +++ b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/CarEventArgs.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace GenericCarEventArgs +{ + public class CarEventArgs : EventArgs + { + public readonly string msg; + public CarEventArgs(string message) + { + msg = message; + } + } + +} diff --git a/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/GenericCarEventArgs.csproj b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/GenericCarEventArgs.csproj new file mode 100644 index 0000000..a5094d5 --- /dev/null +++ b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/GenericCarEventArgs.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {8334A56E-22D0-4872-886D-38D255E08C2B} + Exe + GenericCarEventArgs + GenericCarEventArgs + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Program.cs b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Program.cs new file mode 100644 index 0000000..6e33f68 --- /dev/null +++ b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Program.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace GenericCarEventArgs +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Events *****\n"); + Car c1 = new Car("SlugBug", 100, 10); + + // Register event handlers. + c1.AboutToBlow += CarAboutToBlow; + c1.Exploded += CarExploded; + + EventHandler d = new EventHandler(CarExploded); + c1.Exploded += d; + + Console.WriteLine("***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + c1.Exploded -= CarExploded; + + Console.WriteLine("\n***** Speeding up *****"); + for (int i = 0; i < 6; i++) + c1.Accelerate(20); + + Console.ReadLine(); + } + + #region Targets for events + public static void CarAboutToBlow(object sender, CarEventArgs e) + { + // Just to be safe, perform a + // runtime check before casting. + if (sender is Car c) + { + Console.WriteLine("Critical Message from {0}: {1}", c.PetName, e.msg); + } + } + public static void CarExploded(object sender, CarEventArgs e) + { Console.WriteLine(e.msg); } + #endregion + } +} diff --git a/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Properties/AssemblyInfo.cs b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8ffe7d8 --- /dev/null +++ b/Chapter_10/GenericCarEventArgs/GenericCarEventArgs/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("GenericCarEventArgs")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("GenericCarEventArgs")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8334a56e-22d0-4872-886d-38d255e08c2b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/GenericDelegate/GenericDelegate.sln b/Chapter_10/GenericDelegate/GenericDelegate.sln new file mode 100644 index 0000000..8128b15 --- /dev/null +++ b/Chapter_10/GenericDelegate/GenericDelegate.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GenericDelegate", "GenericDelegate\GenericDelegate.csproj", "{34C08A22-A84D-4E55-A62D-5BC58251A565}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {34C08A22-A84D-4E55-A62D-5BC58251A565}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {34C08A22-A84D-4E55-A62D-5BC58251A565}.Debug|Any CPU.Build.0 = Debug|Any CPU + {34C08A22-A84D-4E55-A62D-5BC58251A565}.Release|Any CPU.ActiveCfg = Release|Any CPU + {34C08A22-A84D-4E55-A62D-5BC58251A565}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/GenericDelegate/GenericDelegate/App.config b/Chapter_10/GenericDelegate/GenericDelegate/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/GenericDelegate/GenericDelegate/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/GenericDelegate/GenericDelegate/GenericDelegate.csproj b/Chapter_10/GenericDelegate/GenericDelegate/GenericDelegate.csproj new file mode 100644 index 0000000..bba2860 --- /dev/null +++ b/Chapter_10/GenericDelegate/GenericDelegate/GenericDelegate.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {34C08A22-A84D-4E55-A62D-5BC58251A565} + Exe + GenericDelegate + GenericDelegate + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/GenericDelegate/GenericDelegate/Program.cs b/Chapter_10/GenericDelegate/GenericDelegate/Program.cs new file mode 100644 index 0000000..d9adaa9 --- /dev/null +++ b/Chapter_10/GenericDelegate/GenericDelegate/Program.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GenericDelegate +{ + // This generic delegate can call any method + // returning void and taking a single type parameter. + public delegate void MyGenericDelegate( T arg ); + + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Generic Delegates *****\n"); + + // Register targets. + MyGenericDelegate strTarget = new MyGenericDelegate(StringTarget); + strTarget("Some string data"); + + MyGenericDelegate intTarget = new MyGenericDelegate(IntTarget); + intTarget(9); + Console.ReadLine(); + } + + static void StringTarget( string arg ) + { + Console.WriteLine("arg in uppercase is: {0}", arg.ToUpper()); + } + + static void IntTarget( int arg ) + { + Console.WriteLine("++arg is: {0}", ++arg); + } + } +} + diff --git a/Chapter_10/GenericDelegate/GenericDelegate/Properties/AssemblyInfo.cs b/Chapter_10/GenericDelegate/GenericDelegate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..db5ecb6 --- /dev/null +++ b/Chapter_10/GenericDelegate/GenericDelegate/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("GenericDelegate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("GenericDelegate")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("34c08a22-a84d-4e55-a62d-5bc58251a565")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams.sln b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams.sln new file mode 100644 index 0000000..3771d15 --- /dev/null +++ b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LambdaExpressionsMultipleParams", "LambdaExpressionsMultipleParams\LambdaExpressionsMultipleParams.csproj", "{7BF9CA84-15BB-4C22-ABE8-7ACD75F4758F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7BF9CA84-15BB-4C22-ABE8-7ACD75F4758F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7BF9CA84-15BB-4C22-ABE8-7ACD75F4758F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7BF9CA84-15BB-4C22-ABE8-7ACD75F4758F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7BF9CA84-15BB-4C22-ABE8-7ACD75F4758F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/App.config b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams.csproj b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams.csproj new file mode 100644 index 0000000..a703a1a --- /dev/null +++ b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {7BF9CA84-15BB-4C22-ABE8-7ACD75F4758F} + Exe + LambdaExpressionsMultipleParams + LambdaExpressionsMultipleParams + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/Program.cs b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/Program.cs new file mode 100644 index 0000000..2a04ef5 --- /dev/null +++ b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/Program.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LambdaExpressionsMultipleParams +{ + #region SimpleMath (with delegates) + public class SimpleMath + { + public delegate void MathMessage( string msg, int result ); + private MathMessage mmDelegate; + + public void SetMathHandler( MathMessage target ) + { mmDelegate = target; } + + public void Add(int x, int y) + { + mmDelegate?.Invoke("Adding has completed!", x + y); + } + + } + #endregion + + class Program + { + static void Main( string[] args ) + { + // Register w/ delegate as a lambda expression. + SimpleMath m = new SimpleMath(); + m.SetMathHandler(( msg, result ) => + { Console.WriteLine("Message: {0}, Result: {1}", msg, result); }); + + // This will execute the lambda expression. + m.Add(10, 10); + Console.ReadLine(); + } + } +} diff --git a/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/Properties/AssemblyInfo.cs b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..89e0bd9 --- /dev/null +++ b/Chapter_10/LambdaExpressionsMultipleParams/LambdaExpressionsMultipleParams/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LambdaExpressionsMultipleParams")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LambdaExpressionsMultipleParams")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7bf9ca84-15bb-4c22-abe8-7acd75f4758f")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/PublicDelegateProblem/PublicDelegateProblem.sln b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem.sln new file mode 100644 index 0000000..97195a9 --- /dev/null +++ b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PublicDelegateProblem", "PublicDelegateProblem\PublicDelegateProblem.csproj", "{95BD4191-8614-45A6-A08A-FB819E13069C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {95BD4191-8614-45A6-A08A-FB819E13069C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {95BD4191-8614-45A6-A08A-FB819E13069C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {95BD4191-8614-45A6-A08A-FB819E13069C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {95BD4191-8614-45A6-A08A-FB819E13069C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/App.config b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Car.cs b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Car.cs new file mode 100644 index 0000000..d85c0f5 --- /dev/null +++ b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Car.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PublicDelegateProblem +{ + public class Car + { + public delegate void CarEngineHandler( string msgForCaller ); + + // Now a public member! + public CarEngineHandler listOfHandlers; + + // Just fire out the Exploded notification. + public void Accelerate( int delta ) + { + if (listOfHandlers != null) + listOfHandlers("Sorry, this car is dead..."); + } + } +} diff --git a/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Program.cs b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Program.cs new file mode 100644 index 0000000..242a919 --- /dev/null +++ b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Program.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PublicDelegateProblem +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Agh! No Encapsulation! *****\n"); + // Make a Car. + Car myCar = new Car(); + // We have direct access to the delegate! + myCar.listOfHandlers = new Car.CarEngineHandler(CallWhenExploded); + myCar.Accelerate(10); + + // We can now assign to a whole new object... + // confusing at best. + myCar.listOfHandlers = new Car.CarEngineHandler(CallHereToo); + myCar.Accelerate(10); + + // The caller can also directly invoke the delegate! + myCar.listOfHandlers.Invoke("hee, hee, hee..."); + Console.ReadLine(); + } + + static void CallWhenExploded( string msg ) + { Console.WriteLine(msg); } + + static void CallHereToo( string msg ) + { Console.WriteLine(msg); } + } +} diff --git a/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Properties/AssemblyInfo.cs b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e825674 --- /dev/null +++ b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("PublicDelegateProblem")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PublicDelegateProblem")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("95bd4191-8614-45a6-a08a-fb819e13069c")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/PublicDelegateProblem.csproj b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/PublicDelegateProblem.csproj new file mode 100644 index 0000000..751fbe0 --- /dev/null +++ b/Chapter_10/PublicDelegateProblem/PublicDelegateProblem/PublicDelegateProblem.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {95BD4191-8614-45A6-A08A-FB819E13069C} + Exe + PublicDelegateProblem + PublicDelegateProblem + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/SimpleDelegate/SimpleDelegate.sln b/Chapter_10/SimpleDelegate/SimpleDelegate.sln new file mode 100644 index 0000000..f2edc1d --- /dev/null +++ b/Chapter_10/SimpleDelegate/SimpleDelegate.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleDelegate", "SimpleDelegate\SimpleDelegate.csproj", "{33B79504-A7C5-4EC1-81C7-4C5F42BA76F5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {33B79504-A7C5-4EC1-81C7-4C5F42BA76F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33B79504-A7C5-4EC1-81C7-4C5F42BA76F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33B79504-A7C5-4EC1-81C7-4C5F42BA76F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33B79504-A7C5-4EC1-81C7-4C5F42BA76F5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/SimpleDelegate/SimpleDelegate/App.config b/Chapter_10/SimpleDelegate/SimpleDelegate/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/SimpleDelegate/SimpleDelegate/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/SimpleDelegate/SimpleDelegate/Program.cs b/Chapter_10/SimpleDelegate/SimpleDelegate/Program.cs new file mode 100644 index 0000000..278ec18 --- /dev/null +++ b/Chapter_10/SimpleDelegate/SimpleDelegate/Program.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SimpleDelegate +{ + // This delegate can point to any method, + // taking two integers and returning an integer. + public delegate int BinaryOp( int x, int y ); + + #region SimpleMath class + // This class contains methods BinaryOp will + // point to. + public class SimpleMath + { + public int Add( int x, int y ) => x + y; + + public int Subtract( int x, int y ) => x - y; + + public static int SquareNumber( int a ) => a * a; + } + #endregion + + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Simple Delegate Example *****\n"); + + // Create a BinaryOp delegate object that + // "points to" SimpleMath.Add(). + SimpleMath m = new SimpleMath(); + + BinaryOp b = new BinaryOp(m.Add); + DisplayDelegateInfo(b); + + // Invoke Add() method indirectly using delegate object. + Console.WriteLine("10 + 10 is {0}", b(10, 10)); + + // Compiler error! Method does not match delegate pattern! + // BinaryOp b2 = new BinaryOp(SimpleMath.SquareNumber); + + Console.ReadLine(); + } + + #region Display delegate info + static void DisplayDelegateInfo( Delegate delObj ) + { + // Print the names of each member in the + // delegate's invocation list. + foreach (Delegate d in delObj.GetInvocationList()) + { + Console.WriteLine("Method Name: {0}", d.Method); + Console.WriteLine("Type Name: {0}", d.Target); + } + } + #endregion + + } +} + diff --git a/Chapter_10/SimpleDelegate/SimpleDelegate/Properties/AssemblyInfo.cs b/Chapter_10/SimpleDelegate/SimpleDelegate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8027bb3 --- /dev/null +++ b/Chapter_10/SimpleDelegate/SimpleDelegate/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleDelegate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleDelegate")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("33b79504-a7c5-4ec1-81c7-4c5f42ba76f5")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/SimpleDelegate/SimpleDelegate/SimpleDelegate.csproj b/Chapter_10/SimpleDelegate/SimpleDelegate/SimpleDelegate.csproj new file mode 100644 index 0000000..7e8b5db --- /dev/null +++ b/Chapter_10/SimpleDelegate/SimpleDelegate/SimpleDelegate.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {33B79504-A7C5-4EC1-81C7-4C5F42BA76F5} + Exe + SimpleDelegate + SimpleDelegate + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions.sln b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions.sln new file mode 100644 index 0000000..421408d --- /dev/null +++ b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLambdaExpressions", "SimpleLambdaExpressions\SimpleLambdaExpressions.csproj", "{42BFB93C-14C2-4258-BF4A-7693329C3C1E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {42BFB93C-14C2-4258-BF4A-7693329C3C1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {42BFB93C-14C2-4258-BF4A-7693329C3C1E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {42BFB93C-14C2-4258-BF4A-7693329C3C1E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {42BFB93C-14C2-4258-BF4A-7693329C3C1E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/App.config b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/Program.cs b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/Program.cs new file mode 100644 index 0000000..d94b88b --- /dev/null +++ b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/Program.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SimpleLambdaExpressions +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Fun with Lambdas *****\n"); + TraditionalDelegateSyntax(); + AnonymousMethodSyntax(); + Console.WriteLine(); + + LambdaExpressionSyntax(); + Console.ReadLine(); + } + + #region Traditional delegate syntax + static void TraditionalDelegateSyntax() + { + // Make a list of integers. + List list = new List(); + list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 }); + + // Call FindAll() using traditional delegate syntax. + Predicate callback = IsEvenNumber; + List evenNumbers = list.FindAll(callback); + + Console.WriteLine("Here are your even numbers:"); + foreach (int evenNumber in evenNumbers) + { + Console.Write("{0}\t", evenNumber); + } + Console.WriteLine(); + } + + // Target for the Predicate<> delegate. + static bool IsEvenNumber( int i ) + { + // Is it an even number? + return (i % 2) == 0; + } + #endregion + + #region Anonymous method systax + static void AnonymousMethodSyntax() + { + // Make a list of integers. + List list = new List(); + list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 }); + + // Now, use an anonymous method. + List evenNumbers = list.FindAll(delegate( int i ) + { return (i % 2) == 0; }); + + Console.WriteLine("Here are your even numbers:"); + foreach (int evenNumber in evenNumbers) + { + Console.Write("{0}\t", evenNumber); + } + Console.WriteLine(); + } + #endregion + + #region Lambda! + static void LambdaExpressionSyntax() + { + // Make a list of integers. + List list = new List(); + list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 }); + + // Now process each argument within a group of + // code statements. + List evenNumbers = list.FindAll(( i ) => + { + Console.WriteLine("value of i is currently: {0}", i); + bool isEven = ((i % 2) == 0); + return isEven; + }); + + Console.WriteLine("Here are your even numbers:"); + foreach (int evenNumber in evenNumbers) + { + Console.Write("{0}\t", evenNumber); + } + Console.WriteLine(); + } + #endregion + } +} diff --git a/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/Properties/AssemblyInfo.cs b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1b1d65f --- /dev/null +++ b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleLambdaExpressions")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleLambdaExpressions")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("42bfb93c-14c2-4258-bf4a-7693329c3c1e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/SimpleLambdaExpressions.csproj b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/SimpleLambdaExpressions.csproj new file mode 100644 index 0000000..dd418a0 --- /dev/null +++ b/Chapter_10/SimpleLambdaExpressions/SimpleLambdaExpressions/SimpleLambdaExpressions.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {42BFB93C-14C2-4258-BF4A-7693329C3C1E} + Exe + SimpleLambdaExpressions + SimpleLambdaExpressions + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_11/AnonymousTypes/AnonymousTypes.sln b/Chapter_11/AnonymousTypes/AnonymousTypes.sln new file mode 100644 index 0000000..e1e5dc7 --- /dev/null +++ b/Chapter_11/AnonymousTypes/AnonymousTypes.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnonymousTypes", "AnonymousTypes\AnonymousTypes.csproj", "{B08F26F3-0B1F-4F5C-B44C-4BF418029A41}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B08F26F3-0B1F-4F5C-B44C-4BF418029A41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B08F26F3-0B1F-4F5C-B44C-4BF418029A41}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B08F26F3-0B1F-4F5C-B44C-4BF418029A41}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B08F26F3-0B1F-4F5C-B44C-4BF418029A41}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_11/AnonymousTypes/AnonymousTypes/AnonymousTypes.csproj b/Chapter_11/AnonymousTypes/AnonymousTypes/AnonymousTypes.csproj new file mode 100644 index 0000000..90e4b31 --- /dev/null +++ b/Chapter_11/AnonymousTypes/AnonymousTypes/AnonymousTypes.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {B08F26F3-0B1F-4F5C-B44C-4BF418029A41} + Exe + AnonymousTypes + AnonymousTypes + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_11/AnonymousTypes/AnonymousTypes/App.config b/Chapter_11/AnonymousTypes/AnonymousTypes/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_11/AnonymousTypes/AnonymousTypes/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_11/AnonymousTypes/AnonymousTypes/Program.cs b/Chapter_11/AnonymousTypes/AnonymousTypes/Program.cs new file mode 100644 index 0000000..c8085ce --- /dev/null +++ b/Chapter_11/AnonymousTypes/AnonymousTypes/Program.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AnonymousTypes +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Fun with Anonymous Types *****\n"); + + // Make an anonymous type representing a car using hard coded data. + var myCar = new { Color = "Bright Pink", Make = "Saab", CurrentSpeed = 55 }; + + // Reflect over what the compiler generated. + ReflectOverAnonymousType(myCar); + + // Now show the color and make. + Console.WriteLine("My car is a {0} {1}.", myCar.Color, myCar.Make); + + // Now call our helper method to build anonymous type via args. + BuildAnonType("BMW", "Black", 90); + + EqualityTest(); + + Console.ReadLine(); + } + + static void BuildAnonType( string make, string color, int currSp ) + { + // Build anon type using incoming args. + var car = new { Make = make, Color = color, Speed = currSp }; + + // Note you can now use this type to get the property data! + Console.WriteLine("You have a {0} {1} going {2} MPH", + car.Color, car.Make, car.Speed); + + // Anon types have custom implementations of each virtual + // method of System.Object. For example: + Console.WriteLine("ToString() == {0}", car.ToString()); + } + + static void ReflectOverAnonymousType( object obj ) + { + Console.WriteLine("obj is an instance of: {0}", obj.GetType().Name); + Console.WriteLine("Base class of {0} is {1}", obj.GetType().Name, obj.GetType().BaseType); + Console.WriteLine("obj.ToString() == {0}", obj.ToString()); + Console.WriteLine("obj.GetHashCode() == {0}", obj.GetHashCode()); + Console.WriteLine(); + } + + static void EqualityTest() + { + // Make 2 anonymous classes with identical name/value pairs. + var firstCar = new { Color = "Bright Pink", Make = "Saab", CurrentSpeed = 55 }; + var secondCar = new { Color = "Bright Pink", Make = "Saab", CurrentSpeed = 55 }; + + // Are they considered equal when using Equals()? + if (firstCar.Equals(secondCar)) + Console.WriteLine("Same anonymous object!"); + else + Console.WriteLine("Not the same anonymous object!"); + + // Are they considered equal when using ==? + if (firstCar == secondCar) + Console.WriteLine("Same anonymous object!"); + else + Console.WriteLine("Not the same anonymous object!"); + + // Are these objects the same underlying type? + if (firstCar.GetType().Name == secondCar.GetType().Name) + Console.WriteLine("We are both the same type!"); + else + Console.WriteLine("We are different types!"); + + // Show all the details. + Console.WriteLine(); + ReflectOverAnonymousType(firstCar); + ReflectOverAnonymousType(secondCar); + } + + } +} diff --git a/Chapter_11/AnonymousTypes/AnonymousTypes/Properties/AssemblyInfo.cs b/Chapter_11/AnonymousTypes/AnonymousTypes/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4fa3334 --- /dev/null +++ b/Chapter_11/AnonymousTypes/AnonymousTypes/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AnonymousTypes")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AnonymousTypes")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b08f26f3-0b1f-4f5c-b44c-4bf418029a41")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_11/CustomConversions/CustomConversions.sln b/Chapter_11/CustomConversions/CustomConversions.sln new file mode 100644 index 0000000..67367c8 --- /dev/null +++ b/Chapter_11/CustomConversions/CustomConversions.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomConversions", "CustomConversions\CustomConversions.csproj", "{414C8D8D-26F9-472E-8A26-1122B28A4E54}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {414C8D8D-26F9-472E-8A26-1122B28A4E54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {414C8D8D-26F9-472E-8A26-1122B28A4E54}.Debug|Any CPU.Build.0 = Debug|Any CPU + {414C8D8D-26F9-472E-8A26-1122B28A4E54}.Release|Any CPU.ActiveCfg = Release|Any CPU + {414C8D8D-26F9-472E-8A26-1122B28A4E54}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_11/CustomConversions/CustomConversions/App.config b/Chapter_11/CustomConversions/CustomConversions/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_11/CustomConversions/CustomConversions/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_11/CustomConversions/CustomConversions/CustomConversions.csproj b/Chapter_11/CustomConversions/CustomConversions/CustomConversions.csproj new file mode 100644 index 0000000..0d3ab3b --- /dev/null +++ b/Chapter_11/CustomConversions/CustomConversions/CustomConversions.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {414C8D8D-26F9-472E-8A26-1122B28A4E54} + Exe + CustomConversions + CustomConversions + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_11/CustomConversions/CustomConversions/Program.cs b/Chapter_11/CustomConversions/CustomConversions/Program.cs new file mode 100644 index 0000000..564c11c --- /dev/null +++ b/Chapter_11/CustomConversions/CustomConversions/Program.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CustomConversions +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Fun with Conversions *****\n"); + + // Make a Rectangle. + Rectangle r = new Rectangle(15, 4); + Console.WriteLine(r.ToString()); + r.Draw(); + + Console.WriteLine(); + + // Convert r into a Square, + // based on the height of the Rectangle. + Square s = (Square)r; + Console.WriteLine(s.ToString()); + s.Draw(); + Console.WriteLine(); + + // Convert Rectangle to Square to invoke method. + Rectangle rect = new Rectangle(10, 5); + DrawSquare((Square)rect); + Console.WriteLine(); + + // Converting an int to a Square. + Square sq2 = (Square)90; + Console.WriteLine("sq2 = {0}", sq2); + + // Converting a Square to a int. + int side = (int)sq2; + Console.WriteLine("Side length of sq2 = {0}", side); + Console.WriteLine(); + + Square s3 = new Square {Length = 83}; + + // Attempt to make an implicit cast? + Rectangle rect2 = s3; + + Console.ReadLine(); + } + + // This method requires a Square type. + static void DrawSquare( Square sq ) + { + Console.WriteLine(sq.ToString()); + sq.Draw(); + } + + } +} diff --git a/Chapter_11/CustomConversions/CustomConversions/Properties/AssemblyInfo.cs b/Chapter_11/CustomConversions/CustomConversions/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..13eef72 --- /dev/null +++ b/Chapter_11/CustomConversions/CustomConversions/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CustomConversions")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CustomConversions")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("414c8d8d-26f9-472e-8a26-1122b28a4e54")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_11/CustomConversions/CustomConversions/Rectangle.cs b/Chapter_11/CustomConversions/CustomConversions/Rectangle.cs new file mode 100644 index 0000000..40887c5 --- /dev/null +++ b/Chapter_11/CustomConversions/CustomConversions/Rectangle.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CustomConversions +{ + public struct Rectangle + { + public int Width { get; set; } + public int Height { get; set; } + + public Rectangle( int w, int h ) : this() + { + Width = w; + Height = h; + } + + public void Draw() + { + for (int i = 0; i < Height; i++) + { + for (int j = 0; j < Width; j++) + { + Console.Write("*"); + } + Console.WriteLine(); + } + } + + public override string ToString() => $"[Width = {Width}; Height = {Height}]"; + + public static implicit operator Rectangle( Square s ) + { + Rectangle r = new Rectangle + { + Height = s.Length, + Width = s.Length * 2 // Assume the length of the new Rectangle with (Length x 2) + }; + + return r; + } + + } +} diff --git a/Chapter_11/CustomConversions/CustomConversions/Square.cs b/Chapter_11/CustomConversions/CustomConversions/Square.cs new file mode 100644 index 0000000..8ea75d6 --- /dev/null +++ b/Chapter_11/CustomConversions/CustomConversions/Square.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CustomConversions +{ + public struct Square + { + public int Length { get; set; } + + public Square( int l ) : this() + { + Length = l; + } + + public void Draw() + { + for (int i = 0; i < Length; i++) + { + for (int j = 0; j < Length; j++) + { + Console.Write("*"); + } + Console.WriteLine(); + } + } + + public override string ToString() => $"[Length = {Length}]"; + + #region Conversion operations + // Rectangles can be explicitly converted + // into Squares. + public static explicit operator Square( Rectangle r ) + { + Square s = new Square {Length = r.Height}; + return s; + } + + public static explicit operator Square( int sideLength ) + { + Square newSq = new Square {Length = sideLength}; + return newSq; + } + + public static explicit operator int( Square s ) => s.Length; + + #endregion + } + +} diff --git a/Chapter_11/ExtensionMethods/ExtensionMethods.sln b/Chapter_11/ExtensionMethods/ExtensionMethods.sln new file mode 100644 index 0000000..95277fc --- /dev/null +++ b/Chapter_11/ExtensionMethods/ExtensionMethods.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExtensionMethods", "ExtensionMethods\ExtensionMethods.csproj", "{A6637A94-4A42-4AC8-AB95-A86C5952CF63}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A6637A94-4A42-4AC8-AB95-A86C5952CF63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A6637A94-4A42-4AC8-AB95-A86C5952CF63}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A6637A94-4A42-4AC8-AB95-A86C5952CF63}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A6637A94-4A42-4AC8-AB95-A86C5952CF63}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_11/ExtensionMethods/ExtensionMethods/App.config b/Chapter_11/ExtensionMethods/ExtensionMethods/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_11/ExtensionMethods/ExtensionMethods/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_11/ExtensionMethods/ExtensionMethods/ExtensionMethods.csproj b/Chapter_11/ExtensionMethods/ExtensionMethods/ExtensionMethods.csproj new file mode 100644 index 0000000..0be9cd9 --- /dev/null +++ b/Chapter_11/ExtensionMethods/ExtensionMethods/ExtensionMethods.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {A6637A94-4A42-4AC8-AB95-A86C5952CF63} + Exe + ExtensionMethods + ExtensionMethods + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_11/ExtensionMethods/ExtensionMethods/MyExtensions.cs b/Chapter_11/ExtensionMethods/ExtensionMethods/MyExtensions.cs new file mode 100644 index 0000000..7515380 --- /dev/null +++ b/Chapter_11/ExtensionMethods/ExtensionMethods/MyExtensions.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace MyExtensionMethods +{ + static class MyExtensions + { + // This method allows any object to display the assembly + // it is defined in. + public static void DisplayDefiningAssembly( this object obj ) + { + Console.WriteLine("{0} lives here: => {1}\n", obj.GetType().Name, + Assembly.GetAssembly(obj.GetType()).GetName().Name); + } + + // This method allows any integer to reverse its digits. + // For example, 56 would return 65. + public static int ReverseDigits( this int i ) + { + // Translate int into a string, and then + // get all the characters. + char[] digits = i.ToString().ToCharArray(); + + // Now reverse items in the array. + Array.Reverse(digits); + + // Put back into string. + string newDigits = new string(digits); + + // Finally, return the modified string back as an int. + return int.Parse(newDigits); + } + } +} diff --git a/Chapter_11/ExtensionMethods/ExtensionMethods/Program.cs b/Chapter_11/ExtensionMethods/ExtensionMethods/Program.cs new file mode 100644 index 0000000..9d9a660 --- /dev/null +++ b/Chapter_11/ExtensionMethods/ExtensionMethods/Program.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MyExtensionMethods; + +namespace ExtensionMethods +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Fun with Extension Methods *****\n"); + + // The int has assumed a new identity! + int myInt = 12345678; + myInt.DisplayDefiningAssembly(); + + // So has the DataSet! + System.Data.DataSet d = new System.Data.DataSet(); + d.DisplayDefiningAssembly(); + + // And the SoundPlayer! + System.Media.SoundPlayer sp = new System.Media.SoundPlayer(); + sp.DisplayDefiningAssembly(); + + // Use new integer functionality. + Console.WriteLine("Value of myInt: {0}", myInt); + Console.WriteLine("Reversed digits of myInt: {0}", myInt.ReverseDigits()); + + Console.ReadLine(); + } + + } +} diff --git a/Chapter_11/ExtensionMethods/ExtensionMethods/Properties/AssemblyInfo.cs b/Chapter_11/ExtensionMethods/ExtensionMethods/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..33855d2 --- /dev/null +++ b/Chapter_11/ExtensionMethods/ExtensionMethods/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ExtensionMethods")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ExtensionMethods")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a6637a94-4a42-4ac8-ab95-a86c5952cf63")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_11/InterfaceExtensions/InterfaceExtensions.sln b/Chapter_11/InterfaceExtensions/InterfaceExtensions.sln new file mode 100644 index 0000000..8b6bf1e --- /dev/null +++ b/Chapter_11/InterfaceExtensions/InterfaceExtensions.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InterfaceExtensions", "InterfaceExtensions\InterfaceExtensions.csproj", "{9411D96D-2E00-4D36-BEE6-3918022888FE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9411D96D-2E00-4D36-BEE6-3918022888FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9411D96D-2E00-4D36-BEE6-3918022888FE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9411D96D-2E00-4D36-BEE6-3918022888FE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9411D96D-2E00-4D36-BEE6-3918022888FE}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_11/InterfaceExtensions/InterfaceExtensions/App.config b/Chapter_11/InterfaceExtensions/InterfaceExtensions/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_11/InterfaceExtensions/InterfaceExtensions/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_11/InterfaceExtensions/InterfaceExtensions/InterfaceExtensions.csproj b/Chapter_11/InterfaceExtensions/InterfaceExtensions/InterfaceExtensions.csproj new file mode 100644 index 0000000..bf89a6c --- /dev/null +++ b/Chapter_11/InterfaceExtensions/InterfaceExtensions/InterfaceExtensions.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {9411D96D-2E00-4D36-BEE6-3918022888FE} + Exe + InterfaceExtensions + InterfaceExtensions + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_11/InterfaceExtensions/InterfaceExtensions/Program.cs b/Chapter_11/InterfaceExtensions/InterfaceExtensions/Program.cs new file mode 100644 index 0000000..b37294c --- /dev/null +++ b/Chapter_11/InterfaceExtensions/InterfaceExtensions/Program.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace InterfaceExtensions +{ + static class AnnoyingExtensions + { + public static void PrintDataAndBeep(this System.Collections.IEnumerable iterator) + { + foreach (var item in iterator) + { + Console.WriteLine(item); + Console.Beep(); + } + } + } + + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Extending Interface Compatible Types *****\n"); + + // System.Array implements IEnumerable! + string[] data = { "Wow", "this", "is", "sort", "of", "annoying", + "but", "in", "a", "weird", "way", "fun!"}; + + data.PrintDataAndBeep(); + + Console.WriteLine(); + + // List implements IEnumerable! + List myInts = new List() { 10, 15, 20 }; + myInts.PrintDataAndBeep(); + + Console.ReadLine(); + } + } +} diff --git a/Chapter_11/InterfaceExtensions/InterfaceExtensions/Properties/AssemblyInfo.cs b/Chapter_11/InterfaceExtensions/InterfaceExtensions/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3b17c6e --- /dev/null +++ b/Chapter_11/InterfaceExtensions/InterfaceExtensions/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("InterfaceExtensions")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("InterfaceExtensions")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9411d96d-2e00-4d36-bee6-3918022888fe")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_11/OverloadedOps/OverloadedOps.sln b/Chapter_11/OverloadedOps/OverloadedOps.sln new file mode 100644 index 0000000..1fed31a --- /dev/null +++ b/Chapter_11/OverloadedOps/OverloadedOps.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OverloadedOps", "OverloadedOps\OverloadedOps.csproj", "{4096AABB-B0DC-4823-AA05-4A3AF15CE9E1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4096AABB-B0DC-4823-AA05-4A3AF15CE9E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4096AABB-B0DC-4823-AA05-4A3AF15CE9E1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4096AABB-B0DC-4823-AA05-4A3AF15CE9E1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4096AABB-B0DC-4823-AA05-4A3AF15CE9E1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_11/OverloadedOps/OverloadedOps/App.config b/Chapter_11/OverloadedOps/OverloadedOps/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_11/OverloadedOps/OverloadedOps/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_11/OverloadedOps/OverloadedOps/OverloadedOps.csproj b/Chapter_11/OverloadedOps/OverloadedOps/OverloadedOps.csproj new file mode 100644 index 0000000..8dd1180 --- /dev/null +++ b/Chapter_11/OverloadedOps/OverloadedOps/OverloadedOps.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {4096AABB-B0DC-4823-AA05-4A3AF15CE9E1} + Exe + OverloadedOps + OverloadedOps + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_11/OverloadedOps/OverloadedOps/Point.cs b/Chapter_11/OverloadedOps/OverloadedOps/Point.cs new file mode 100644 index 0000000..8fbd8f0 --- /dev/null +++ b/Chapter_11/OverloadedOps/OverloadedOps/Point.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OverloadedOps +{ + // Just a simple, everyday C# class. + public class Point : IComparable + { + public int X { get; set; } + public int Y { get; set; } + + public Point( int xPos, int yPos ) + { + X = xPos; + Y = yPos; + } + + #region Object overrides + public override string ToString() => $"[{this.X}, {this.Y}]"; + + public override bool Equals( object o ) => o?.ToString() == this.ToString(); + + public override int GetHashCode() => this.ToString().GetHashCode(); + #endregion + + #region Overloaded ops + // overloaded operator + + public static Point operator +( Point p1, Point p2 ) => new Point(p1.X + p2.X, p1.Y + p2.Y); + + // overloaded operator - + public static Point operator -( Point p1, Point p2 ) => new Point(p1.X - p2.X, p1.Y - p2.Y); + + public static Point operator +( Point p1, int change ) => new Point(p1.X + change, p1.Y + change); + + public static Point operator +( int change, Point p1 ) => new Point(p1.X + change, p1.Y + change); + + // Add 1 to the X/Y values incoming Point. + public static Point operator ++( Point p1 ) => new Point(p1.X + 1, p1.Y + 1); + + // Subtract 1 from the X/Y values incoming Point. + public static Point operator --( Point p1 ) => new Point(p1.X - 1, p1.Y - 1); + + // Now let's overload the == and != operators. + public static bool operator ==( Point p1, Point p2 ) => p1.Equals(p2); + + public static bool operator !=( Point p1, Point p2 ) => !p1.Equals(p2); + + public static bool operator <( Point p1, Point p2 ) => p1.CompareTo(p2) < 0; + + public static bool operator >( Point p1, Point p2 ) => p1.CompareTo(p2) > 0; + + public static bool operator <=( Point p1, Point p2 ) => p1.CompareTo(p2) <= 0; + + public static bool operator >=( Point p1, Point p2 ) => p1.CompareTo(p2) >= 0; + + #endregion + + public int CompareTo( Point other ) + { + if (this.X > other.X && this.Y > other.Y) + return 1; + if (this.X < other.X && this.Y < other.Y) + return -1; + else + return 0; + } + } +} diff --git a/Chapter_11/OverloadedOps/OverloadedOps/Program.cs b/Chapter_11/OverloadedOps/OverloadedOps/Program.cs new file mode 100644 index 0000000..3b9e951 --- /dev/null +++ b/Chapter_11/OverloadedOps/OverloadedOps/Program.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OverloadedOps +{ + class Program + { + // Adding and subtracting two points? + static void Main( string[] args ) + { + Console.WriteLine("***** Fun with Overloaded Operators *****\n"); + + // Make two points. + Point ptOne = new Point(100, 100); + Point ptTwo = new Point(40, 40); + Console.WriteLine("ptOne = {0}", ptOne); + Console.WriteLine("ptTwo = {0}", ptTwo); + Console.WriteLine(); + + // Add the points to make a bigger point? + Console.WriteLine("ptOne + ptTwo: {0} ", ptOne + ptTwo); + + // Subtract the points to make a smaller point? + Console.WriteLine("ptOne - ptTwo: {0} ", ptOne - ptTwo); + Console.WriteLine(); + + // Prints [110, 110] + Point biggerPoint = ptOne + 10; + Console.WriteLine("ptOne + 10 = {0}", biggerPoint); + + // Prints [120, 120] + Console.WriteLine("10 + biggerPoint = {0}", 10 + biggerPoint); + Console.WriteLine(); + + // Freebie += + Point ptThree = new Point(90, 5); + Console.WriteLine("ptThree = {0}", ptThree); + Console.WriteLine("ptThree += ptTwo: {0}", ptThree += ptTwo); + Console.WriteLine(); + + // Freebie -= + Point ptFour = new Point(0, 500); + Console.WriteLine("ptFour = {0}", ptFour); + Console.WriteLine("ptFour -= ptThree: {0}", ptFour -= ptThree); + Console.WriteLine(); + + // Applying the ++ and -- unary operators to a Point. + Point ptFive = new Point(1, 1); + Console.WriteLine("++ptFive = {0}", ++ptFive); // [2, 2] + Console.WriteLine("--ptFive = {0}", --ptFive); // [1, 1] + Console.WriteLine(); + + // Apply same operators as postincrement/decrement. + Point ptSix = new Point(20, 20); + Console.WriteLine("ptSix++ = {0}", ptSix++); // [20, 20] + Console.WriteLine("ptSix-- = {0}", ptSix--); // [21, 21] + Console.WriteLine(); + + Console.WriteLine("ptOne == ptTwo : {0}", ptOne == ptTwo); + Console.WriteLine("ptOne != ptTwo : {0}", ptOne != ptTwo); + Console.WriteLine(); + + Console.WriteLine("ptOne < ptTwo : {0}", ptOne < ptTwo); + Console.WriteLine("ptOne > ptTwo : {0}", ptOne > ptTwo); + + Console.ReadLine(); + } + } +} diff --git a/Chapter_11/OverloadedOps/OverloadedOps/Properties/AssemblyInfo.cs b/Chapter_11/OverloadedOps/OverloadedOps/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..dc677f1 --- /dev/null +++ b/Chapter_11/OverloadedOps/OverloadedOps/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OverloadedOps")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OverloadedOps")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4096aabb-b0dc-4823-aa05-4a3af15ce9e1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_11/SimpleIndexer/SimpleIndexer.sln b/Chapter_11/SimpleIndexer/SimpleIndexer.sln new file mode 100644 index 0000000..43010c5 --- /dev/null +++ b/Chapter_11/SimpleIndexer/SimpleIndexer.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleIndexer", "SimpleIndexer\SimpleIndexer.csproj", "{8E3059C8-0C8F-48B1-93C9-30095B91F347}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8E3059C8-0C8F-48B1-93C9-30095B91F347}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E3059C8-0C8F-48B1-93C9-30095B91F347}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E3059C8-0C8F-48B1-93C9-30095B91F347}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E3059C8-0C8F-48B1-93C9-30095B91F347}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_11/SimpleIndexer/SimpleIndexer/App.config b/Chapter_11/SimpleIndexer/SimpleIndexer/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_11/SimpleIndexer/SimpleIndexer/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_11/SimpleIndexer/SimpleIndexer/Person.cs b/Chapter_11/SimpleIndexer/SimpleIndexer/Person.cs new file mode 100644 index 0000000..8ef9682 --- /dev/null +++ b/Chapter_11/SimpleIndexer/SimpleIndexer/Person.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SimpleIndexer +{ + public class Person + { + public int Age { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + + public Person() { } + public Person(string firstName, string lastName, int age) + { + Age = age; + FirstName = firstName; + LastName = lastName; + } + + public override string ToString() + { + return $"Name: {FirstName} {LastName}, Age: {Age}"; + } + } +} diff --git a/Chapter_11/SimpleIndexer/SimpleIndexer/PersonCollection.cs b/Chapter_11/SimpleIndexer/SimpleIndexer/PersonCollection.cs new file mode 100644 index 0000000..8e0ef57 --- /dev/null +++ b/Chapter_11/SimpleIndexer/SimpleIndexer/PersonCollection.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Collections; + +namespace SimpleIndexer +{ + public class PersonCollection : IEnumerable + { + private ArrayList arPeople = new ArrayList(); + + // Cast for caller. + public Person GetPerson(int pos) => (Person)arPeople[pos]; + + // Only insert Person types. + public void AddPerson(Person p) + { arPeople.Add(p); } + + public void ClearPeople() + { arPeople.Clear(); } + + public int Count => arPeople.Count; + + // Foreach enumeration support. + IEnumerator IEnumerable.GetEnumerator() => arPeople.GetEnumerator(); + + // Custom indexer for this class. + public Person this[int index] + { + get => (Person)arPeople[index]; + set => arPeople.Insert(index, value); + } + } +} diff --git a/Chapter_11/SimpleIndexer/SimpleIndexer/Program.cs b/Chapter_11/SimpleIndexer/SimpleIndexer/Program.cs new file mode 100644 index 0000000..f94808b --- /dev/null +++ b/Chapter_11/SimpleIndexer/SimpleIndexer/Program.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SimpleIndexer +{ + // Indexers allow you to access items in an array-like fashion. + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Fun with Indexers *****\n"); + + PersonCollection myPeople = new PersonCollection(); + + // Add objects with indexer syntax. + myPeople[0] = new Person("Homer", "Simpson", 40); + myPeople[1] = new Person("Marge", "Simpson", 38); + myPeople[2] = new Person("Lisa", "Simpson", 9); + myPeople[3] = new Person("Bart", "Simpson", 7); + myPeople[4] = new Person("Maggie", "Simpson", 2); + + // Now obtain and display each item using indexer. + for (int i = 0; i < myPeople.Count; i++) + { + Console.WriteLine("Person number: {0}", i); + Console.WriteLine("Name: {0} {1}", + myPeople[i].FirstName, myPeople[i].LastName); + Console.WriteLine("Age: {0}", myPeople[i].Age); + Console.WriteLine(); + } + } + + static void UseGenericListOfPeople() + { + List myPeople = new List(); + myPeople.Add(new Person("Lisa", "Simpson", 9)); + myPeople.Add(new Person("Bart", "Simpson", 7)); + + // Change first person with indexer. + myPeople[0] = new Person("Maggie", "Simpson", 2); + + // Now obtain and display each item using indexer. + for (int i = 0; i < myPeople.Count; i++) + { + Console.WriteLine("Person number: {0}", i); + Console.WriteLine("Name: {0} {1}", myPeople[i].FirstName, + myPeople[i].LastName); + Console.WriteLine("Age: {0}", myPeople[i].Age); + Console.WriteLine(); + } + } + + } +} diff --git a/Chapter_11/SimpleIndexer/SimpleIndexer/Properties/AssemblyInfo.cs b/Chapter_11/SimpleIndexer/SimpleIndexer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..95123dd --- /dev/null +++ b/Chapter_11/SimpleIndexer/SimpleIndexer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleIndexer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleIndexer")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8e3059c8-0c8f-48b1-93c9-30095b91f347")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_11/SimpleIndexer/SimpleIndexer/SimpleIndexer.csproj b/Chapter_11/SimpleIndexer/SimpleIndexer/SimpleIndexer.csproj new file mode 100644 index 0000000..ac1d6bb --- /dev/null +++ b/Chapter_11/SimpleIndexer/SimpleIndexer/SimpleIndexer.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {8E3059C8-0C8F-48B1-93C9-30095B91F347} + Exe + SimpleIndexer + SimpleIndexer + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_11/StringIndexer/StringIndexer.sln b/Chapter_11/StringIndexer/StringIndexer.sln new file mode 100644 index 0000000..d17b99c --- /dev/null +++ b/Chapter_11/StringIndexer/StringIndexer.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StringIndexer", "StringIndexer\StringIndexer.csproj", "{56D19384-C324-4D56-B702-FCBDA1583AFE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {56D19384-C324-4D56-B702-FCBDA1583AFE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {56D19384-C324-4D56-B702-FCBDA1583AFE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {56D19384-C324-4D56-B702-FCBDA1583AFE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {56D19384-C324-4D56-B702-FCBDA1583AFE}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_11/StringIndexer/StringIndexer/App.config b/Chapter_11/StringIndexer/StringIndexer/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_11/StringIndexer/StringIndexer/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_11/StringIndexer/StringIndexer/Person.cs b/Chapter_11/StringIndexer/StringIndexer/Person.cs new file mode 100644 index 0000000..e7a34a6 --- /dev/null +++ b/Chapter_11/StringIndexer/StringIndexer/Person.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace StringIndexer +{ + public class Person + { + public int Age { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + + public Person() { } + public Person(string firstName, string lastName, int age) + { + Age = age; + FirstName = firstName; + LastName = lastName; + } + + public override string ToString() + { + return string.Format("Name: {0} {1}, Age: {2}", + FirstName, LastName, Age); + } + } +} diff --git a/Chapter_11/StringIndexer/StringIndexer/PersonCollection.cs b/Chapter_11/StringIndexer/StringIndexer/PersonCollection.cs new file mode 100644 index 0000000..3709b4c --- /dev/null +++ b/Chapter_11/StringIndexer/StringIndexer/PersonCollection.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Collections; + +namespace StringIndexer +{ + public class PersonCollection : IEnumerable + { + private Dictionary listPeople = new Dictionary(); + + // This indexer returns a person based on a string index. + public Person this[string name] + { + get => (Person)listPeople[name]; + set => listPeople[name] = value; + } + + public void ClearPeople() + { listPeople.Clear(); } + + public int Count => listPeople.Count; + + IEnumerator IEnumerable.GetEnumerator() => listPeople.GetEnumerator(); + } +} diff --git a/Chapter_11/StringIndexer/StringIndexer/Program.cs b/Chapter_11/StringIndexer/StringIndexer/Program.cs new file mode 100644 index 0000000..f53b5f1 --- /dev/null +++ b/Chapter_11/StringIndexer/StringIndexer/Program.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StringIndexer +{ + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Fun with Indexers *****\n"); + + PersonCollection myPeople = new PersonCollection(); + + myPeople["Homer"] = new Person("Homer", "Simpson", 40); + myPeople["Marge"] = new Person("Marge", "Simpson", 38); + + // Get "Homer" and print data. + Person homer = myPeople["Homer"]; + Console.WriteLine(homer.ToString()); + + Console.ReadLine(); + } + } +} diff --git a/Chapter_11/StringIndexer/StringIndexer/Properties/AssemblyInfo.cs b/Chapter_11/StringIndexer/StringIndexer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9f7fc4d --- /dev/null +++ b/Chapter_11/StringIndexer/StringIndexer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("StringIndexer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("StringIndexer")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("56d19384-c324-4d56-b702-fcbda1583afe")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_11/StringIndexer/StringIndexer/StringIndexer.csproj b/Chapter_11/StringIndexer/StringIndexer/StringIndexer.csproj new file mode 100644 index 0000000..e655ad1 --- /dev/null +++ b/Chapter_11/StringIndexer/StringIndexer/StringIndexer.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {56D19384-C324-4D56-B702-FCBDA1583AFE} + Exe + StringIndexer + StringIndexer + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_11/UnsafeCode/UnsafeCode.sln b/Chapter_11/UnsafeCode/UnsafeCode.sln new file mode 100644 index 0000000..d2d66e2 --- /dev/null +++ b/Chapter_11/UnsafeCode/UnsafeCode.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnsafeCode", "UnsafeCode\UnsafeCode.csproj", "{91204F96-4BFD-4BA0-9DBC-8D092639D7EF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {91204F96-4BFD-4BA0-9DBC-8D092639D7EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {91204F96-4BFD-4BA0-9DBC-8D092639D7EF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {91204F96-4BFD-4BA0-9DBC-8D092639D7EF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {91204F96-4BFD-4BA0-9DBC-8D092639D7EF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_11/UnsafeCode/UnsafeCode/App.config b/Chapter_11/UnsafeCode/UnsafeCode/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_11/UnsafeCode/UnsafeCode/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_11/UnsafeCode/UnsafeCode/Program.cs b/Chapter_11/UnsafeCode/UnsafeCode/Program.cs new file mode 100644 index 0000000..9826be1 --- /dev/null +++ b/Chapter_11/UnsafeCode/UnsafeCode/Program.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace UnsafeCode +{ + #region Test Points + struct Point + { + public int x; + public int y; + + public override string ToString() => $"({x}, {y})"; + } + + class PointRef // <= Renamed and retyped. + { + public int x; + public int y; + public override string ToString() => $"({x}, {y})"; + } + #endregion + + class Program + { + static void Main( string[] args ) + { + Console.WriteLine("***** Calling method with unsafe code *****"); + + // Values for swap. + int i = 10, j = 20; + + // Swap values "safely." + Console.WriteLine("\n***** Safe swap *****"); + Console.WriteLine("Values before safe swap: i = {0}, j = {1}", i, j); + SafeSwap(ref i, ref j); + Console.WriteLine("Values after safe swap: i = {0}, j = {1}", i, j); + + // Swap values "unsafely." + Console.WriteLine("\n***** Unsafe swap *****"); + Console.WriteLine("Values before unsafe swap: i = {0}, j = {1}", i, j); + + unsafe { UnsafeSwap(&i, &j); } + + Console.WriteLine("Values after unsafe swap: i = {0}, j = {1}", i, j); + + UsePointerToPoint(); + PrintValueAndAddress(); + UseAndPinPoint(); + UseSizeOfOperator(); + + Console.ReadLine(); + } + + #region Unsafe methods... + static unsafe void UsePointerToPoint() + { + // Access members via pointer. + Point point; + Point* p = &point; + p->x = 100; + p->y = 200; + Console.WriteLine(p->ToString()); + + // Access members via pointer indirection. + Point point2; + Point* p2 = &point2; + (*p2).x = 100; + (*p2).y = 200; + Console.WriteLine((*p2).ToString()); + } + + static unsafe void UnsafeStackAlloc() + { + char* p = stackalloc char[256]; + for (int k = 0; k < 256; k++) + p[k] = (char)k; + } + + static unsafe void SquareIntPointer( int* myIntPointer ) + { + // Square the value just for a test. + *myIntPointer *= *myIntPointer; + } + + static unsafe void PrintValueAndAddress() + { + int myInt; + + // Define an int pointer, and + // assign it the address of myInt. + int* ptrToMyInt = &myInt; + + // Assign value of myInt using pointer indirection. + *ptrToMyInt = 123; + + // Print some stats. + Console.WriteLine("Value of myInt {0}", myInt); + Console.WriteLine("Address of myInt {0:X}", (int)&ptrToMyInt); + } + + public static unsafe void UnsafeSwap( int* i, int* j ) + { + int temp = *i; + *i = *j; + *j = temp; + } + + public static unsafe void UseAndPinPoint() + { + PointRef pt = new PointRef + { + x = 5, + y = 6 + }; + + // pin pt in place so it will not + // be moved or GC-ed. + fixed (int* p = &pt.x) + { + // Use int* variable here! + } + + // pt is now unpinned, and ready to be GC-ed once + // the method completes. + Console.WriteLine("Point is: {0}", pt); + } + + static unsafe void UseSizeOfOperator() + { + Console.WriteLine("The size of short is {0}.", sizeof(short)); + Console.WriteLine("The size of int is {0}.", sizeof(int)); + Console.WriteLine("The size of long is {0}.", sizeof(long)); + Console.WriteLine("The size of Point is {0}.", sizeof(Point)); + } + + #endregion + + public static void SafeSwap( ref int i, ref int j ) + { + int temp = i; + i = j; + j = temp; + } + } +} diff --git a/Chapter_11/UnsafeCode/UnsafeCode/Properties/AssemblyInfo.cs b/Chapter_11/UnsafeCode/UnsafeCode/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..708671f --- /dev/null +++ b/Chapter_11/UnsafeCode/UnsafeCode/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("UnsafeCode")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("UnsafeCode")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("91204f96-4bfd-4ba0-9dbc-8d092639d7ef")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_11/UnsafeCode/UnsafeCode/UnsafeCode.csproj b/Chapter_11/UnsafeCode/UnsafeCode/UnsafeCode.csproj new file mode 100644 index 0000000..b109808 --- /dev/null +++ b/Chapter_11/UnsafeCode/UnsafeCode/UnsafeCode.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {91204F96-4BFD-4BA0-9DBC-8D092639D7EF} + Exe + UnsafeCode + UnsafeCode + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions.sln b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions.sln new file mode 100644 index 0000000..60b6fcc --- /dev/null +++ b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FunWithLinqExpressions", "FunWithLinqExpressions\FunWithLinqExpressions.csproj", "{511D97D7-14E3-4ED9-8BEB-C715E0D43CFF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {511D97D7-14E3-4ED9-8BEB-C715E0D43CFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {511D97D7-14E3-4ED9-8BEB-C715E0D43CFF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {511D97D7-14E3-4ED9-8BEB-C715E0D43CFF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {511D97D7-14E3-4ED9-8BEB-C715E0D43CFF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/App.config b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/FunWithLinqExpressions.csproj b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/FunWithLinqExpressions.csproj new file mode 100644 index 0000000..2967641 --- /dev/null +++ b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/FunWithLinqExpressions.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {511D97D7-14E3-4ED9-8BEB-C715E0D43CFF} + Exe + FunWithLinqExpressions + FunWithLinqExpressions + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/Program.cs b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/Program.cs new file mode 100644 index 0000000..4f1763a --- /dev/null +++ b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/Program.cs @@ -0,0 +1,250 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FunWithLinqExpressions +{ + #region ProdoctInfo class + class ProductInfo + { + public string Name { get; set; } = ""; + public string Description { get; set; }= ""; + public int NumberInStock { get; set; } + + public override string ToString() => $"Name={Name}, Description={Description}, Number in Stock={NumberInStock}"; + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Query Expressions *****\n"); + + #region Fill array of data + // This array will be the basis of our testing... + ProductInfo[] itemsInStock = new[] { + new ProductInfo{ Name = "Mac's Coffee", + Description = "Coffee with TEETH", + NumberInStock = 24}, + new ProductInfo{ Name = "Milk Maid Milk", + Description = "Milk cow's love", + NumberInStock = 100}, + new ProductInfo{ Name = "Pure Silk Tofu", + Description = "Bland as Possible", + NumberInStock = 120}, + new ProductInfo{ Name = "Cruchy Pops", + Description = "Cheezy, peppery goodness", + NumberInStock = 2}, + new ProductInfo{ Name = "RipOff Water", + Description = "From the tap to your wallet", + NumberInStock = 100}, + new ProductInfo{ Name = "Classic Valpo Pizza", + Description = "Everyone loves pizza!", + NumberInStock = 73} + }; + #endregion + + // We will call various methods here! + ListProductNames(itemsInStock); + Console.WriteLine(); + + GetOverstock(itemsInStock); + Console.WriteLine(); + + GetNamesAndDescriptions(itemsInStock); + Console.WriteLine(); + + GetCountFromQuery(); + Console.WriteLine(); + + DisplayConcat(); + Console.WriteLine(); + + DisplayDiff(); + Console.WriteLine(); + + DisplayIntersection(); + Console.WriteLine(); + + DisplayUnion(); + Console.WriteLine(); + + DisplayConcatNoDups(); + Console.WriteLine(); + + AggregateOps(); + Console.WriteLine(); + + Console.ReadLine(); + } + + #region Linq queries + static void SelectEverything(ProductInfo[] products) + { + // Get everything! + Console.WriteLine("All product details:"); + var allProducts = from p in products select p; + + foreach (var prod in allProducts) + { + Console.WriteLine(prod.ToString()); + } + } + + static void ListProductNames(ProductInfo[] products) + { + // Now get only the names of the products. + Console.WriteLine("Only product names:"); + var names = from p in products select p.Name; + + foreach (var n in names) + { + Console.WriteLine("Name: {0}", n); + } + } + + static void GetOverstock(ProductInfo[] products) + { + Console.WriteLine("The overstock items!"); + + // Get only the items where we have more than + // 25 in stock. + var overstock = from p in products where p.NumberInStock > 25 select p; + + foreach (ProductInfo c in overstock) + { + Console.WriteLine(c.ToString()); + } + } + + static void GetNamesAndDescriptions(ProductInfo[] products) + { + Console.WriteLine("Names and Descriptions:"); + var nameDesc = from p in products select new { p.Name, p.Description }; + + foreach (var item in nameDesc) + { + // Could also use Name and Description properties directly. + Console.WriteLine(item.ToString()); + } + } + + static void GetCountFromQuery() + { + string[] currentVideoGames = {"Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2"}; + + // Get count from the query. + int numb = (from g in currentVideoGames where g.Length > 6 select g).Count(); + + // Print out the number of items. + Console.WriteLine("{0} items honor the LINQ query.", numb); + } + + static void ReverseEverything(ProductInfo[] products) + { + Console.WriteLine("Product in reverse:"); + var allProducts = from p in products select p; + foreach (var prod in allProducts.Reverse()) + { + Console.WriteLine(prod.ToString()); + } + } + + static void AlphabetizeProductNames(ProductInfo[] products) + { + // Get names of products, alphabetized. + var subset = from p in products orderby p.Name select p; + + Console.WriteLine("Ordered by Name:"); + foreach (var p in subset) + { + Console.WriteLine(p.ToString()); + } + } + + static void DisplayDiff() + { + List myCars = new List { "Yugo", "Aztec", "BMW" }; + List yourCars = new List { "BMW", "Saab", "Aztec" }; + + var carDiff = (from c in myCars select c) + .Except(from c2 in yourCars select c2); + + Console.WriteLine("Here is what you don't have, but I do:"); + foreach (string s in carDiff) + Console.WriteLine(s); // Prints Yugo. + } + + static void DisplayIntersection() + { + List myCars = new List { "Yugo", "Aztec", "BMW" }; + List yourCars = new List { "BMW", "Saab", "Aztec" }; + + // Get the common members. + var carIntersect = (from c in myCars select c).Intersect(from c2 in yourCars select c2); + + Console.WriteLine("Here is what we have in common:"); + foreach (string s in carIntersect) + Console.WriteLine(s); // Prints Aztec and BMW. + } + + static void DisplayUnion() + { + List myCars = new List { "Yugo", "Aztec", "BMW" }; + List yourCars = new List { "BMW", "Saab", "Aztec" }; + + // Get the union of these containers. + var carUnion = (from c in myCars select c).Union(from c2 in yourCars select c2); + + Console.WriteLine("Here is everything:"); + foreach (string s in carUnion) + Console.WriteLine(s); // Prints all common members. + } + + static void DisplayConcat() + { + List myCars = new List { "Yugo", "Aztec", "BMW" }; + List yourCars = new List { "BMW", "Saab", "Aztec" }; + + var carConcat = (from c in myCars select c).Concat(from c2 in yourCars select c2); + + // Prints: + // Yugo Aztec BMW BMW Saab Aztec. + foreach (string s in carConcat) + Console.WriteLine(s); + } + + static void DisplayConcatNoDups() + { + List myCars = new List { "Yugo", "Aztec", "BMW" }; + List yourCars = new List { "BMW", "Saab", "Aztec" }; + + var carConcat = (from c in myCars select c).Concat(from c2 in yourCars select c2); + + // Prints: + // Yugo Aztec BMW Saab Aztec. + foreach (string s in carConcat.Distinct()) + Console.WriteLine(s); + } + + + static void AggregateOps() + { + double[] winterTemps = { 2.0, -21.3, 8, -4, 0, 8.2 }; + + // Various aggregation examples. + Console.WriteLine("Max temp: {0}",(from t in winterTemps select t).Max()); + + Console.WriteLine("Min temp: {0}",(from t in winterTemps select t).Min()); + + Console.WriteLine("Avarage temp: {0}",(from t in winterTemps select t).Average()); + + Console.WriteLine("Sum of all temps: {0}",(from t in winterTemps select t).Sum()); + } + #endregion + } +} diff --git a/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/Properties/AssemblyInfo.cs b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bcfebd5 --- /dev/null +++ b/Chapter_12/FunWithLinqExpressions/FunWithLinqExpressions/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("FunWithLinqExpressions")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FunWithLinqExpressions")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("511d97d7-14e3-4ed9-8beb-c715e0d43cff")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_12/LinqOverArray/LinqOverArray.sln b/Chapter_12/LinqOverArray/LinqOverArray.sln new file mode 100644 index 0000000..357806e --- /dev/null +++ b/Chapter_12/LinqOverArray/LinqOverArray.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqOverArray", "LinqOverArray\LinqOverArray.csproj", "{FEFA3458-5DBA-4A7D-9535-A3F4E282CCE9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FEFA3458-5DBA-4A7D-9535-A3F4E282CCE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FEFA3458-5DBA-4A7D-9535-A3F4E282CCE9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FEFA3458-5DBA-4A7D-9535-A3F4E282CCE9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FEFA3458-5DBA-4A7D-9535-A3F4E282CCE9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_12/LinqOverArray/LinqOverArray/App.config b/Chapter_12/LinqOverArray/LinqOverArray/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_12/LinqOverArray/LinqOverArray/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_12/LinqOverArray/LinqOverArray/LinqOverArray.csproj b/Chapter_12/LinqOverArray/LinqOverArray/LinqOverArray.csproj new file mode 100644 index 0000000..def9a98 --- /dev/null +++ b/Chapter_12/LinqOverArray/LinqOverArray/LinqOverArray.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {FEFA3458-5DBA-4A7D-9535-A3F4E282CCE9} + Exe + LinqOverArray + LinqOverArray + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_12/LinqOverArray/LinqOverArray/Program.cs b/Chapter_12/LinqOverArray/LinqOverArray/Program.cs new file mode 100644 index 0000000..6d47c61 --- /dev/null +++ b/Chapter_12/LinqOverArray/LinqOverArray/Program.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LinqOverArray +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with LINQ to Objects *****\n"); + QueryOverStrings(); + Console.WriteLine(); + QueryOverStringsWithExtensionMethods(); + Console.WriteLine(); + + QueryOverInts(); + Console.WriteLine(); + + Console.ReadLine(); + } + + #region Linq over string array + + static void QueryOverStrings() + { + // Assume we have an array of strings. + string[] currentVideoGames = + { + "Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2" + }; + + // Build a query expression to find the items in the array + // that have an embedded space. + IEnumerable subset = from g in currentVideoGames + where g.Contains(" ") + orderby g + select g; + + ReflectOverQueryResults(subset); + + // Print out the results. + foreach (string s in subset) + Console.WriteLine("Item: {0}", s); + ReflectOverQueryResults(subset); + + } + + static void QueryOverStringsWithExtensionMethods() + { + // Assume we have an array of strings. + string[] currentVideoGames = + { + "Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2" + }; + + // Build a query expression to find the items in the array + // that have an embedded space. + IEnumerable subset = currentVideoGames.Where(g => g.Contains(" ")).OrderBy(g => g).Select(g => g); + ReflectOverQueryResults(subset,"Extension Methods"); + + // Print out the results. + foreach (string s in subset) + Console.WriteLine("Item: {0}", s); + } + + static void QueryOverStringsLongHand() + { + // Assume we have an array of strings. + string[] currentVideoGames = + { + "Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2" + }; + + string[] gamesWithSpaces = new string[5]; + + for (int i = 0; i < currentVideoGames.Length; i++) + { + if (currentVideoGames[i].Contains(" ")) + gamesWithSpaces[i] = currentVideoGames[i]; + } + + // Now sort them. + Array.Sort(gamesWithSpaces); + + // Print out the results. + foreach (string s in gamesWithSpaces) + { + if (s != null) + Console.WriteLine("Item: {0}", s); + } + Console.WriteLine(); + } + + #endregion + + #region Linq over int array + + static void QueryOverInts() + { + int[] numbers = {10, 20, 30, 40, 1, 2, 3, 8}; + + // Get numbers less than ten. + var subset = from i in numbers where i < 10 select i; + + // LINQ statement evaluated here! + foreach (var i in subset) + Console.WriteLine("{0} < 10", i); + Console.WriteLine(); + // Change some data in the array. + numbers[0] = 4; + + // Evaluated again! + foreach (var j in subset) + Console.WriteLine("{0} < 10", j); + + Console.WriteLine(); + ReflectOverQueryResults(subset); + } + + static void ImmediateExecution() + { + int[] numbers = {10, 20, 30, 40, 1, 2, 3, 8}; + + // Get data RIGHT NOW as int[]. + int[] subsetAsIntArray = (from i in numbers where i < 10 select i).ToArray(); + + // Get data RIGHT NOW as List. + List subsetAsListOfInts = (from i in numbers where i < 10 select i).ToList(); + } + + #endregion + + static void ReflectOverQueryResults(object resultSet, string queryType = "Query Expressions") + { + Console.WriteLine($"***** Info about your query using {queryType} *****"); + Console.WriteLine("resultSet is of type: {0}", resultSet.GetType().Name); + Console.WriteLine("resultSet location: {0}", resultSet.GetType().Assembly.GetName().Name); + } + } +} \ No newline at end of file diff --git a/Chapter_12/LinqOverArray/LinqOverArray/Properties/AssemblyInfo.cs b/Chapter_12/LinqOverArray/LinqOverArray/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6ebbf99 --- /dev/null +++ b/Chapter_12/LinqOverArray/LinqOverArray/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LinqOverArray")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LinqOverArray")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("fefa3458-5dba-4a7d-9535-a3f4e282cce9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_12/LinqOverCollections/LinqOverCollections.sln b/Chapter_12/LinqOverCollections/LinqOverCollections.sln new file mode 100644 index 0000000..16ca776 --- /dev/null +++ b/Chapter_12/LinqOverCollections/LinqOverCollections.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqOverCollections", "LinqOverCollections\LinqOverCollections.csproj", "{1D907E56-7425-4F2D-9600-1F4B986B0CB6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1D907E56-7425-4F2D-9600-1F4B986B0CB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1D907E56-7425-4F2D-9600-1F4B986B0CB6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1D907E56-7425-4F2D-9600-1F4B986B0CB6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1D907E56-7425-4F2D-9600-1F4B986B0CB6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_12/LinqOverCollections/LinqOverCollections/App.config b/Chapter_12/LinqOverCollections/LinqOverCollections/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_12/LinqOverCollections/LinqOverCollections/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_12/LinqOverCollections/LinqOverCollections/LinqOverCollections.csproj b/Chapter_12/LinqOverCollections/LinqOverCollections/LinqOverCollections.csproj new file mode 100644 index 0000000..1d57a1a --- /dev/null +++ b/Chapter_12/LinqOverCollections/LinqOverCollections/LinqOverCollections.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {1D907E56-7425-4F2D-9600-1F4B986B0CB6} + Exe + LinqOverCollections + LinqOverCollections + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_12/LinqOverCollections/LinqOverCollections/Program.cs b/Chapter_12/LinqOverCollections/LinqOverCollections/Program.cs new file mode 100644 index 0000000..72c1d27 --- /dev/null +++ b/Chapter_12/LinqOverCollections/LinqOverCollections/Program.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LinqOverCollections +{ + #region Simple car class + class Car + { + public string PetName { get; set; } = ""; + public string Color { get; set; } = ""; + public int Speed { get; set; } + public string Make { get; set; } = ""; + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** LINQ over Generic Collections *****\n"); + + // Make a List<> of Car objects. + List myCars = new List() { + new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"}, + new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"}, + new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"}, + new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"}, + new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"} + }; + + GetFastCars(myCars); + Console.WriteLine(); + + GetFastBMWs(myCars); + Console.WriteLine(); + + LINQOverArrayList(); + Console.WriteLine(); + + OfTypeAsFilter(); + Console.WriteLine(); + + Console.ReadLine(); + } + + #region Linq queries + static void GetFastCars(List myCars) + { + // Find all Car objects in the List<>, where the Speed is + // greater than 55. + var fastCars = from c in myCars where c.Speed > 55 select c; + + foreach (var car in fastCars) + { + Console.WriteLine("{0} is going too fast!", car.PetName); + } + } + + static void GetFastBMWs(List myCars) + { + // Find the fast BMWs! + var fastCars = from c in myCars where c.Speed > 90 && c.Make == "BMW" select c; + foreach (var car in fastCars) + { + Console.WriteLine("{0} is going too fast!", car.PetName); + } + } + + static void LINQOverArrayList() + { + Console.WriteLine("***** LINQ over ArrayList *****"); + + // Here is a nongeneric collection of cars. + ArrayList myCars = new ArrayList() { + new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"}, + new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"}, + new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"}, + new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"}, + new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"} + }; + + // Transform ArrayList into an IEnumerable-compatible type. + var myCarsEnum = myCars.OfType(); + + // Create a query expression targeting the compatible type. + var fastCars = from c in myCarsEnum where c.Speed > 55 select c; + + foreach (var car in fastCars) + { + Console.WriteLine("{0} is going too fast!", car.PetName); + } + } + + static void OfTypeAsFilter() + { + // Extract the ints from the ArrayList. + ArrayList myStuff = new ArrayList(); + myStuff.AddRange(new object[] { 10, 400, 8, false, new Car(), "string data" }); + var myInts = myStuff.OfType(); + + // Prints out 10, 400, and 8. + foreach (int i in myInts) + { + Console.WriteLine("Int value: {0}", i); + } + } + #endregion + } +} diff --git a/Chapter_12/LinqOverCollections/LinqOverCollections/Properties/AssemblyInfo.cs b/Chapter_12/LinqOverCollections/LinqOverCollections/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..276f785 --- /dev/null +++ b/Chapter_12/LinqOverCollections/LinqOverCollections/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LinqOverCollections")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LinqOverCollections")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1d907e56-7425-4f2d-9600-1f4b986b0cb6")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_12/LinqRetValues/LinqRetValues.sln b/Chapter_12/LinqRetValues/LinqRetValues.sln new file mode 100644 index 0000000..ef5d85e --- /dev/null +++ b/Chapter_12/LinqRetValues/LinqRetValues.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqRetValues", "LinqRetValues\LinqRetValues.csproj", "{63075722-B84F-4C33-BF88-C89E1AECDAC5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {63075722-B84F-4C33-BF88-C89E1AECDAC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {63075722-B84F-4C33-BF88-C89E1AECDAC5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {63075722-B84F-4C33-BF88-C89E1AECDAC5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {63075722-B84F-4C33-BF88-C89E1AECDAC5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_12/LinqRetValues/LinqRetValues/App.config b/Chapter_12/LinqRetValues/LinqRetValues/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_12/LinqRetValues/LinqRetValues/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_12/LinqRetValues/LinqRetValues/LinqRetValues.csproj b/Chapter_12/LinqRetValues/LinqRetValues/LinqRetValues.csproj new file mode 100644 index 0000000..69eadcf --- /dev/null +++ b/Chapter_12/LinqRetValues/LinqRetValues/LinqRetValues.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {63075722-B84F-4C33-BF88-C89E1AECDAC5} + Exe + LinqRetValues + LinqRetValues + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_12/LinqRetValues/LinqRetValues/Program.cs b/Chapter_12/LinqRetValues/LinqRetValues/Program.cs new file mode 100644 index 0000000..7885e2d --- /dev/null +++ b/Chapter_12/LinqRetValues/LinqRetValues/Program.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LinqRetValues +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** LINQ Return Values *****\n"); + IEnumerable subset = GetStringSubset(); + + foreach (string item in subset) + { + Console.WriteLine(item); + } + + Console.WriteLine(); + + foreach (string item in GetStringSubsetAsArray()) + { + Console.WriteLine(item); + } + + Console.ReadLine(); + } + + #region Linq query methods + static IEnumerable GetStringSubset() + { + string[] colors = {"Light Red", "Green", "Yellow", "Dark Red", "Red", "Purple"}; + + // Note subset is an IEnumerable-compatible object. + IEnumerable theRedColors = from c in colors + where c.Contains("Red") + select c; + + return theRedColors; + } + + static string[] GetStringSubsetAsArray() + { + string[] colors = {"Light Red", "Green", "Yellow", "Dark Red", "Red", "Purple"}; + + var theRedColors = from c in colors + where c.Contains("Red") + select c; + + // Map results into an array. + return theRedColors.ToArray(); + } + #endregion + } +} diff --git a/Chapter_12/LinqRetValues/LinqRetValues/Properties/AssemblyInfo.cs b/Chapter_12/LinqRetValues/LinqRetValues/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4062363 --- /dev/null +++ b/Chapter_12/LinqRetValues/LinqRetValues/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LinqRetValues")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LinqRetValues")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("63075722-b84f-4c33-bf88-c89e1aecdac5")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable.sln b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable.sln new file mode 100644 index 0000000..e6e58df --- /dev/null +++ b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqUsingEnumerable", "LinqUsingEnumerable\LinqUsingEnumerable.csproj", "{B2565957-DD4F-40A2-8584-EC97C7CCF092}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B2565957-DD4F-40A2-8584-EC97C7CCF092}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B2565957-DD4F-40A2-8584-EC97C7CCF092}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B2565957-DD4F-40A2-8584-EC97C7CCF092}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B2565957-DD4F-40A2-8584-EC97C7CCF092}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/App.config b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/LinqUsingEnumerable.csproj b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/LinqUsingEnumerable.csproj new file mode 100644 index 0000000..ec262fb --- /dev/null +++ b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/LinqUsingEnumerable.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {B2565957-DD4F-40A2-8584-EC97C7CCF092} + Exe + LinqUsingEnumerable + LinqUsingEnumerable + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/Program.cs b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/Program.cs new file mode 100644 index 0000000..a06fb02 --- /dev/null +++ b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/Program.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LinqUsingEnumerable +{ + class Program + { + static void Main(string[] args) + { + QueryStringWithOperators(); + Console.WriteLine(); + + QueryStringsWithEnumerableAndLambdas(); + Console.WriteLine(); + + QueryStringsWithAnonymousMethods(); + Console.WriteLine(); + + VeryComplexQueryExpression.QueryStringsWithRawDelegates(); + Console.WriteLine(); + + Console.ReadLine(); + } + + #region Use Linq operators + static void QueryStringWithOperators() + { + Console.WriteLine("***** Using Query Operators *****"); + + string[] currentVideoGames = {"Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2"}; + + var subset = from game in currentVideoGames + where game.Contains(" ") + orderby game + select game; + + foreach (string s in subset) + Console.WriteLine("Item: {0}", s); + } + #endregion + + #region With enumerable and lambdas + static void QueryStringsWithEnumerableAndLambdas() + { + Console.WriteLine("***** Using Enumerable / Lambda Expressions *****"); + + string[] currentVideoGames = {"Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2"}; + + // Build a query expression using extension methods + // granted to the Array via the Enumerable type. + var subset = currentVideoGames.Where(game => game.Contains(" ")) + .OrderBy(game => game).Select(game => game); + + // Print out the results. + foreach (var game in subset) + Console.WriteLine("Item: {0}", game); + Console.WriteLine(); + + } + static void QueryStringsWithEnumerableAndLambdas2() + { + Console.WriteLine("***** Using Enumerable / Lambda Expressions *****"); + + string[] currentVideoGames = {"Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2"}; + + // Break it down! + var gamesWithSpaces = currentVideoGames.Where(game => game.Contains(" ")); + var orderedGames = gamesWithSpaces.OrderBy(game => game); + var subset = orderedGames.Select(game => game); + + foreach (var game in subset) + Console.WriteLine("Item: {0}", game); + Console.WriteLine(); + } + #endregion + + #region With anonymous methods + static void QueryStringsWithAnonymousMethods() + { + Console.WriteLine("***** Using Anonymous Methods *****"); + + string[] currentVideoGames = {"Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2"}; + + // Build the necessary Func<> delegates using anonymous methods. + Func searchFilter = + delegate (string game) { return game.Contains(" "); }; + Func itemToProcess = delegate (string s) { return s; }; + + // Pass the delegates into the methods of Enumerable. + var subset = currentVideoGames.Where(searchFilter) + .OrderBy(itemToProcess).Select(itemToProcess); + + // Print out the results. + foreach (var game in subset) + Console.WriteLine("Item: {0}", game); + Console.WriteLine(); + } + #endregion + } +} diff --git a/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/Properties/AssemblyInfo.cs b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..5029103 --- /dev/null +++ b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LinqUsingEnumerable")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LinqUsingEnumerable")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b2565957-dd4f-40a2-8584-ec97c7ccf092")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/VeryComplexQueryExpression.cs b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/VeryComplexQueryExpression.cs new file mode 100644 index 0000000..39d4ab4 --- /dev/null +++ b/Chapter_12/LinqUsingEnumerable/LinqUsingEnumerable/VeryComplexQueryExpression.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LinqUsingEnumerable +{ + class VeryComplexQueryExpression + { + public static void QueryStringsWithRawDelegates() + { + Console.WriteLine("***** Using Raw Delegates *****"); + + string[] currentVideoGames = {"Morrowind", "Uncharted 2", + "Fallout 3", "Daxter", "System Shock 2"}; + + // Build the necessary Func<> delegates. + Func searchFilter = new Func(Filter); + Func itemToProcess = new Func(ProcessItem); + + // Pass the delegates into the methods of Enumerable. + var subset = currentVideoGames + .Where(searchFilter).OrderBy(itemToProcess).Select(itemToProcess); + + // Print out the results. + foreach (var game in subset) + Console.WriteLine("Item: {0}", game); + Console.WriteLine(); + } + + // Delegate targets. + public static bool Filter(string game) { return game.Contains(" "); } + public static string ProcessItem(string game) { return game; } + } + +} diff --git a/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass.sln b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass.sln new file mode 100644 index 0000000..5ee2488 --- /dev/null +++ b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FInalizableDisposableClass", "FInalizableDisposableClass\FInalizableDisposableClass.csproj", "{4E3EF778-EA5F-43D3-A072-4596416D3394}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4E3EF778-EA5F-43D3-A072-4596416D3394}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4E3EF778-EA5F-43D3-A072-4596416D3394}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4E3EF778-EA5F-43D3-A072-4596416D3394}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4E3EF778-EA5F-43D3-A072-4596416D3394}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/App.config b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/FInalizableDisposableClass.csproj b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/FInalizableDisposableClass.csproj new file mode 100644 index 0000000..d61890e --- /dev/null +++ b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/FInalizableDisposableClass.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {4E3EF778-EA5F-43D3-A072-4596416D3394} + Exe + FInalizableDisposableClass + FInalizableDisposableClass + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/Program.cs b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/Program.cs new file mode 100644 index 0000000..5d94bfa --- /dev/null +++ b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/Program.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FinalizableDisposableClass +{ + #region Disposable and finalizable object + class MyResourceWrapper : IDisposable + { + // Used to determine if Dispose() + // has already been called. + private bool disposed = false; + + public void Dispose() + { + // Call our helper method. + // Specifying "true" signifies that + // the object user triggered the cleanup. + CleanUp(true); + + // Now suppress finalization. + GC.SuppressFinalize(this); + } + + private void CleanUp(bool disposing) + { + // Be sure we have not already been disposed! + if (!this.disposed) + { + // If disposing equals true, dispose all + // managed resources. + if (disposing) + { + // Dispose managed resources. + } + // Clean up unmanaged resources here. + } + disposed = true; + } + + ~MyResourceWrapper() + { + Console.Beep(); + // Call our helper method. + // Specifying "false" signifies that + // the GC triggered the cleanup. + CleanUp(false); + } + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Dispose() / Destructor Combo Platter *****"); + + // Call Dispose() manually, this will not call the finalizer. + MyResourceWrapper rw = new MyResourceWrapper(); + rw.Dispose(); + + // Don't call Dispose(), this will trigger the finalizer + // and cause a beep. + MyResourceWrapper rw2 = new MyResourceWrapper(); + + Console.ReadLine(); + } + } +} diff --git a/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/Properties/AssemblyInfo.cs b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..11579f9 --- /dev/null +++ b/Chapter_13/FInalizableDisposableClass/FInalizableDisposableClass/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("FInalizableDisposableClass")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FInalizableDisposableClass")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4e3ef778-ea5f-43d3-a072-4596416d3394")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation.sln b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation.sln new file mode 100644 index 0000000..3787a16 --- /dev/null +++ b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LazyObjectInstantiation", "LazyObjectInstantiation\LazyObjectInstantiation.csproj", "{B02E360C-7EC2-43CA-BE78-B04BF007BD55}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B02E360C-7EC2-43CA-BE78-B04BF007BD55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B02E360C-7EC2-43CA-BE78-B04BF007BD55}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B02E360C-7EC2-43CA-BE78-B04BF007BD55}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B02E360C-7EC2-43CA-BE78-B04BF007BD55}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/App.config b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/LazyObjectInstantiation.csproj b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/LazyObjectInstantiation.csproj new file mode 100644 index 0000000..ba58b2d --- /dev/null +++ b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/LazyObjectInstantiation.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {B02E360C-7EC2-43CA-BE78-B04BF007BD55} + Exe + LazyObjectInstantiation + LazyObjectInstantiation + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/Program.cs b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/Program.cs new file mode 100644 index 0000000..bae2a7d --- /dev/null +++ b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/Program.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LazyObjectInstantiation +{ + #region Classes for illustration of lazy instantiation + // Represents a single song. + class Song + { + public string Artist { get; set; } + public string TrackName { get; set; } + public double TrackLength { get; set; } + } + + // Represents all songs on a player. + class AllTracks + { + // Our media player can have a maximum + // of 10,000 songs. + private Song[] allSongs = new Song[10000]; + + public AllTracks() + { + // Assume we fill up the array + // of Song objects here. + Console.WriteLine("Filling up the songs!"); + } + } + + // The MediaPlayer has-a AllTracks object. + class MediaPlayer + { + // Assume these methods do something useful. + public void Play() { /* Play a song */ } + public void Pause() { /* Pause the song */ } + public void Stop() { /* Stop playback */ } + + // Use a lambda expression to add additional code + // when the AllTracks object is made. + private Lazy allSongs = new Lazy(() => + { + Console.WriteLine("Creating AllTracks object!"); + return new AllTracks(); + } + ); + + public AllTracks GetAllTracks() + { + // Return all of the songs. + return allSongs.Value; + } + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Lazy Instantiation *****\n"); + + // No allocation of AllTracks object here! + MediaPlayer myPlayer = new MediaPlayer(); + myPlayer.Play(); + + // Allocation of AllTracks happens when you call GetAllTracks(). + MediaPlayer yourPlayer = new MediaPlayer(); + AllTracks yourMusic = yourPlayer.GetAllTracks(); + + Console.ReadLine(); + } + } +} diff --git a/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/Properties/AssemblyInfo.cs b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b446422 --- /dev/null +++ b/Chapter_13/LazyObjectInstantiation/LazyObjectInstantiation/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LazyObjectInstantiation")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LazyObjectInstantiation")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b02e360c-7ec2-43ca-be78-b04bf007bd55")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_13/SimpleDispose/SimpleDispose.sln b/Chapter_13/SimpleDispose/SimpleDispose.sln new file mode 100644 index 0000000..2920c1b --- /dev/null +++ b/Chapter_13/SimpleDispose/SimpleDispose.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleDispose", "SimpleDispose\SimpleDispose.csproj", "{D34DFCC0-1457-4933-9E14-E86E80732B5E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D34DFCC0-1457-4933-9E14-E86E80732B5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D34DFCC0-1457-4933-9E14-E86E80732B5E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D34DFCC0-1457-4933-9E14-E86E80732B5E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D34DFCC0-1457-4933-9E14-E86E80732B5E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_13/SimpleDispose/SimpleDispose/App.config b/Chapter_13/SimpleDispose/SimpleDispose/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_13/SimpleDispose/SimpleDispose/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_13/SimpleDispose/SimpleDispose/Program.cs b/Chapter_13/SimpleDispose/SimpleDispose/Program.cs new file mode 100644 index 0000000..5c644ca --- /dev/null +++ b/Chapter_13/SimpleDispose/SimpleDispose/Program.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SimpleDispose +{ + #region A disposable object + // Implementing IDisposable. + class MyResourceWrapper : IDisposable + { + // The object user should call this method + // when they finish with the object. + public void Dispose() + { + // Clean up unmanaged resources... + + // Dispose other contained disposable objects... + + // Just for a test. + Console.WriteLine("***** In Dispose! *****"); + } + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Dispose *****\n"); + + // Use a comma-delimited list to declare multiple objects to dispose. + using (MyResourceWrapper rw = new MyResourceWrapper(), + rw2 = new MyResourceWrapper()) + { + // Use rw and rw2 objects. + } + Console.ReadLine(); + } + } +} diff --git a/Chapter_13/SimpleDispose/SimpleDispose/Properties/AssemblyInfo.cs b/Chapter_13/SimpleDispose/SimpleDispose/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..afe9f9a --- /dev/null +++ b/Chapter_13/SimpleDispose/SimpleDispose/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleDispose")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleDispose")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("d34dfcc0-1457-4933-9e14-e86e80732b5e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_13/SimpleDispose/SimpleDispose/SimpleDispose.csproj b/Chapter_13/SimpleDispose/SimpleDispose/SimpleDispose.csproj new file mode 100644 index 0000000..8ca8e61 --- /dev/null +++ b/Chapter_13/SimpleDispose/SimpleDispose/SimpleDispose.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {D34DFCC0-1457-4933-9E14-E86E80732B5E} + Exe + SimpleDispose + SimpleDispose + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_13/SimpleFinalize/SimpleFinalize.sln b/Chapter_13/SimpleFinalize/SimpleFinalize.sln new file mode 100644 index 0000000..d06557c --- /dev/null +++ b/Chapter_13/SimpleFinalize/SimpleFinalize.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleFinalize", "SimpleFinalize\SimpleFinalize.csproj", "{3C9CA873-E403-4A43-8684-FCAE94400F99}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3C9CA873-E403-4A43-8684-FCAE94400F99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3C9CA873-E403-4A43-8684-FCAE94400F99}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3C9CA873-E403-4A43-8684-FCAE94400F99}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3C9CA873-E403-4A43-8684-FCAE94400F99}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_13/SimpleFinalize/SimpleFinalize/App.config b/Chapter_13/SimpleFinalize/SimpleFinalize/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_13/SimpleFinalize/SimpleFinalize/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_13/SimpleFinalize/SimpleFinalize/Program.cs b/Chapter_13/SimpleFinalize/SimpleFinalize/Program.cs new file mode 100644 index 0000000..e0ae33c --- /dev/null +++ b/Chapter_13/SimpleFinalize/SimpleFinalize/Program.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SimpleFinalize +{ + // Override System.Object.Finalize() via finalizer syntax. + class MyResourceWrapper + { + // Clean up unmanaged resources here. + // Beep when destroyed (testing purposes only!) + ~MyResourceWrapper() => Console.Beep(); + } + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Finalizers *****\n"); + Console.WriteLine("Hit the return key to shut down this app"); + Console.WriteLine("and force the GC to invoke Finalize()"); + Console.WriteLine("for finalizable objects created in this AppDomain."); + Console.ReadLine(); + MyResourceWrapper rw = new MyResourceWrapper(); + } + } +} \ No newline at end of file diff --git a/Chapter_13/SimpleFinalize/SimpleFinalize/Properties/AssemblyInfo.cs b/Chapter_13/SimpleFinalize/SimpleFinalize/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6a12810 --- /dev/null +++ b/Chapter_13/SimpleFinalize/SimpleFinalize/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleFinalize")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleFinalize")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3c9ca873-e403-4a43-8684-fcae94400f99")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_13/SimpleFinalize/SimpleFinalize/SimpleFinalize.csproj b/Chapter_13/SimpleFinalize/SimpleFinalize/SimpleFinalize.csproj new file mode 100644 index 0000000..8b55944 --- /dev/null +++ b/Chapter_13/SimpleFinalize/SimpleFinalize/SimpleFinalize.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {3C9CA873-E403-4A43-8684-FCAE94400F99} + Exe + SimpleFinalize + SimpleFinalize + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_13/SimpleGC/SimpleGC.sln b/Chapter_13/SimpleGC/SimpleGC.sln new file mode 100644 index 0000000..e76d9f0 --- /dev/null +++ b/Chapter_13/SimpleGC/SimpleGC.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleGC", "SimpleGC\SimpleGC.csproj", "{0A800018-D285-45FB-B534-8D53DDD9AED1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0A800018-D285-45FB-B534-8D53DDD9AED1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A800018-D285-45FB-B534-8D53DDD9AED1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A800018-D285-45FB-B534-8D53DDD9AED1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A800018-D285-45FB-B534-8D53DDD9AED1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_13/SimpleGC/SimpleGC/App.config b/Chapter_13/SimpleGC/SimpleGC/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_13/SimpleGC/SimpleGC/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_13/SimpleGC/SimpleGC/Car.cs b/Chapter_13/SimpleGC/SimpleGC/Car.cs new file mode 100644 index 0000000..a200404 --- /dev/null +++ b/Chapter_13/SimpleGC/SimpleGC/Car.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SimpleGC +{ + public class Car + { + public int CurrentSpeed { get; set; } + public string PetName { get; set; } + + public Car() { } + public Car(string name, int speed) + { + PetName = name; + CurrentSpeed = speed; + } + public override string ToString() => $"{PetName} is going {CurrentSpeed} MPH"; + } +} diff --git a/Chapter_13/SimpleGC/SimpleGC/Program.cs b/Chapter_13/SimpleGC/SimpleGC/Program.cs new file mode 100644 index 0000000..1398f42 --- /dev/null +++ b/Chapter_13/SimpleGC/SimpleGC/Program.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SimpleGC +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with System.GC *****"); + + // Print out estimated number of bytes on heap. + Console.WriteLine("Estimated bytes on heap: {0}", GC.GetTotalMemory(false)); + + // MaxGeneration is zero based. + Console.WriteLine("This OS has {0} object generations.\n", (GC.MaxGeneration + 1)); + Car refToMyCar = new Car("Zippy", 100); + Console.WriteLine(refToMyCar.ToString()); + + // Print out generation of refToMyCar. + Console.WriteLine("\nGeneration of refToMyCar is: {0}", GC.GetGeneration(refToMyCar)); + + // Make a ton of objects for testing purposes. + object[] tonsOfObjects = new object[50000]; + for (int i = 0; i < 50000; i++) + tonsOfObjects[i] = new object(); + + // Collect only gen 0 objects. + GC.Collect(0, GCCollectionMode.Forced); + GC.WaitForPendingFinalizers(); + + // Print out generation of refToMyCar. + Console.WriteLine("Generation of refToMyCar is: {0}", GC.GetGeneration(refToMyCar)); + + // See if tonsOfObjects[9000] is still alive. + if (tonsOfObjects[9000] != null) + { + Console.WriteLine("Generation of tonsOfObjects[9000] is: {0}", + GC.GetGeneration(tonsOfObjects[9000])); + } + else + Console.WriteLine("tonsOfObjects[9000] is no longer alive."); + + // Print out how many times a generation has been swept. + Console.WriteLine("\nGen 0 has been swept {0} times", GC.CollectionCount(0)); + Console.WriteLine("Gen 1 has been swept {0} times", GC.CollectionCount(1)); + Console.WriteLine("Gen 2 has been swept {0} times", GC.CollectionCount(2)); + Console.ReadLine(); + } + + static void MakeACar() + { + // If myCar is the only reference to the Car object, + // it *may* be destroyed when this method returns. + Car myCar = new Car(); + myCar = null; + } + + } +} diff --git a/Chapter_13/SimpleGC/SimpleGC/Properties/AssemblyInfo.cs b/Chapter_13/SimpleGC/SimpleGC/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..78d0f45 --- /dev/null +++ b/Chapter_13/SimpleGC/SimpleGC/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleGC")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleGC")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0a800018-d285-45fb-b534-8d53ddd9aed1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_13/SimpleGC/SimpleGC/SimpleGC.csproj b/Chapter_13/SimpleGC/SimpleGC/SimpleGC.csproj new file mode 100644 index 0000000..cf768ae --- /dev/null +++ b/Chapter_13/SimpleGC/SimpleGC/SimpleGC.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {0A800018-D285-45FB-B534-8D53DDD9AED1} + Exe + SimpleGC + SimpleGC + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/AppConfigReaderClient/AppConfigReaderClient.sln b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient.sln new file mode 100644 index 0000000..6d6ca97 --- /dev/null +++ b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AppConfigReaderClient", "AppConfigReaderClient\AppConfigReaderClient.csproj", "{F2306385-D9F8-4F35-8201-772A3FA1F010}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F2306385-D9F8-4F35-8201-772A3FA1F010}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F2306385-D9F8-4F35-8201-772A3FA1F010}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F2306385-D9F8-4F35-8201-772A3FA1F010}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F2306385-D9F8-4F35-8201-772A3FA1F010}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/App.config b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/App.config new file mode 100644 index 0000000..96fc0cd --- /dev/null +++ b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/App.config @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/AppConfigReaderClient.csproj b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/AppConfigReaderClient.csproj new file mode 100644 index 0000000..a21f629 --- /dev/null +++ b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/AppConfigReaderClient.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {F2306385-D9F8-4F35-8201-772A3FA1F010} + Exe + AppConfigReaderClient + AppConfigReaderClient + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/Program.cs b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/Program.cs new file mode 100644 index 0000000..5b8eefc --- /dev/null +++ b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/Program.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using System.Configuration; + +namespace AppConfigReaderApp +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Reading Data *****\n"); + + // Get our custom data from the *.config file. + AppSettingsReader ar = new AppSettingsReader(); + int numbOfTimes = (int)ar.GetValue("RepeatCount", typeof(int)); + string textColor = (string)ar.GetValue("TextColor", typeof(string)); + + Console.ForegroundColor = + (ConsoleColor)Enum.Parse(typeof(ConsoleColor), textColor); + + // Now print a message correctly. + for (int i = 0; i < numbOfTimes; i++) + Console.WriteLine("Howdy!"); + Console.ReadLine(); + } + } +} diff --git a/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/Properties/AssemblyInfo.cs b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..13a9bba --- /dev/null +++ b/Chapter_14/AppConfigReaderClient/AppConfigReaderClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AppConfigReaderClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AppConfigReaderClient")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f2306385-d9f8-4f35-8201-772a3fa1f010")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_14/CSharpCarClient/CSharpCarClient.sln b/Chapter_14/CSharpCarClient/CSharpCarClient.sln new file mode 100644 index 0000000..becd5d8 --- /dev/null +++ b/Chapter_14/CSharpCarClient/CSharpCarClient.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpCarClient", "CSharpCarClient\CSharpCarClient.csproj", "{55EC275E-1E40-4843-BF44-3011F65C26A2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {55EC275E-1E40-4843-BF44-3011F65C26A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55EC275E-1E40-4843-BF44-3011F65C26A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55EC275E-1E40-4843-BF44-3011F65C26A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55EC275E-1E40-4843-BF44-3011F65C26A2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_14/CSharpCarClient/CSharpCarClient/App.config b/Chapter_14/CSharpCarClient/CSharpCarClient/App.config new file mode 100644 index 0000000..2030049 --- /dev/null +++ b/Chapter_14/CSharpCarClient/CSharpCarClient/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/CSharpCarClient/CSharpCarClient/CSharpCarClient.csproj b/Chapter_14/CSharpCarClient/CSharpCarClient/CSharpCarClient.csproj new file mode 100644 index 0000000..6c39992 --- /dev/null +++ b/Chapter_14/CSharpCarClient/CSharpCarClient/CSharpCarClient.csproj @@ -0,0 +1,55 @@ + + + + + Debug + AnyCPU + {55EC275E-1E40-4843-BF44-3011F65C26A2} + Exe + CSharpCarClient + CSharpCarClient + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\CarLibrary\CarLibrary\bin\Debug\CarLibrary.dll + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/CSharpCarClient/CSharpCarClient/Program.cs b/Chapter_14/CSharpCarClient/CSharpCarClient/Program.cs new file mode 100644 index 0000000..c521cdd --- /dev/null +++ b/Chapter_14/CSharpCarClient/CSharpCarClient/Program.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// Don't forget to import the CarLibrary namespace! +using CarLibrary; + +namespace CSharpCarClient +{ + public class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** C# CarLibrary Client App *****"); + // Make a sports car. + SportsCar viper = new SportsCar("Viper", 240, 40); + viper.TurboBoost(); + + // Make a minivan. + MiniVan mv = new MiniVan(); + mv.TurboBoost(); + + Console.WriteLine("Done. Press any key to terminate"); + Console.ReadLine(); + } + } +} diff --git a/Chapter_14/CSharpCarClient/CSharpCarClient/Properties/AssemblyInfo.cs b/Chapter_14/CSharpCarClient/CSharpCarClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c8dc38d --- /dev/null +++ b/Chapter_14/CSharpCarClient/CSharpCarClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CSharpCarClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CSharpCarClient")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("55ec275e-1e40-4843-bf44-3011f65c26a2")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_14/CarLibrary/CarLibrary.sln b/Chapter_14/CarLibrary/CarLibrary.sln new file mode 100644 index 0000000..11330b8 --- /dev/null +++ b/Chapter_14/CarLibrary/CarLibrary.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarLibrary", "CarLibrary\CarLibrary.csproj", "{B3C031BE-18E3-4FB1-BB4F-88C8B42D1891}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B3C031BE-18E3-4FB1-BB4F-88C8B42D1891}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B3C031BE-18E3-4FB1-BB4F-88C8B42D1891}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B3C031BE-18E3-4FB1-BB4F-88C8B42D1891}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B3C031BE-18E3-4FB1-BB4F-88C8B42D1891}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_14/CarLibrary/CarLibrary/Car.cs b/Chapter_14/CarLibrary/CarLibrary/Car.cs new file mode 100644 index 0000000..e2b63c3 --- /dev/null +++ b/Chapter_14/CarLibrary/CarLibrary/Car.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace CarLibrary +{ + // Represents the state of the engine. + public enum EngineState + { engineAlive, engineDead } + + // Which type of music player does this car have? + public enum MusicMedia + { + musicCd, + musicTape, + musicRadio, + musicMp3 + } + + // The abstract base class in the hierarchy. + public abstract class Car + { + public string PetName { get; set; } + public int CurrentSpeed { get; set; } + public int MaxSpeed { get; set; } + + protected EngineState egnState = EngineState.engineAlive; + public EngineState EngineState => egnState; + public abstract void TurboBoost(); + + public Car() => MessageBox.Show("CarLibrary Version 2.0!"); + public Car(string name, int maxSp, int currSp) + { + MessageBox.Show("CarLibrary Version 2.0!"); + PetName = name; MaxSpeed = maxSp; CurrentSpeed = currSp; + } + + + public void TurnOnRadio(bool musicOn, MusicMedia mm) + => MessageBox.Show(musicOn ? $"Jamming {mm}" : "Quiet time..."); + + } +} + diff --git a/Chapter_14/CarLibrary/CarLibrary/CarLibrary.csproj b/Chapter_14/CarLibrary/CarLibrary/CarLibrary.csproj new file mode 100644 index 0000000..f7a6ec6 --- /dev/null +++ b/Chapter_14/CarLibrary/CarLibrary/CarLibrary.csproj @@ -0,0 +1,58 @@ + + + + + Debug + AnyCPU + {B3C031BE-18E3-4FB1-BB4F-88C8B42D1891} + Library + Properties + CarLibrary + CarLibrary + v4.7 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + + + myKeyPair.snk + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/CarLibrary/CarLibrary/DerivedCars.cs b/Chapter_14/CarLibrary/CarLibrary/DerivedCars.cs new file mode 100644 index 0000000..91807f4 --- /dev/null +++ b/Chapter_14/CarLibrary/CarLibrary/DerivedCars.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// Keep reading! This won't compile until you reference a .NET library. +using System.Windows.Forms; + +namespace CarLibrary +{ + public class SportsCar : Car + { + public SportsCar() { } + public SportsCar(string name, int maxSp, int currSp) + : base(name, maxSp, currSp) + { } + + public override void TurboBoost() + { + MessageBox.Show("Ramming speed!", "Faster is better..."); + } + } + + public class MiniVan : Car + { + public MiniVan() { } + public MiniVan(string name, int maxSp, int currSp) + : base(name, maxSp, currSp) + { } + + public override void TurboBoost() + { + // Minivans have poor turbo capabilities! + egnState = EngineState.engineDead; + MessageBox.Show("Eek!", "Your engine block exploded!"); + } + } +} diff --git a/Chapter_14/CarLibrary/CarLibrary/Properties/AssemblyInfo.cs b/Chapter_14/CarLibrary/CarLibrary/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8ce8a66 --- /dev/null +++ b/Chapter_14/CarLibrary/CarLibrary/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CarLibrary")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CarLibrary")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b3c031be-18e3-4fb1-bb4f-88c8b42d1891")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("2.0.0.0")] +[assembly: AssemblyFileVersion("2.0.0.0")] diff --git a/Chapter_14/CarLibrary/CarLibrary/myKeyPair.snk b/Chapter_14/CarLibrary/CarLibrary/myKeyPair.snk new file mode 100644 index 0000000..f91d0c0 Binary files /dev/null and b/Chapter_14/CarLibrary/CarLibrary/myKeyPair.snk differ diff --git a/Chapter_14/CodeBaseClient/CodeBaseClient.sln b/Chapter_14/CodeBaseClient/CodeBaseClient.sln new file mode 100644 index 0000000..2aded6f --- /dev/null +++ b/Chapter_14/CodeBaseClient/CodeBaseClient.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeBaseClient", "CodeBaseClient\CodeBaseClient.csproj", "{A6A1DD55-8F21-49B1-906E-1EC25CCE643B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A6A1DD55-8F21-49B1-906E-1EC25CCE643B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A6A1DD55-8F21-49B1-906E-1EC25CCE643B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A6A1DD55-8F21-49B1-906E-1EC25CCE643B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A6A1DD55-8F21-49B1-906E-1EC25CCE643B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_14/CodeBaseClient/CodeBaseClient/App.config b/Chapter_14/CodeBaseClient/CodeBaseClient/App.config new file mode 100644 index 0000000..1d421fb --- /dev/null +++ b/Chapter_14/CodeBaseClient/CodeBaseClient/App.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/CodeBaseClient/CodeBaseClient/CodeBaseClient.csproj b/Chapter_14/CodeBaseClient/CodeBaseClient/CodeBaseClient.csproj new file mode 100644 index 0000000..8dc0d8d --- /dev/null +++ b/Chapter_14/CodeBaseClient/CodeBaseClient/CodeBaseClient.csproj @@ -0,0 +1,56 @@ + + + + + Debug + AnyCPU + {A6A1DD55-8F21-49B1-906E-1EC25CCE643B} + Exe + CodeBaseClient + CodeBaseClient + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\CarLibrary\CarLibrary\bin\Debug\CarLibrary.dll + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/CodeBaseClient/CodeBaseClient/Program.cs b/Chapter_14/CodeBaseClient/CodeBaseClient/Program.cs new file mode 100644 index 0000000..859f1af --- /dev/null +++ b/Chapter_14/CodeBaseClient/CodeBaseClient/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using CarLibrary; + +namespace CodeBaseClient +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with CodeBases *****"); + SportsCar c = new SportsCar(); + Console.WriteLine("Sports car has been allocated."); + Console.ReadLine(); + } + } +} diff --git a/Chapter_14/CodeBaseClient/CodeBaseClient/Properties/AssemblyInfo.cs b/Chapter_14/CodeBaseClient/CodeBaseClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..abde3b5 --- /dev/null +++ b/Chapter_14/CodeBaseClient/CodeBaseClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CodeBaseClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CodeBaseClient")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a6a1dd55-8f21-49b1-906e-1ec25cce643b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_14/CustomNamespaces/CustomNamespaces.sln b/Chapter_14/CustomNamespaces/CustomNamespaces.sln new file mode 100644 index 0000000..f3ce56d --- /dev/null +++ b/Chapter_14/CustomNamespaces/CustomNamespaces.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomNamespaces", "CustomNamespaces\CustomNamespaces.csproj", "{6D0B4625-721C-46FE-9CE4-E3738AFD4D0F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6D0B4625-721C-46FE-9CE4-E3738AFD4D0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6D0B4625-721C-46FE-9CE4-E3738AFD4D0F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6D0B4625-721C-46FE-9CE4-E3738AFD4D0F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6D0B4625-721C-46FE-9CE4-E3738AFD4D0F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_14/CustomNamespaces/CustomNamespaces/App.config b/Chapter_14/CustomNamespaces/CustomNamespaces/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_14/CustomNamespaces/CustomNamespaces/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_14/CustomNamespaces/CustomNamespaces/CustomNamespaces.csproj b/Chapter_14/CustomNamespaces/CustomNamespaces/CustomNamespaces.csproj new file mode 100644 index 0000000..c362080 --- /dev/null +++ b/Chapter_14/CustomNamespaces/CustomNamespaces/CustomNamespaces.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {6D0B4625-721C-46FE-9CE4-E3738AFD4D0F} + Exe + Chapter14.CoreLogic + CustomNamespaces + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/CustomNamespaces/CustomNamespaces/My3DShapes.cs b/Chapter_14/CustomNamespaces/CustomNamespaces/My3DShapes.cs new file mode 100644 index 0000000..a5aea88 --- /dev/null +++ b/Chapter_14/CustomNamespaces/CustomNamespaces/My3DShapes.cs @@ -0,0 +1,13 @@ +// Another shape-centric namespace. +using System; +namespace My3DShapes +{ + // 3D Circle class. + public class Circle { } + + // 3D Hexagon class. + public class Hexagon { } + + // 3D Square class. + public class Square { } +} diff --git a/Chapter_14/CustomNamespaces/CustomNamespaces/Program.cs b/Chapter_14/CustomNamespaces/CustomNamespaces/Program.cs new file mode 100644 index 0000000..b30e1d4 --- /dev/null +++ b/Chapter_14/CustomNamespaces/CustomNamespaces/Program.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// Make use of types defined the MyShapes namespace. +using MyShapes; + +// Resolve the ambiguity using a custom alias. +using The3DHexagon = My3DShapes.Hexagon; + +namespace CustomNamespaces +{ + public class Program + { + static void Main(string[] args) + { + Console.WriteLine("This app does not really do anything..."); + Console.WriteLine("Just illustrating namespaces."); + // This is really creating a My3DShapes.Hexagon class. + The3DHexagon h2 = new The3DHexagon(); + + Hexagon h = new Hexagon(); + Circle c = new Circle(); + Square s = new Square(); + } + } +} diff --git a/Chapter_14/CustomNamespaces/CustomNamespaces/Properties/AssemblyInfo.cs b/Chapter_14/CustomNamespaces/CustomNamespaces/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1dade79 --- /dev/null +++ b/Chapter_14/CustomNamespaces/CustomNamespaces/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CustomNamespaces")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CustomNamespaces")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6d0b4625-721c-46fe-9ce4-e3738afd4d0f")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_14/CustomNamespaces/CustomNamespaces/ShapesLib.cs b/Chapter_14/CustomNamespaces/CustomNamespaces/ShapesLib.cs new file mode 100644 index 0000000..906ca6d --- /dev/null +++ b/Chapter_14/CustomNamespaces/CustomNamespaces/ShapesLib.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MyShapes +{ + // Circle class + public class Circle { /* Interesting members... */ } + + // Hexagon class + public class Hexagon { /* More interesting members... */ } + + // Square class + public class Square { /* Even more interesting members... */ } +} \ No newline at end of file diff --git a/Chapter_14/MyApp/CSharpCarClient.exe.config b/Chapter_14/MyApp/CSharpCarClient.exe.config new file mode 100644 index 0000000..bb54430 --- /dev/null +++ b/Chapter_14/MyApp/CSharpCarClient.exe.config @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/SharedCarLibClient/SharedCarLibClient.sln b/Chapter_14/SharedCarLibClient/SharedCarLibClient.sln new file mode 100644 index 0000000..2a25aea --- /dev/null +++ b/Chapter_14/SharedCarLibClient/SharedCarLibClient.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedCarLibClient", "SharedCarLibClient\SharedCarLibClient.csproj", "{EEE4DA53-84EF-4DE3-ACCD-88C1073F43DD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EEE4DA53-84EF-4DE3-ACCD-88C1073F43DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EEE4DA53-84EF-4DE3-ACCD-88C1073F43DD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EEE4DA53-84EF-4DE3-ACCD-88C1073F43DD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EEE4DA53-84EF-4DE3-ACCD-88C1073F43DD}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_14/SharedCarLibClient/SharedCarLibClient/App.config b/Chapter_14/SharedCarLibClient/SharedCarLibClient/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_14/SharedCarLibClient/SharedCarLibClient/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_14/SharedCarLibClient/SharedCarLibClient/Program.cs b/Chapter_14/SharedCarLibClient/SharedCarLibClient/Program.cs new file mode 100644 index 0000000..89cae0f --- /dev/null +++ b/Chapter_14/SharedCarLibClient/SharedCarLibClient/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using CarLibrary; + +namespace SharedCarLibClient +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Shared Assembly Client *****"); + SportsCar c = new SportsCar(); + c.TurboBoost(); + Console.ReadLine(); + } + } +} diff --git a/Chapter_14/SharedCarLibClient/SharedCarLibClient/Properties/AssemblyInfo.cs b/Chapter_14/SharedCarLibClient/SharedCarLibClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8c650d0 --- /dev/null +++ b/Chapter_14/SharedCarLibClient/SharedCarLibClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SharedCarLibClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SharedCarLibClient")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("eee4da53-84ef-4de3-accd-88c1073f43dd")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_14/SharedCarLibClient/SharedCarLibClient/SharedCarLibClient.csproj b/Chapter_14/SharedCarLibClient/SharedCarLibClient/SharedCarLibClient.csproj new file mode 100644 index 0000000..6be9e97 --- /dev/null +++ b/Chapter_14/SharedCarLibClient/SharedCarLibClient/SharedCarLibClient.csproj @@ -0,0 +1,57 @@ + + + + + Debug + AnyCPU + {EEE4DA53-84EF-4DE3-ACCD-88C1073F43DD} + Exe + SharedCarLibClient + SharedCarLibClient + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\CarLibrary\CarLibrary\bin\Debug\CarLibrary.dll + False + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient.sln b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient.sln new file mode 100644 index 0000000..1809591 --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "VisualBasicCarClient", "VisualBasicCarClient\VisualBasicCarClient.vbproj", "{8D2CD518-94AC-4E29-8321-10836399E4B6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8D2CD518-94AC-4E29-8321-10836399E4B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8D2CD518-94AC-4E29-8321-10836399E4B6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D2CD518-94AC-4E29-8321-10836399E4B6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8D2CD518-94AC-4E29-8321-10836399E4B6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/App.config b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/Module1.vb b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/Module1.vb new file mode 100644 index 0000000..286b308 --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/Module1.vb @@ -0,0 +1,23 @@ +Imports CarLibrary + +Module Module1 + + Sub Main() + Console.WriteLine("***** VB CarLibrary Client App *****") + ' Local variables are declared using the Dim keyword. + Dim myMiniVan As New MiniVan() + myMiniVan.TurboBoost() + + Dim mySportsCar As New SportsCar() + mySportsCar.TurboBoost() + + Dim dreamCar As New PerformanceCar() + ' Use Inherited property. + dreamCar.PetName = "Hank" + dreamCar.TurboBoost() + + Console.ReadLine() + End Sub + + +End Module diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Application.Designer.vb b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Application.Designer.vb new file mode 100644 index 0000000..88dd01c --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Application.Designer.vb @@ -0,0 +1,13 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Application.myapp b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Application.myapp new file mode 100644 index 0000000..e62f1a5 --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Application.myapp @@ -0,0 +1,10 @@ + + + false + false + 0 + true + 0 + 2 + true + diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/AssemblyInfo.vb b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/AssemblyInfo.vb new file mode 100644 index 0000000..aa4447d --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/AssemblyInfo.vb @@ -0,0 +1,35 @@ +Imports System +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Resources.Designer.vb b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Resources.Designer.vb new file mode 100644 index 0000000..09984ac --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Resources.Designer.vb @@ -0,0 +1,62 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ''' + ''' A strongly-typed resource class, for looking up localized strings, etc. + ''' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ''' + ''' Returns the cached ResourceManager instance used by this class. + ''' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("VisualBasicCarClient.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ''' + ''' Overrides the current thread's CurrentUICulture property for all + ''' resource lookups using this strongly typed resource class. + ''' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set(ByVal value As Global.System.Globalization.CultureInfo) + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Resources.resx b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Settings.Designer.vb b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Settings.Designer.vb new file mode 100644 index 0000000..28d4601 --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.VisualBasicCarClient.My.MySettings + Get + Return Global.VisualBasicCarClient.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Settings.settings b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Settings.settings new file mode 100644 index 0000000..85b890b --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/PerformanceCar.vb b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/PerformanceCar.vb new file mode 100644 index 0000000..e4b0a5a --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/PerformanceCar.vb @@ -0,0 +1,10 @@ +Imports CarLibrary + +' This VB class is deriving from the C# SportsCar. +Public Class PerformanceCar + Inherits SportsCar + + Public Overrides Sub TurboBoost() + Console.WriteLine("Zero to 60 in a cool 4.8 seconds...") + End Sub +End Class diff --git a/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/VisualBasicCarClient.vbproj b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/VisualBasicCarClient.vbproj new file mode 100644 index 0000000..ea80421 --- /dev/null +++ b/Chapter_14/VisualBasicCarClient/VisualBasicCarClient/VisualBasicCarClient.vbproj @@ -0,0 +1,113 @@ + + + + + Debug + AnyCPU + {8D2CD518-94AC-4E29-8321-10836399E4B6} + Exe + VisualBasicCarClient.Module1 + VisualBasicCarClient + VisualBasicCarClient + 512 + Console + v4.7 + true + + + AnyCPU + true + full + true + true + bin\Debug\ + VisualBasicCarClient.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + AnyCPU + pdbonly + false + true + true + bin\Release\ + VisualBasicCarClient.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + On + + + Binary + + + Off + + + On + + + + ..\..\CarLibrary\CarLibrary\bin\Debug\CarLibrary.dll + + + + + + + + + + + + + + + + + + + + + + + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + \ No newline at end of file diff --git a/Chapter_15/ApplyingAttributes/ApplyingAttributes.sln b/Chapter_15/ApplyingAttributes/ApplyingAttributes.sln new file mode 100644 index 0000000..7fcd063 --- /dev/null +++ b/Chapter_15/ApplyingAttributes/ApplyingAttributes.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApplyingAttributes", "ApplyingAttributes\ApplyingAttributes.csproj", "{B6149D98-C499-4371-8E5C-ACFEB76FC8BE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B6149D98-C499-4371-8E5C-ACFEB76FC8BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6149D98-C499-4371-8E5C-ACFEB76FC8BE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6149D98-C499-4371-8E5C-ACFEB76FC8BE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6149D98-C499-4371-8E5C-ACFEB76FC8BE}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/ApplyingAttributes/ApplyingAttributes/App.config b/Chapter_15/ApplyingAttributes/ApplyingAttributes/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_15/ApplyingAttributes/ApplyingAttributes/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_15/ApplyingAttributes/ApplyingAttributes/ApplyingAttributes.csproj b/Chapter_15/ApplyingAttributes/ApplyingAttributes/ApplyingAttributes.csproj new file mode 100644 index 0000000..d34f538 --- /dev/null +++ b/Chapter_15/ApplyingAttributes/ApplyingAttributes/ApplyingAttributes.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {B6149D98-C499-4371-8E5C-ACFEB76FC8BE} + Exe + ApplyingAttributes + ApplyingAttributes + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_15/ApplyingAttributes/ApplyingAttributes/Program.cs b/Chapter_15/ApplyingAttributes/ApplyingAttributes/Program.cs new file mode 100644 index 0000000..e1dc315 --- /dev/null +++ b/Chapter_15/ApplyingAttributes/ApplyingAttributes/Program.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ApplyingAttributes +{ + #region Simple classes for testing + // This class can be saved to disk. + [Serializable] + public class Motorcycle + { + // However this field will not be persisted. + [NonSerialized] + float weightOfCurrentPassengers; + + // These fields are still serializable. + bool hasRadioSystem; + bool hasHeadSet; + bool hasSissyBar; + } + + [Serializable, Obsolete("Use another vehicle!")] + public class HorseAndBuggy + { + // ... + } + #endregion + + class Program + { + static void Main(string[] args) + { + HorseAndBuggy mule = new HorseAndBuggy(); + } + } +} diff --git a/Chapter_15/ApplyingAttributes/ApplyingAttributes/Properties/AssemblyInfo.cs b/Chapter_15/ApplyingAttributes/ApplyingAttributes/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d71e6bd --- /dev/null +++ b/Chapter_15/ApplyingAttributes/ApplyingAttributes/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ApplyingAttributes")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ApplyingAttributes")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b6149d98-c499-4371-8e5c-acfeb76fc8be")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/AttributedCarLibrary/AttributedCarLibrary.sln b/Chapter_15/AttributedCarLibrary/AttributedCarLibrary.sln new file mode 100644 index 0000000..32e84f0 --- /dev/null +++ b/Chapter_15/AttributedCarLibrary/AttributedCarLibrary.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AttributedCarLibrary", "AttributedCarLibrary\AttributedCarLibrary.csproj", "{2A7A1B87-6CA6-40A6-A40E-3AA5049AE7FA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2A7A1B87-6CA6-40A6-A40E-3AA5049AE7FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2A7A1B87-6CA6-40A6-A40E-3AA5049AE7FA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2A7A1B87-6CA6-40A6-A40E-3AA5049AE7FA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2A7A1B87-6CA6-40A6-A40E-3AA5049AE7FA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/AttributedCarLibrary.csproj b/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/AttributedCarLibrary.csproj new file mode 100644 index 0000000..3cffe92 --- /dev/null +++ b/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/AttributedCarLibrary.csproj @@ -0,0 +1,47 @@ + + + + + Debug + AnyCPU + {2A7A1B87-6CA6-40A6-A40E-3AA5049AE7FA} + Library + Properties + AttributedCarLibrary + AttributedCarLibrary + v4.7 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/Properties/AssemblyInfo.cs b/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..cc784a8 --- /dev/null +++ b/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AttributedCarLibrary")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AttributedCarLibrary")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2a7a1b87-6ca6-40a6-a40e-3aa5049ae7fa")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/Types.cs b/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/Types.cs new file mode 100644 index 0000000..c5c4b18 --- /dev/null +++ b/Chapter_15/AttributedCarLibrary/AttributedCarLibrary/Types.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +[assembly: CLSCompliant(true)] + +namespace AttributedCarLibrary +{ + #region Custom attribute! + // A custom attribute. + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct,AllowMultiple = false, Inherited = false)] + public sealed class VehicleDescriptionAttribute : System.Attribute + { + public string Description { get; set; } + + public VehicleDescriptionAttribute(string vehicalDescription) + => Description = vehicalDescription; + public VehicleDescriptionAttribute() { } + } + #endregion + + // Assign description using a "named property." + [Serializable] + [VehicleDescription(Description = "My rocking Harley")] + public class Motorcycle + { + } + + [SerializableAttribute] + [ObsoleteAttribute("Use another vehicle!")] + [VehicleDescription("The old gray mare, she ain't what she used to be...")] + public class HorseAndBuggy + { + } + + [VehicleDescription("A very long, slow, but feature-rich auto")] + public class Winnebago + { + } +} diff --git a/Chapter_15/ExtendableApp/CSharpSnapIn/CSharpModule.cs b/Chapter_15/ExtendableApp/CSharpSnapIn/CSharpModule.cs new file mode 100644 index 0000000..7ab011a --- /dev/null +++ b/Chapter_15/ExtendableApp/CSharpSnapIn/CSharpModule.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using CommonSnappableTypes; + +namespace CSharpSnapIn +{ + [CompanyInfo(CompanyName = "FooBar", CompanyUrl = "www.FooBar.com")] + public class CSharpModule : IAppFunctionality + { + void IAppFunctionality.DoIt() + { + Console.WriteLine("You have just used the C# snap in!"); + } + } +} diff --git a/Chapter_15/ExtendableApp/CSharpSnapIn/CSharpSnapIn.csproj b/Chapter_15/ExtendableApp/CSharpSnapIn/CSharpSnapIn.csproj new file mode 100644 index 0000000..280921a --- /dev/null +++ b/Chapter_15/ExtendableApp/CSharpSnapIn/CSharpSnapIn.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {8C108FE3-43FD-45FB-9703-29D6BB2E1291} + Library + Properties + CSharpSnapIn + CSharpSnapIn + v4.7 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + {5540525e-6d9f-4ecc-b875-2baad59e3a00} + CommonSnappableTypes + + + + \ No newline at end of file diff --git a/Chapter_15/ExtendableApp/CSharpSnapIn/Properties/AssemblyInfo.cs b/Chapter_15/ExtendableApp/CSharpSnapIn/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bab6a61 --- /dev/null +++ b/Chapter_15/ExtendableApp/CSharpSnapIn/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CSharpSnapIn")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CSharpSnapIn")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8c108fe3-43fd-45fb-9703-29d6bb2e1291")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/ExtendableApp/CommonSnappableTypes/CommonSnappableTypes.csproj b/Chapter_15/ExtendableApp/CommonSnappableTypes/CommonSnappableTypes.csproj new file mode 100644 index 0000000..122ec90 --- /dev/null +++ b/Chapter_15/ExtendableApp/CommonSnappableTypes/CommonSnappableTypes.csproj @@ -0,0 +1,47 @@ + + + + + Debug + AnyCPU + {5540525E-6D9F-4ECC-B875-2BAAD59E3A00} + Library + Properties + CommonSnappableTypes + CommonSnappableTypes + v4.7 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_15/ExtendableApp/CommonSnappableTypes/Properties/AssemblyInfo.cs b/Chapter_15/ExtendableApp/CommonSnappableTypes/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bc64c87 --- /dev/null +++ b/Chapter_15/ExtendableApp/CommonSnappableTypes/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CommonSnappableTypes")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CommonSnappableTypes")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5540525e-6d9f-4ecc-b875-2baad59e3a00")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/ExtendableApp/CommonSnappableTypes/SnappableTypes.cs b/Chapter_15/ExtendableApp/CommonSnappableTypes/SnappableTypes.cs new file mode 100644 index 0000000..6200dd1 --- /dev/null +++ b/Chapter_15/ExtendableApp/CommonSnappableTypes/SnappableTypes.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace CommonSnappableTypes +{ + public interface IAppFunctionality + { + void DoIt(); + } + + [AttributeUsage(AttributeTargets.Class)] + public sealed class CompanyInfoAttribute : System.Attribute + { + public string CompanyName { get; set; } + public string CompanyUrl { get; set; } + } + +} diff --git a/Chapter_15/ExtendableApp/ExtendableApp.sln b/Chapter_15/ExtendableApp/ExtendableApp.sln new file mode 100644 index 0000000..b52652d --- /dev/null +++ b/Chapter_15/ExtendableApp/ExtendableApp.sln @@ -0,0 +1,44 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommonSnappableTypes", "CommonSnappableTypes\CommonSnappableTypes.csproj", "{5540525E-6D9F-4ECC-B875-2BAAD59E3A00}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpSnapIn", "CSharpSnapIn\CSharpSnapIn.csproj", "{8C108FE3-43FD-45FB-9703-29D6BB2E1291}" +EndProject +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "VbSnapIn", "VbSnapIn\VbSnapIn.vbproj", "{93F7B99D-8E78-466A-AF8D-CE4179567D08}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyExtendableApp", "MyExtendableApp\MyExtendableApp.csproj", "{4C3427E2-B3C1-4F23-A234-AEDBEFFFEC61}" + ProjectSection(ProjectDependencies) = postProject + {93F7B99D-8E78-466A-AF8D-CE4179567D08} = {93F7B99D-8E78-466A-AF8D-CE4179567D08} + {8C108FE3-43FD-45FB-9703-29D6BB2E1291} = {8C108FE3-43FD-45FB-9703-29D6BB2E1291} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5540525E-6D9F-4ECC-B875-2BAAD59E3A00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5540525E-6D9F-4ECC-B875-2BAAD59E3A00}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5540525E-6D9F-4ECC-B875-2BAAD59E3A00}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5540525E-6D9F-4ECC-B875-2BAAD59E3A00}.Release|Any CPU.Build.0 = Release|Any CPU + {8C108FE3-43FD-45FB-9703-29D6BB2E1291}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8C108FE3-43FD-45FB-9703-29D6BB2E1291}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8C108FE3-43FD-45FB-9703-29D6BB2E1291}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8C108FE3-43FD-45FB-9703-29D6BB2E1291}.Release|Any CPU.Build.0 = Release|Any CPU + {93F7B99D-8E78-466A-AF8D-CE4179567D08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {93F7B99D-8E78-466A-AF8D-CE4179567D08}.Debug|Any CPU.Build.0 = Debug|Any CPU + {93F7B99D-8E78-466A-AF8D-CE4179567D08}.Release|Any CPU.ActiveCfg = Release|Any CPU + {93F7B99D-8E78-466A-AF8D-CE4179567D08}.Release|Any CPU.Build.0 = Release|Any CPU + {4C3427E2-B3C1-4F23-A234-AEDBEFFFEC61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C3427E2-B3C1-4F23-A234-AEDBEFFFEC61}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C3427E2-B3C1-4F23-A234-AEDBEFFFEC61}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C3427E2-B3C1-4F23-A234-AEDBEFFFEC61}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/ExtendableApp/MyExtendableApp/App.config b/Chapter_15/ExtendableApp/MyExtendableApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_15/ExtendableApp/MyExtendableApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_15/ExtendableApp/MyExtendableApp/MyExtendableApp.csproj b/Chapter_15/ExtendableApp/MyExtendableApp/MyExtendableApp.csproj new file mode 100644 index 0000000..41661dc --- /dev/null +++ b/Chapter_15/ExtendableApp/MyExtendableApp/MyExtendableApp.csproj @@ -0,0 +1,59 @@ + + + + + Debug + AnyCPU + {4C3427E2-B3C1-4F23-A234-AEDBEFFFEC61} + Exe + MyExtendableApp + MyExtendableApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + {5540525e-6d9f-4ecc-b875-2baad59e3a00} + CommonSnappableTypes + + + + \ No newline at end of file diff --git a/Chapter_15/ExtendableApp/MyExtendableApp/Program.cs b/Chapter_15/ExtendableApp/MyExtendableApp/Program.cs new file mode 100644 index 0000000..5261c3f --- /dev/null +++ b/Chapter_15/ExtendableApp/MyExtendableApp/Program.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using CommonSnappableTypes; + +namespace MyExtendableApp +{ + class Program + { + [STAThread] + static void Main(string[] args) + { + Console.WriteLine("***** Welcome to MyTypeViewer *****"); + do + { + Console.WriteLine("\nWould you like to load a snapin? [Y,N]"); + + // Get name of type. + string answer = Console.ReadLine(); + + // Does user want to quit? + if (!answer.Equals("Y", StringComparison.OrdinalIgnoreCase)) + { + break; + } + + // Try to display type. + try + { + LoadSnapin(); + } + catch (Exception ex) + { + Console.WriteLine("Sorry, can't find snapin"); + } + } while (true); + } + + static void LoadSnapin() + { + // Allow user to select an assembly to load. + OpenFileDialog dlg = new OpenFileDialog + { + //set the initial directory to the path of this project + InitialDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), + Filter = "assemblies (*.dll)|*.dll|All files (*.*)|*.*", + FilterIndex = 1 + }; + + if (dlg.ShowDialog() != DialogResult.OK) + { + Console.WriteLine("User cancelled out of the open file dialog."); + return; + } + if (dlg.FileName.Contains("CommonSnappableTypes")) + Console.WriteLine("CommonSnappableTypes has no snap-ins!"); + else if (!LoadExternalModule(dlg.FileName)) + Console.WriteLine("Nothing implements IAppFunctionality!"); + } + + private static bool LoadExternalModule(string path) + { + bool foundSnapIn = false; + Assembly theSnapInAsm = null; + + try + { + // Dynamically load the selected assembly. + theSnapInAsm = Assembly.LoadFrom(path); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred loading the snapin: {ex.Message}"); + return foundSnapIn; + } + + // Get all IAppFunctionality compatible classes in assembly. + var theClassTypes = from t in theSnapInAsm.GetTypes() + where t.IsClass && (t.GetInterface("IAppFunctionality") != null) + select t; + + // Now, create the object and call DoIt() method. + foreach (Type t in theClassTypes) + { + foundSnapIn = true; + // Use late binding to create the type. + IAppFunctionality itfApp = (IAppFunctionality) theSnapInAsm.CreateInstance(t.FullName, true); + itfApp?.DoIt(); + //lstLoadedSnapIns.Items.Add(t.FullName); + + // Show company info. + DisplayCompanyData(t); + } + return foundSnapIn; + } + + private static void DisplayCompanyData(Type t) + { + // Get [CompanyInfo] data. + var compInfo = from ci in t.GetCustomAttributes(false) + where (ci is CompanyInfoAttribute) + select ci; + + // Show data. + foreach (CompanyInfoAttribute c in compInfo) + { + Console.WriteLine($"More info about {c.CompanyName} can be found at {c.CompanyUrl}"); + } + } + } +} \ No newline at end of file diff --git a/Chapter_15/ExtendableApp/MyExtendableApp/Properties/AssemblyInfo.cs b/Chapter_15/ExtendableApp/MyExtendableApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ec1fdeb --- /dev/null +++ b/Chapter_15/ExtendableApp/MyExtendableApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MyExtendableApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MyExtendableApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4c3427e2-b3c1-4f23-a234-aedbefffec61")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/ExtendableApp/VbSnapIn/My Project/Application.Designer.vb b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Application.Designer.vb new file mode 100644 index 0000000..88dd01c --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Application.Designer.vb @@ -0,0 +1,13 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + diff --git a/Chapter_15/ExtendableApp/VbSnapIn/My Project/Application.myapp b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Application.myapp new file mode 100644 index 0000000..758895d --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Application.myapp @@ -0,0 +1,10 @@ + + + false + false + 0 + true + 0 + 1 + true + diff --git a/Chapter_15/ExtendableApp/VbSnapIn/My Project/AssemblyInfo.vb b/Chapter_15/ExtendableApp/VbSnapIn/My Project/AssemblyInfo.vb new file mode 100644 index 0000000..07480dd --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/My Project/AssemblyInfo.vb @@ -0,0 +1,35 @@ +Imports System +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/Chapter_15/ExtendableApp/VbSnapIn/My Project/Resources.Designer.vb b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Resources.Designer.vb new file mode 100644 index 0000000..34d5ceb --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Resources.Designer.vb @@ -0,0 +1,62 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ''' + ''' A strongly-typed resource class, for looking up localized strings, etc. + ''' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ''' + ''' Returns the cached ResourceManager instance used by this class. + ''' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("VbSnapIn.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ''' + ''' Overrides the current thread's CurrentUICulture property for all + ''' resource lookups using this strongly typed resource class. + ''' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set(ByVal value As Global.System.Globalization.CultureInfo) + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/Chapter_15/ExtendableApp/VbSnapIn/My Project/Resources.resx b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Chapter_15/ExtendableApp/VbSnapIn/My Project/Settings.Designer.vb b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Settings.Designer.vb new file mode 100644 index 0000000..9424ebb --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.VbSnapIn.My.MySettings + Get + Return Global.VbSnapIn.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/Chapter_15/ExtendableApp/VbSnapIn/My Project/Settings.settings b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Settings.settings new file mode 100644 index 0000000..85b890b --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Chapter_15/ExtendableApp/VbSnapIn/VbSnapIn.vb b/Chapter_15/ExtendableApp/VbSnapIn/VbSnapIn.vb new file mode 100644 index 0000000..04d4e83 --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/VbSnapIn.vb @@ -0,0 +1,10 @@ +Imports CommonSnappableTypes + + _ +Public Class VbSnapIn + Implements IAppFunctionality + + Public Sub DoIt() Implements CommonSnappableTypes.IAppFunctionality.DoIt + Console.WriteLine("You have just used the VB snap in!") + End Sub +End Class diff --git a/Chapter_15/ExtendableApp/VbSnapIn/VbSnapIn.vbproj b/Chapter_15/ExtendableApp/VbSnapIn/VbSnapIn.vbproj new file mode 100644 index 0000000..06c697a --- /dev/null +++ b/Chapter_15/ExtendableApp/VbSnapIn/VbSnapIn.vbproj @@ -0,0 +1,109 @@ + + + + + Debug + AnyCPU + {93F7B99D-8E78-466A-AF8D-CE4179567D08} + Library + VbSnapIn + VbSnapIn + 512 + Windows + v4.7 + + + true + full + true + true + bin\Debug\ + VbSnapIn.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + pdbonly + false + true + true + bin\Release\ + VbSnapIn.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + On + + + Binary + + + Off + + + On + + + + + + + + + + + + + + + + + + + + + + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + {5540525e-6d9f-4ecc-b875-2baad59e3a00} + CommonSnappableTypes + + + + \ No newline at end of file diff --git a/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector.sln b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector.sln new file mode 100644 index 0000000..3fac034 --- /dev/null +++ b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExternalAssemblyReflector", "ExternalAssemblyReflector\ExternalAssemblyReflector.csproj", "{F25F868C-A89E-4158-9A17-2F58ED46DFEA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F25F868C-A89E-4158-9A17-2F58ED46DFEA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F25F868C-A89E-4158-9A17-2F58ED46DFEA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F25F868C-A89E-4158-9A17-2F58ED46DFEA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F25F868C-A89E-4158-9A17-2F58ED46DFEA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/App.config b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/ExternalAssemblyReflector.csproj b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/ExternalAssemblyReflector.csproj new file mode 100644 index 0000000..1b2a7ac --- /dev/null +++ b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/ExternalAssemblyReflector.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {F25F868C-A89E-4158-9A17-2F58ED46DFEA} + Exe + ExternalAssemblyReflector + ExternalAssemblyReflector + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/Program.cs b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/Program.cs new file mode 100644 index 0000000..f4a1d17 --- /dev/null +++ b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/Program.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using System.Reflection; +using System.IO; // For FileNotFoundException definition. + +namespace ExternalAssemblyReflector +{ + class Program + { + #region Helper function + static void DisplayTypesInAsm(Assembly asm) + { + Console.WriteLine("\n***** Types in Assembly *****"); + Console.WriteLine("->{0}", asm.FullName); + Type[] types = asm.GetTypes(); + foreach (Type t in types) + Console.WriteLine("Type: {0}", t); + Console.WriteLine(""); + } + #endregion + + static void Main(string[] args) + { + Console.WriteLine("***** External Assembly Viewer *****"); + + string asmName = ""; + Assembly asm = null; + + do + { + Console.WriteLine("\nEnter an assembly to evaluate"); + Console.Write("or enter Q to quit: "); + + // Get name of assembly. + asmName = Console.ReadLine(); + + // Does user want to quit? + if (asmName.Equals("Q",StringComparison.OrdinalIgnoreCase)) + { + + break; + } + + // Try to load assembly. + try + { + //asm = Assembly.Load(asmName); + asm = Assembly.LoadFrom(asmName); + DisplayTypesInAsm(asm); + } + catch + { + Console.WriteLine("Sorry, can't find assembly."); + } + } while (true); + } + } +} diff --git a/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/Properties/AssemblyInfo.cs b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..cfb7b33 --- /dev/null +++ b/Chapter_15/ExternalAssemblyReflector/ExternalAssemblyReflector/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ExternalAssemblyReflector")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ExternalAssemblyReflector")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f25f868c-a89e-4158-9a17-2f58ed46dfea")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/LateBindingApp/LateBindingApp.sln b/Chapter_15/LateBindingApp/LateBindingApp.sln new file mode 100644 index 0000000..7be267d --- /dev/null +++ b/Chapter_15/LateBindingApp/LateBindingApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LateBindingApp", "LateBindingApp\LateBindingApp.csproj", "{70016404-A363-474D-997E-5687351C3743}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {70016404-A363-474D-997E-5687351C3743}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {70016404-A363-474D-997E-5687351C3743}.Debug|Any CPU.Build.0 = Debug|Any CPU + {70016404-A363-474D-997E-5687351C3743}.Release|Any CPU.ActiveCfg = Release|Any CPU + {70016404-A363-474D-997E-5687351C3743}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/LateBindingApp/LateBindingApp/App.config b/Chapter_15/LateBindingApp/LateBindingApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_15/LateBindingApp/LateBindingApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_15/LateBindingApp/LateBindingApp/LateBindingApp.csproj b/Chapter_15/LateBindingApp/LateBindingApp/LateBindingApp.csproj new file mode 100644 index 0000000..100b571 --- /dev/null +++ b/Chapter_15/LateBindingApp/LateBindingApp/LateBindingApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {70016404-A363-474D-997E-5687351C3743} + Exe + LateBindingApp + LateBindingApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_15/LateBindingApp/LateBindingApp/Program.cs b/Chapter_15/LateBindingApp/LateBindingApp/Program.cs new file mode 100644 index 0000000..c5c2a2c --- /dev/null +++ b/Chapter_15/LateBindingApp/LateBindingApp/Program.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using System.Reflection; + +namespace LateBindingApp +{ + // This program will load an external library, + // and create an object using late binding. + public class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Late Binding *****\n"); + // Try to load a local copy of CarLibrary. + Assembly a = null; + try + { + a = Assembly.Load("CarLibrary"); + } + catch (FileNotFoundException ex) + { + Console.WriteLine(ex.Message); + return; + } + + if (a != null) + { + CreateUsingLateBinding(a); + InvokeMethodWithArgsUsingLateBinding(a); + } + + Console.ReadLine(); + } + + #region Invoke method with no args + static void CreateUsingLateBinding(Assembly asm) + { + try + { + // Get metadata for the Minivan type. + Type miniVan = asm.GetType("CarLibrary.MiniVan"); + + // Create the Minivan on the fly. + object obj = Activator.CreateInstance(miniVan); + Console.WriteLine("Created a {0} using late binding!", obj); + + // Get info for TurboBoost. + MethodInfo mi = miniVan.GetMethod("TurboBoost"); + + // Invoke method ('null' for no parameters). + mi.Invoke(obj, null); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + #endregion + + #region Invoke method with args + static void InvokeMethodWithArgsUsingLateBinding(Assembly asm) + { + try + { + // First, get a metadata description of the sports car. + Type sport = asm.GetType("CarLibrary.SportsCar"); + + // Now, create the sports car. + object obj = Activator.CreateInstance(sport); + + // Invoke TurnOnRadio() with arguments. + MethodInfo mi = sport.GetMethod("TurnOnRadio"); + mi.Invoke(obj, new object[] { true, 2 }); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + #endregion + } +} diff --git a/Chapter_15/LateBindingApp/LateBindingApp/Properties/AssemblyInfo.cs b/Chapter_15/LateBindingApp/LateBindingApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..5cde6ee --- /dev/null +++ b/Chapter_15/LateBindingApp/LateBindingApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LateBindingApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LateBindingApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("70016404-a363-474d-997e-5687351c3743")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/MyTypeViewer/MyTypeViewer.sln b/Chapter_15/MyTypeViewer/MyTypeViewer.sln new file mode 100644 index 0000000..27adc0c --- /dev/null +++ b/Chapter_15/MyTypeViewer/MyTypeViewer.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyTypeViewer", "MyTypeViewer\MyTypeViewer.csproj", "{01A62B4E-6B6D-4493-9CE9-A647A184032D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {01A62B4E-6B6D-4493-9CE9-A647A184032D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {01A62B4E-6B6D-4493-9CE9-A647A184032D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {01A62B4E-6B6D-4493-9CE9-A647A184032D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {01A62B4E-6B6D-4493-9CE9-A647A184032D}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/MyTypeViewer/MyTypeViewer/App.config b/Chapter_15/MyTypeViewer/MyTypeViewer/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_15/MyTypeViewer/MyTypeViewer/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_15/MyTypeViewer/MyTypeViewer/MyTypeViewer.csproj b/Chapter_15/MyTypeViewer/MyTypeViewer/MyTypeViewer.csproj new file mode 100644 index 0000000..e1240dd --- /dev/null +++ b/Chapter_15/MyTypeViewer/MyTypeViewer/MyTypeViewer.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {01A62B4E-6B6D-4493-9CE9-A647A184032D} + Exe + MyTypeViewer + MyTypeViewer + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_15/MyTypeViewer/MyTypeViewer/Program.cs b/Chapter_15/MyTypeViewer/MyTypeViewer/Program.cs new file mode 100644 index 0000000..3906c53 --- /dev/null +++ b/Chapter_15/MyTypeViewer/MyTypeViewer/Program.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using System.Reflection; + +namespace MyTypeViewer +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Welcome to MyTypeViewer *****"); + string typeName = ""; + + do + { + Console.WriteLine("\nEnter a type name to evaluate"); + Console.Write("or enter Q to quit: "); + + // Get name of type. + typeName = Console.ReadLine(); + + // Does user want to quit? + if (typeName.Equals("Q",StringComparison.OrdinalIgnoreCase)) + { + break; + } + + // Try to display type. + try + { + Type t = Type.GetType(typeName); + Console.WriteLine(""); + ListVariousStats(t); + ListFields(t); + ListProps(t); + ListMethods(t); + ListInterfaces(t); + } + catch + { + Console.WriteLine("Sorry, can't find type"); + } + } while (true); + } + + #region Helper methods + + #region Simple version of ListMethods + // Display method names of type. + //static void ListMethods(Type t) + //{ + // Console.WriteLine("***** Methods *****"); + // var methodNames = from n in t.GetMethods() select n.Name; + // foreach (var name in methodNames) + // Console.WriteLine("->{0}", name); + // Console.WriteLine(); + //} + #endregion + + #region Complex version of ListMethods (No LINQ) + //static void ListMethods(Type t) + //{ + // Console.WriteLine("***** Methods *****"); + // MethodInfo[] mi = t.GetMethods(); + // foreach (MethodInfo m in mi) + // { + // // Get return value. + // string retVal = m.ReturnType.FullName; + // string paramInfo = "( "; + + // // Get params. + // foreach (ParameterInfo pi in m.GetParameters()) + // { + // paramInfo += string.Format("{0} {1} ", pi.ParameterType, pi.Name); + // } + // paramInfo += " )"; + + // // Now display the basic method sig. + // Console.WriteLine("->{0} {1} {2}", retVal, m.Name, paramInfo); + // } + // Console.WriteLine(); + //} + #endregion + + // Display method names of type. + static void ListMethods(Type t) + { + Console.WriteLine("***** Methods *****"); + var methodNames = from n in t.GetMethods() select n; + foreach (var name in methodNames) + Console.WriteLine("->{0}", name); + Console.WriteLine(); + } + + // Display field names of type. + static void ListFields(Type t) + { + Console.WriteLine("***** Fields *****"); + var fieldNames = from f in t.GetFields() select f.Name; + foreach (var name in fieldNames) + Console.WriteLine("->{0}", name); + Console.WriteLine(); + } + + // Display property names of type. + static void ListProps(Type t) + { + Console.WriteLine("***** Properties *****"); + var propNames = from p in t.GetProperties() select p.Name; + foreach (var name in propNames) + Console.WriteLine("->{0}", name); + Console.WriteLine(); + } + + // Display implemented interfaces. + static void ListInterfaces(Type t) + { + Console.WriteLine("***** Interfaces *****"); + var ifaces = from i in t.GetInterfaces() select i; + foreach (Type i in ifaces) + Console.WriteLine("->{0}", i.Name); + } + + // Just for good measure. + static void ListVariousStats(Type t) + { + Console.WriteLine("***** Various Statistics *****"); + Console.WriteLine("Base class is: {0}", t.BaseType); + Console.WriteLine("Is type abstract? {0}", t.IsAbstract); + Console.WriteLine("Is type sealed? {0}", t.IsSealed); + Console.WriteLine("Is type generic? {0}", t.IsGenericTypeDefinition); + Console.WriteLine("Is type a class type? {0}", t.IsClass); + Console.WriteLine(); + } + #endregion + } +} diff --git a/Chapter_15/MyTypeViewer/MyTypeViewer/Properties/AssemblyInfo.cs b/Chapter_15/MyTypeViewer/MyTypeViewer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..fc530d9 --- /dev/null +++ b/Chapter_15/MyTypeViewer/MyTypeViewer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MyTypeViewer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MyTypeViewer")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("01a62b4e-6b6d-4493-9ce9-a647a184032d")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/SharedAsmReflector/SharedAsmReflector.sln b/Chapter_15/SharedAsmReflector/SharedAsmReflector.sln new file mode 100644 index 0000000..b891d6f --- /dev/null +++ b/Chapter_15/SharedAsmReflector/SharedAsmReflector.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedAsmReflector", "SharedAsmReflector\SharedAsmReflector.csproj", "{B114A93E-AE1C-440C-A91D-54795FF42A05}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B114A93E-AE1C-440C-A91D-54795FF42A05}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B114A93E-AE1C-440C-A91D-54795FF42A05}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B114A93E-AE1C-440C-A91D-54795FF42A05}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B114A93E-AE1C-440C-A91D-54795FF42A05}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/SharedAsmReflector/SharedAsmReflector/App.config b/Chapter_15/SharedAsmReflector/SharedAsmReflector/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_15/SharedAsmReflector/SharedAsmReflector/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_15/SharedAsmReflector/SharedAsmReflector/Program.cs b/Chapter_15/SharedAsmReflector/SharedAsmReflector/Program.cs new file mode 100644 index 0000000..5b015d7 --- /dev/null +++ b/Chapter_15/SharedAsmReflector/SharedAsmReflector/Program.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using System.Reflection; +using System.IO; + +namespace SharedAsmReflector +{ + public class SharedAsmReflector + { + #region DisplayInfo helper method + private static void DisplayInfo(Assembly a) + { + Console.WriteLine("***** Info about Assembly *****"); + Console.WriteLine("Loaded from GAC? {0}", a.GlobalAssemblyCache); + Console.WriteLine("Asm Name: {0}", a.GetName().Name); + Console.WriteLine("Asm Version: {0}", a.GetName().Version); + Console.WriteLine("Asm Culture: {0}", + a.GetName().CultureInfo.DisplayName); + Console.WriteLine("\nHere are the public enums:"); + + // Use a LINQ query to find the public enums. + Type[] types = a.GetTypes(); + var publicEnums = from pe in types + where pe.IsEnum && + pe.IsPublic + select pe; + + foreach (var pe in types) + { + Console.WriteLine(pe); + } + } + #endregion + + static void Main(string[] args) + { + Console.WriteLine("***** The Shared Asm Reflector App *****\n"); + + // Load System.Windows.Forms.dll from GAC. + string displayName = null; + displayName = "System.Windows.Forms," + + "Version=4.0.0.0," + + "PublicKeyToken=b77a5c561934e089," + + @"Culture="""; + + Assembly asm = Assembly.Load(displayName); + + DisplayInfo(asm); + Console.WriteLine("Done!"); + Console.ReadLine(); + } + } +} diff --git a/Chapter_15/SharedAsmReflector/SharedAsmReflector/Properties/AssemblyInfo.cs b/Chapter_15/SharedAsmReflector/SharedAsmReflector/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d5bdfcd --- /dev/null +++ b/Chapter_15/SharedAsmReflector/SharedAsmReflector/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SharedAsmReflector")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SharedAsmReflector")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b114a93e-ae1c-440c-a91d-54795ff42a05")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/SharedAsmReflector/SharedAsmReflector/SharedAsmReflector.csproj b/Chapter_15/SharedAsmReflector/SharedAsmReflector/SharedAsmReflector.csproj new file mode 100644 index 0000000..3858612 --- /dev/null +++ b/Chapter_15/SharedAsmReflector/SharedAsmReflector/SharedAsmReflector.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {B114A93E-AE1C-440C-A91D-54795FF42A05} + Exe + SharedAsmReflector + SharedAsmReflector + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader.sln b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader.sln new file mode 100644 index 0000000..3626f7b --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleDescriptionAttributeReader", "VehicleDescriptionAttributeReader\VehicleDescriptionAttributeReader.csproj", "{9F4DADAC-B072-410F-AA7A-5DA5B20E1EAD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9F4DADAC-B072-410F-AA7A-5DA5B20E1EAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9F4DADAC-B072-410F-AA7A-5DA5B20E1EAD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9F4DADAC-B072-410F-AA7A-5DA5B20E1EAD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9F4DADAC-B072-410F-AA7A-5DA5B20E1EAD}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/App.config b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/Program.cs b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/Program.cs new file mode 100644 index 0000000..aae9a60 --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/Program.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using AttributedCarLibrary; + +namespace VehicleDescriptionAttributeReader +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Value of VehicleDescriptionAttribute *****\n"); + ReflectOnAttributesWithEarlyBinding(); + Console.ReadLine(); + } + + private static void ReflectOnAttributesWithEarlyBinding() + { + // Get a Type representing the Winnebago. + Type t = typeof(Winnebago); + + // Get all attributes on the Winnebago. + object[] customAtts = t.GetCustomAttributes(false); + + // Print the description. + foreach (VehicleDescriptionAttribute v in customAtts) + Console.WriteLine("-> {0}\n", v.Description); + } + } +} diff --git a/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/Properties/AssemblyInfo.cs b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2a3b73e --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("VehicleDescriptionAttributeReader")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("VehicleDescriptionAttributeReader")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9f4dadac-b072-410f-aa7a-5da5b20e1ead")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader.csproj b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader.csproj new file mode 100644 index 0000000..34226ce --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader/VehicleDescriptionAttributeReader.csproj @@ -0,0 +1,55 @@ + + + + + Debug + AnyCPU + {9F4DADAC-B072-410F-AA7A-5DA5B20E1EAD} + Exe + VehicleDescriptionAttributeReader + VehicleDescriptionAttributeReader + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\AttributedCarLibrary\AttributedCarLibrary\bin\Debug\AttributedCarLibrary.dll + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding.sln b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding.sln new file mode 100644 index 0000000..f4703c9 --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleDescriptionAttributeReaderLateBinding", "VehicleDescriptionAttributeReaderLateBinding\VehicleDescriptionAttributeReaderLateBinding.csproj", "{4976AC1F-0F47-4D2B-8EB8-F8F6084BCCAA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4976AC1F-0F47-4D2B-8EB8-F8F6084BCCAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4976AC1F-0F47-4D2B-8EB8-F8F6084BCCAA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4976AC1F-0F47-4D2B-8EB8-F8F6084BCCAA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4976AC1F-0F47-4D2B-8EB8-F8F6084BCCAA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/App.config b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/Program.cs b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/Program.cs new file mode 100644 index 0000000..be218ba --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/Program.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using System.Reflection; + +namespace VehicleDescriptionAttributeReaderLateBinding +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Value of VehicleDescriptionAttribute *****\n"); + ReflectAttributesUsingLateBinding(); + Console.ReadLine(); + } + + #region Helper method + private static void ReflectAttributesUsingLateBinding() + { + try + { + // Load the local copy of AttributedCarLibrary. + Assembly asm = Assembly.Load("AttributedCarLibrary"); + + // Get type info of VehicleDescriptionAttribute. + Type vehicleDesc = + asm.GetType("AttributedCarLibrary.VehicleDescriptionAttribute"); + + // Get type info of the Description property. + PropertyInfo propDesc = vehicleDesc.GetProperty("Description"); + + // Get all types in the assembly. + Type[] types = asm.GetTypes(); + + // Iterate over each type and obtain any VehicleDescriptionAttributes. + foreach (Type t in types) + { + object[] objs = t.GetCustomAttributes(vehicleDesc, false); + + // Iterate over each VehicleDescriptionAttribute and print + // the description using late binding. + foreach (object o in objs) + { + Console.WriteLine("-> {0}: {1}\n", + t.Name, propDesc.GetValue(o, null)); + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + #endregion + } +} diff --git a/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/Properties/AssemblyInfo.cs b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..edf7877 --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("VehicleDescriptionAttributeReaderLateBinding")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("VehicleDescriptionAttributeReaderLateBinding")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4976ac1f-0f47-4d2b-8eb8-f8f6084bccaa")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding.csproj b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding.csproj new file mode 100644 index 0000000..f13bcf1 --- /dev/null +++ b/Chapter_15/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding/VehicleDescriptionAttributeReaderLateBinding.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {4976AC1F-0F47-4D2B-8EB8-F8F6084BCCAA} + Exe + VehicleDescriptionAttributeReaderLateBinding + VehicleDescriptionAttributeReaderLateBinding + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_16/DynamicKeyword/DynamicKeyword.sln b/Chapter_16/DynamicKeyword/DynamicKeyword.sln new file mode 100644 index 0000000..357cb37 --- /dev/null +++ b/Chapter_16/DynamicKeyword/DynamicKeyword.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DynamicKeyword", "DynamicKeyword\DynamicKeyword.csproj", "{18C9985A-ABA4-48FF-B6C9-6BD25B4103ED}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {18C9985A-ABA4-48FF-B6C9-6BD25B4103ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18C9985A-ABA4-48FF-B6C9-6BD25B4103ED}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18C9985A-ABA4-48FF-B6C9-6BD25B4103ED}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18C9985A-ABA4-48FF-B6C9-6BD25B4103ED}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_16/DynamicKeyword/DynamicKeyword/App.config b/Chapter_16/DynamicKeyword/DynamicKeyword/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_16/DynamicKeyword/DynamicKeyword/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_16/DynamicKeyword/DynamicKeyword/DynamicKeyword.csproj b/Chapter_16/DynamicKeyword/DynamicKeyword/DynamicKeyword.csproj new file mode 100644 index 0000000..e5d46bc --- /dev/null +++ b/Chapter_16/DynamicKeyword/DynamicKeyword/DynamicKeyword.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {18C9985A-ABA4-48FF-B6C9-6BD25B4103ED} + Exe + DynamicKeyword + DynamicKeyword + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_16/DynamicKeyword/DynamicKeyword/Program.cs b/Chapter_16/DynamicKeyword/DynamicKeyword/Program.cs new file mode 100644 index 0000000..df3ee22 --- /dev/null +++ b/Chapter_16/DynamicKeyword/DynamicKeyword/Program.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DynamicKeyword +{ + #region Simple Person + class Person + { + public string FirstName { get; set; } = ""; + public string LastName { get; set; } = ""; + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with the dynamic keyword *****"); + PrintThreeStrings(); + Console.WriteLine(); + + ChangeDynamicDataType(); + Console.WriteLine(); + + InvokeMembersOnDynamicData(); + Console.WriteLine(); + + Console.ReadLine(); + } + + #region Implicit typing test + static void ImplicitlyTypedVariable() + { + // a is of type List. + var a = new List {90}; + // This would be a compile-time error! + // a = "Hello"; + } + #endregion + + #region Object type test + static void UseObjectVarible() + { + // Assume we have a class named Person. + object o = new Person() { FirstName = "Mike", LastName = "Larson" }; + + // Must cast object as Person to gain access to the Person properties. + Console.WriteLine("Person's first name is {0}", ((Person)o).FirstName); + } + #endregion + + #region Dynamic variable + static void ChangeDynamicDataType() + { + // Declare a single dynamic data point named "t". + dynamic t = "Hello!"; + Console.WriteLine("t is of type: {0}", t.GetType()); + + t = false; + Console.WriteLine("t is of type: {0}", t.GetType()); + + t = new List(); + Console.WriteLine("t is of type: {0}", t.GetType()); + } + + static void InvokeMembersOnDynamicData() + { + dynamic textData1 = "Hello"; + + try + { + Console.WriteLine(textData1.ToUpper()); + Console.WriteLine(textData1.toupper()); + Console.WriteLine(textData1.Foo(10, "ee", DateTime.Now)); + } + catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) + { + Console.WriteLine(ex.Message); + } + } + #endregion + + static void PrintThreeStrings() + { + var s1 = "Greetings"; + object s2 = "From"; + dynamic s3 = "Minneapolis"; + + Console.WriteLine("s1 is of type: {0}", s1.GetType()); + Console.WriteLine("s2 is of type: {0}", s2.GetType()); + Console.WriteLine("s3 is of type: {0}", s3.GetType()); + } + } +} diff --git a/Chapter_16/DynamicKeyword/DynamicKeyword/Properties/AssemblyInfo.cs b/Chapter_16/DynamicKeyword/DynamicKeyword/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e033990 --- /dev/null +++ b/Chapter_16/DynamicKeyword/DynamicKeyword/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DynamicKeyword")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DynamicKeyword")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("18c9985a-aba4-48ff-b6c9-6bd25b4103ed")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp.sln b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp.sln new file mode 100644 index 0000000..e405d11 --- /dev/null +++ b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExportDataToOfficeApp", "ExportDataToOfficeApp\ExportDataToOfficeApp.csproj", "{77DBFAF2-4D1C-4C09-B29A-1815E72FF348}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {77DBFAF2-4D1C-4C09-B29A-1815E72FF348}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {77DBFAF2-4D1C-4C09-B29A-1815E72FF348}.Debug|Any CPU.Build.0 = Debug|Any CPU + {77DBFAF2-4D1C-4C09-B29A-1815E72FF348}.Release|Any CPU.ActiveCfg = Release|Any CPU + {77DBFAF2-4D1C-4C09-B29A-1815E72FF348}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/App.config b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Car.cs b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Car.cs new file mode 100644 index 0000000..e44f531 --- /dev/null +++ b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Car.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ExportDataToOfficeApp +{ + public class Car + { + public string Make { get; set; } + public string Color { get; set; } + public string PetName { get; set; } + } +} diff --git a/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/ExportDataToOfficeApp.csproj b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/ExportDataToOfficeApp.csproj new file mode 100644 index 0000000..a8eb57b --- /dev/null +++ b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/ExportDataToOfficeApp.csproj @@ -0,0 +1,56 @@ + + + + + Debug + AnyCPU + {77DBFAF2-4D1C-4C09-B29A-1815E72FF348} + Exe + ExportDataToOfficeApp + ExportDataToOfficeApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + True + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Program.cs b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Program.cs new file mode 100644 index 0000000..fa21d34 --- /dev/null +++ b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Program.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using Excel = Microsoft.Office.Interop.Excel; + +namespace ExportDataToOfficeApp +{ + class Program + { + static void Main(string[] args) + { + List carsInStock = new List + { + new Car {Color="Green", Make="VW", PetName="Mary"}, + new Car {Color="Red", Make="Saab", PetName="Mel"}, + new Car {Color="Black", Make="Ford", PetName="Hank"}, + new Car {Color="Yellow", Make="BMW", PetName="Davie"} + }; + //ExportToExcelManual(carsInStock); + ExportToExcel(carsInStock); + Console.ReadLine(); + } + + static void ExportToExcel(List carsInStock) + { + // Load up Excel, then make a new empty workbook. + Excel.Application excelApp = new Excel.Application(); + excelApp.Workbooks.Add(); + + // This example uses a single workSheet. + Excel._Worksheet workSheet = excelApp.ActiveSheet; + + // Establish column headings in cells. + workSheet.Cells[1, "A"] = "Make"; + workSheet.Cells[1, "B"] = "Color"; + workSheet.Cells[1, "C"] = "Pet Name"; + + // Now, map all data in List to the cells of the spread sheet. + int row = 1; + foreach (Car c in carsInStock) + { + row++; + workSheet.Cells[row, "A"] = c.Make; + workSheet.Cells[row, "B"] = c.Color; + workSheet.Cells[row, "C"] = c.PetName; + } + + // Give our table data a nice look and feel. + workSheet.Range["A1"].AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2); + + // Save the file, quit Excel and display message to user. + workSheet.SaveAs($@"{Environment.CurrentDirectory}\Inventory.xlsx"); + excelApp.Quit(); + Console.WriteLine("The Inventory.xslx file has been saved to your app folder"); + } + + static void ExportToExcelManual(List carsInStock) + { + Excel.Application excelApp = new Excel.Application(); + + // Must mark missing params! + excelApp.Workbooks.Add(Type.Missing); + + // Must cast Object as _Worksheet! + Excel._Worksheet workSheet = (Excel._Worksheet)excelApp.ActiveSheet; + + // Must cast each Object as Range object then call low level Value2 property! + ((Excel.Range)excelApp.Cells[1, "A"]).Value2 = "Make"; + ((Excel.Range)excelApp.Cells[1, "B"]).Value2 = "Color"; + ((Excel.Range)excelApp.Cells[1, "C"]).Value2 = "Pet Name"; + + int row = 1; + foreach (Car c in carsInStock) + { + row++; + // Must cast each Object as Range and call low level Value2 prop! + ((Excel.Range)workSheet.Cells[row, "A"]).Value2 = c.Make; + ((Excel.Range)workSheet.Cells[row, "B"]).Value2 = c.Color; + ((Excel.Range)workSheet.Cells[row, "C"]).Value2 = c.PetName; + } + + // Must call get_Range method and then specify all missing args!. + excelApp.Range["A1", Type.Missing].AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2, + Type.Missing, Type.Missing, Type.Missing, + Type.Missing, Type.Missing, Type.Missing); + + // Must specify all missing optional args! + workSheet.SaveAs($@"{Environment.CurrentDirectory}\InventoryManual.xlsx", + Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, + Type.Missing, Type.Missing, Type.Missing); + excelApp.Quit(); + Console.WriteLine("The InventoryManual.xslx file has been saved to your app folder"); + } + + } +} diff --git a/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Properties/AssemblyInfo.cs b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2c23173 --- /dev/null +++ b/Chapter_16/ExportDataToOfficeApp/ExportDataToOfficeApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ExportDataToOfficeApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ExportDataToOfficeApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("77dbfaf2-4d1c-4c09-b29a-1815e72ff348")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic.sln b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic.sln new file mode 100644 index 0000000..0f0703d --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LateBindingWithDynamic", "LateBindingWithDynamic\LateBindingWithDynamic.csproj", "{1C1415CD-43F9-4023-8D74-F8CD86747353}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathLibrary", "MathLibrary\MathLibrary.csproj", "{E29D7B5D-0232-41A0-BD43-700BCC45E74E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1C1415CD-43F9-4023-8D74-F8CD86747353}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C1415CD-43F9-4023-8D74-F8CD86747353}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1C1415CD-43F9-4023-8D74-F8CD86747353}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1C1415CD-43F9-4023-8D74-F8CD86747353}.Release|Any CPU.Build.0 = Release|Any CPU + {E29D7B5D-0232-41A0-BD43-700BCC45E74E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E29D7B5D-0232-41A0-BD43-700BCC45E74E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E29D7B5D-0232-41A0-BD43-700BCC45E74E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E29D7B5D-0232-41A0-BD43-700BCC45E74E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/App.config b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/LateBindingWithDynamic.csproj b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/LateBindingWithDynamic.csproj new file mode 100644 index 0000000..2c57ab9 --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/LateBindingWithDynamic.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {1C1415CD-43F9-4023-8D74-F8CD86747353} + Exe + LateBindingWithDynamic + LateBindingWithDynamic + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/Program.cs b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/Program.cs new file mode 100644 index 0000000..f333b02 --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/Program.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace LateBindingWithDynamic +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Adding with reflection & dynamic keyword *****\n"); + AddWithReflection(); + AddWithDynamic(); + Console.ReadLine(); + } + + #region Add with reflection + private static void AddWithReflection() + { + Assembly asm = Assembly.Load("MathLibrary"); + try + { + // Get metadata for the SimpleMath type. + Type math = asm.GetType("MathLibrary.SimpleMath"); + + // Create a SimpleMath on the fly. + object obj = Activator.CreateInstance(math); + + // Get info for Add. + MethodInfo mi = math.GetMethod("Add"); + + // Invoke method (with parameters). + object[] args = { 10, 70 }; + Console.WriteLine("Result is: {0}", mi.Invoke(obj, args)); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + #endregion + + #region Add with dynamic + private static void AddWithDynamic() + { + Assembly asm = Assembly.Load("MathLibrary"); + + try + { + // Get metadata for the SimpleMath type. + Type math = asm.GetType("MathLibrary.SimpleMath"); + + // Create a SimpleMath on the fly. + dynamic obj = Activator.CreateInstance(math); + Console.WriteLine("Result is: {0}", obj.Add(10, 70)); + } + catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) + { + Console.WriteLine(ex.Message); + } + } + + #endregion + } +} diff --git a/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/Properties/AssemblyInfo.cs b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ea670eb --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/LateBindingWithDynamic/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LateBindingWithDynamic")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LateBindingWithDynamic")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1c1415cd-43f9-4023-8d74-f8cd86747353")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_16/LateBindingWithDynamic/MathLibrary/App.config b/Chapter_16/LateBindingWithDynamic/MathLibrary/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/MathLibrary/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_16/LateBindingWithDynamic/MathLibrary/MathLibrary.csproj b/Chapter_16/LateBindingWithDynamic/MathLibrary/MathLibrary.csproj new file mode 100644 index 0000000..75e9433 --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/MathLibrary/MathLibrary.csproj @@ -0,0 +1,55 @@ + + + + + Debug + AnyCPU + {E29D7B5D-0232-41A0-BD43-700BCC45E74E} + Library + MathLibrary + MathLibrary + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_16/LateBindingWithDynamic/MathLibrary/Properties/AssemblyInfo.cs b/Chapter_16/LateBindingWithDynamic/MathLibrary/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1b8d188 --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/MathLibrary/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MathLibrary")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MathLibrary")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e29d7b5d-0232-41a0-bd43-700bcc45e74e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_16/LateBindingWithDynamic/MathLibrary/SimpleMath.cs b/Chapter_16/LateBindingWithDynamic/MathLibrary/SimpleMath.cs new file mode 100644 index 0000000..40c3104 --- /dev/null +++ b/Chapter_16/LateBindingWithDynamic/MathLibrary/SimpleMath.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MathLibrary +{ + public class SimpleMath + { + public int Add(int x, int y) + { + return x + y; + } + } +} diff --git a/Chapter_17/CustomAppDomains/CustomAppDomains.sln b/Chapter_17/CustomAppDomains/CustomAppDomains.sln new file mode 100644 index 0000000..46b2de0 --- /dev/null +++ b/Chapter_17/CustomAppDomains/CustomAppDomains.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomAppDomains", "CustomAppDomains\CustomAppDomains.csproj", "{F3B48AC4-2EBB-4F8C-BEE0-C1B7DD3C1FA1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F3B48AC4-2EBB-4F8C-BEE0-C1B7DD3C1FA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F3B48AC4-2EBB-4F8C-BEE0-C1B7DD3C1FA1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F3B48AC4-2EBB-4F8C-BEE0-C1B7DD3C1FA1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F3B48AC4-2EBB-4F8C-BEE0-C1B7DD3C1FA1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_17/CustomAppDomains/CustomAppDomains/App.config b/Chapter_17/CustomAppDomains/CustomAppDomains/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_17/CustomAppDomains/CustomAppDomains/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_17/CustomAppDomains/CustomAppDomains/CustomAppDomains.csproj b/Chapter_17/CustomAppDomains/CustomAppDomains/CustomAppDomains.csproj new file mode 100644 index 0000000..89d267c --- /dev/null +++ b/Chapter_17/CustomAppDomains/CustomAppDomains/CustomAppDomains.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {F3B48AC4-2EBB-4F8C-BEE0-C1B7DD3C1FA1} + Exe + CustomAppDomains + CustomAppDomains + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_17/CustomAppDomains/CustomAppDomains/Program.cs b/Chapter_17/CustomAppDomains/CustomAppDomains/Program.cs new file mode 100644 index 0000000..4f558fc --- /dev/null +++ b/Chapter_17/CustomAppDomains/CustomAppDomains/Program.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.IO; + +namespace CustomAppDomains +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Custom App Domains *****\n"); + + // Show all loaded assemblies in default app domain. + AppDomain defaultAD = AppDomain.CurrentDomain; + defaultAD.ProcessExit += (o, s) => + { + Console.WriteLine("Default AD unloaded!"); + }; + + ListAllAssembliesInAppDomain(defaultAD); + + MakeNewAppDomain(); + Console.ReadLine(); + } + + #region Make new AD + static void MakeNewAppDomain() + { + // Make a new AppDomain in the current process. + AppDomain newAD = AppDomain.CreateDomain("SecondAppDomain"); + newAD.DomainUnload += (o, s) => + { + Console.WriteLine("The second app domain has been unloaded!"); + }; + + try + { + // Now load CarLibrary.dll into this new domain. + newAD.Load("CarLibrary"); + } + catch (FileNotFoundException ex) + { + Console.WriteLine(ex.Message); + } + + // List all assemblies. + ListAllAssembliesInAppDomain(newAD); + + // Now tear down this app domain. + AppDomain.Unload(newAD); + } + #endregion + + #region List ASMS in AD + static void ListAllAssembliesInAppDomain(AppDomain ad) + { + // Now get all loaded assemblies in the default app domain. + var loadedAssemblies = from a in ad.GetAssemblies() + orderby a.GetName().Name + select a; + + Console.WriteLine("***** Here are the assemblies loaded in {0} *****\n", + ad.FriendlyName); + foreach (var a in loadedAssemblies) + { + Console.WriteLine("-> Name: {0}", a.GetName().Name); + Console.WriteLine("-> Version: {0}\n", a.GetName().Version); + } + } + #endregion + } +} diff --git a/Chapter_17/CustomAppDomains/CustomAppDomains/Properties/AssemblyInfo.cs b/Chapter_17/CustomAppDomains/CustomAppDomains/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0be4be9 --- /dev/null +++ b/Chapter_17/CustomAppDomains/CustomAppDomains/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CustomAppDomains")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CustomAppDomains")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f3b48ac4-2ebb-4f8c-bee0-c1b7dd3c1fa1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp.sln b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp.sln new file mode 100644 index 0000000..779a4e5 --- /dev/null +++ b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DefaultAppDomainApp", "DefaultAppDomainApp\DefaultAppDomainApp.csproj", "{80772D15-287E-4DDD-8700-9DDA6D3473C7}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {80772D15-287E-4DDD-8700-9DDA6D3473C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {80772D15-287E-4DDD-8700-9DDA6D3473C7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {80772D15-287E-4DDD-8700-9DDA6D3473C7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {80772D15-287E-4DDD-8700-9DDA6D3473C7}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/App.config b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/DefaultAppDomainApp.csproj b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/DefaultAppDomainApp.csproj new file mode 100644 index 0000000..8cbda9b --- /dev/null +++ b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/DefaultAppDomainApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {80772D15-287E-4DDD-8700-9DDA6D3473C7} + Exe + DefaultAppDomainApp + DefaultAppDomainApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/Program.cs b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/Program.cs new file mode 100644 index 0000000..b24ed0a --- /dev/null +++ b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/Program.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Reflection; + +namespace DefaultAppDomainApp +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with the default app domain *****\n"); + InitDAD(); + DisplayDADStats(); + ListAllAssembliesInAppDomain(); + Console.ReadLine(); + } + + #region Display stats of default app domain + private static void DisplayDADStats() + { + // Get access to the app domain for the current thread. + + AppDomain defaultAD = AppDomain.CurrentDomain; + + // Print out various stats about this domain. + Console.WriteLine("Name of this domain: {0}", defaultAD.FriendlyName); + Console.WriteLine("ID of domain in this process: {0}", defaultAD.Id); + Console.WriteLine("Is this the default domain?: {0}", defaultAD.IsDefaultAppDomain()); + Console.WriteLine("Base directory of this domain: {0}", defaultAD.BaseDirectory); + } + #endregion + + #region List ASMS in app domain + static void ListAllAssembliesInAppDomain() + { + // Get access to the app domain for the current thread. + AppDomain defaultAD = AppDomain.CurrentDomain; + + // Now get all loaded assemblies in the default app domain. + var loadedAssemblies = from a in defaultAD.GetAssemblies() + orderby a.GetName().Name + select a; + + Console.WriteLine("***** Here are the assemblies loaded in {0} *****\n", + defaultAD.FriendlyName); + foreach (var a in loadedAssemblies) + { + Console.WriteLine("-> Name: {0}", a.GetName().Name); + Console.WriteLine("-> Version: {0}\n", a.GetName().Version); + } + } + #endregion + + static void InitDAD() + { + // This logic will print out the name of any assembly + // loaded into the applicaion domain, after it has been + // created. + AppDomain defaultAD = AppDomain.CurrentDomain; + defaultAD.AssemblyLoad += (o, s) => + { + Console.WriteLine("{0} has been loaded!", s.LoadedAssembly.GetName().Name); + }; + } + } +} diff --git a/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/Properties/AssemblyInfo.cs b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1770333 --- /dev/null +++ b/Chapter_17/DefaultAppDomainApp/DefaultAppDomainApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DefaultAppDomainApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DefaultAppDomainApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("80772d15-287e-4ddd-8700-9dda6d3473c7")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_17/ObjectContextApp/ObjectContextApp.sln b/Chapter_17/ObjectContextApp/ObjectContextApp.sln new file mode 100644 index 0000000..5eb2549 --- /dev/null +++ b/Chapter_17/ObjectContextApp/ObjectContextApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ObjectContextApp", "ObjectContextApp\ObjectContextApp.csproj", "{E61F117E-DDA9-4692-8A1B-9E496F76D918}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E61F117E-DDA9-4692-8A1B-9E496F76D918}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E61F117E-DDA9-4692-8A1B-9E496F76D918}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E61F117E-DDA9-4692-8A1B-9E496F76D918}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E61F117E-DDA9-4692-8A1B-9E496F76D918}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_17/ObjectContextApp/ObjectContextApp/App.config b/Chapter_17/ObjectContextApp/ObjectContextApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_17/ObjectContextApp/ObjectContextApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_17/ObjectContextApp/ObjectContextApp/ObjectContextApp.csproj b/Chapter_17/ObjectContextApp/ObjectContextApp/ObjectContextApp.csproj new file mode 100644 index 0000000..4d40fd7 --- /dev/null +++ b/Chapter_17/ObjectContextApp/ObjectContextApp/ObjectContextApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {E61F117E-DDA9-4692-8A1B-9E496F76D918} + Exe + ObjectContextApp + ObjectContextApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_17/ObjectContextApp/ObjectContextApp/Program.cs b/Chapter_17/ObjectContextApp/ObjectContextApp/Program.cs new file mode 100644 index 0000000..20e2f12 --- /dev/null +++ b/Chapter_17/ObjectContextApp/ObjectContextApp/Program.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using System.Runtime.Remoting.Contexts; // For Context type. +using System.Threading; // For Thread type. + +namespace ObjectContextApp +{ + #region Classes for illustration + // SportsCar has no special contextual + // needs and will be loaded into the + // default context of the app domain. + class SportsCar + { + public SportsCar() + { + // Get context information and print out context ID. + Context ctx = Thread.CurrentContext; + Console.WriteLine("{0} object in context {1}", + this.ToString(), ctx.ContextID); + foreach (IContextProperty itfCtxProp in ctx.ContextProperties) + Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name); + } + } + + // SportsCarTS demands to be loaded in + // a synchronization context. + [Synchronization] + class SportsCarTS : ContextBoundObject + { + public SportsCarTS() + { + // Get context information and print out context ID. + Context ctx = Thread.CurrentContext; + Console.WriteLine("{0} object in context {1}", + this.ToString(), ctx.ContextID); + foreach (IContextProperty itfCtxProp in ctx.ContextProperties) + Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name); + } + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Object Context *****\n"); + + // Objects will display contextual info upon creation. + SportsCar sport = new SportsCar(); + Console.WriteLine(); + + SportsCar sport2 = new SportsCar(); + Console.WriteLine(); + + SportsCarTS synchroSport = new SportsCarTS(); + Console.ReadLine(); + } + } +} diff --git a/Chapter_17/ObjectContextApp/ObjectContextApp/Properties/AssemblyInfo.cs b/Chapter_17/ObjectContextApp/ObjectContextApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..491c368 --- /dev/null +++ b/Chapter_17/ObjectContextApp/ObjectContextApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ObjectContextApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ObjectContextApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e61f117e-dda9-4692-8a1b-9e496f76d918")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_17/ProcessManipulator/ProcessManipulator.sln b/Chapter_17/ProcessManipulator/ProcessManipulator.sln new file mode 100644 index 0000000..76fc88c --- /dev/null +++ b/Chapter_17/ProcessManipulator/ProcessManipulator.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProcessManipulator", "ProcessManipulator\ProcessManipulator.csproj", "{08D2355E-8395-4883-95DF-B062FD520DD3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {08D2355E-8395-4883-95DF-B062FD520DD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {08D2355E-8395-4883-95DF-B062FD520DD3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {08D2355E-8395-4883-95DF-B062FD520DD3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {08D2355E-8395-4883-95DF-B062FD520DD3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_17/ProcessManipulator/ProcessManipulator/App.config b/Chapter_17/ProcessManipulator/ProcessManipulator/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_17/ProcessManipulator/ProcessManipulator/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_17/ProcessManipulator/ProcessManipulator/ProcessManipulator.csproj b/Chapter_17/ProcessManipulator/ProcessManipulator/ProcessManipulator.csproj new file mode 100644 index 0000000..01fa5d4 --- /dev/null +++ b/Chapter_17/ProcessManipulator/ProcessManipulator/ProcessManipulator.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {08D2355E-8395-4883-95DF-B062FD520DD3} + Exe + ProcessManipulator + ProcessManipulator + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_17/ProcessManipulator/ProcessManipulator/Program.cs b/Chapter_17/ProcessManipulator/ProcessManipulator/Program.cs new file mode 100644 index 0000000..bf5ef75 --- /dev/null +++ b/Chapter_17/ProcessManipulator/ProcessManipulator/Program.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Diagnostics; + +namespace ProcessManipulator +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Processes *****\n"); + ListAllRunningProcesses(); + + // Prompt user for a PID and print out the set of active threads. + Console.WriteLine("***** Enter PID of process to investigate *****"); + Console.Write("PID: "); + string pID = Console.ReadLine(); + int theProcID = int.Parse(pID); + + EnumThreadsForPid(theProcID); + EnumModsForPid(theProcID); + StartAndKillProcess(); + Console.ReadLine(); + } + + #region List all processes + + static void ListAllRunningProcesses() + { + // Get all the processes on the local machine, ordered by + // PID. + var runningProcs = from proc in Process.GetProcesses(".") orderby proc.Id select proc; + + // Print out PID and name of each process. + foreach (var p in runningProcs) + { + string info = $"-> PID: {p.Id}\tName: {p.ProcessName}"; + Console.WriteLine(info); + } + Console.WriteLine("************************************\n"); + } + + #endregion + + #region Get process by PID + + // If there is no process with the PID of 987, a runtime exception will be thrown. + static void GetSpecificProcess() + { + Process theProc = null; + try + { + theProc = Process.GetProcessById(987); + } + catch (ArgumentException ex) + { + Console.WriteLine(ex.Message); + } + } + + #endregion + + #region Enum threads in process + + static void EnumThreadsForPid(int pID) + { + Process theProc = null; + try + { + theProc = Process.GetProcessById(pID); + } + catch (ArgumentException ex) + { + Console.WriteLine(ex.Message); + return; + } + + // List out stats for each thread in the specified process. + Console.WriteLine("Here are the threads used by: {0}", theProc.ProcessName); + ProcessThreadCollection theThreads = theProc.Threads; + + foreach (ProcessThread pt in theThreads) + { + string info = + $"-> Thread ID: {pt.Id}\tStart Time: {pt.StartTime.ToShortTimeString()}\tPriority: {pt.PriorityLevel}"; + Console.WriteLine(info); + } + Console.WriteLine("************************************\n"); + } + + #endregion + + #region Enum mods in process + + static void EnumModsForPid(int pID) + { + Process theProc = null; + try + { + theProc = Process.GetProcessById(pID); + } + catch (ArgumentException ex) + { + Console.WriteLine(ex.Message); + return; + } + + Console.WriteLine("Here are the loaded modules for: {0}", theProc.ProcessName); + ProcessModuleCollection theMods = theProc.Modules; + foreach (ProcessModule pm in theMods) + { + string info = $"-> Mod Name: {pm.ModuleName}"; + Console.WriteLine(info); + } + Console.WriteLine("************************************\n"); + } + + #endregion + + #region Start and Kill process + + static void StartAndKillProcess() + { + Process ffProc = null; + + // Launch Internet Explorer, and go to facebook! + try + { + ProcessStartInfo startInfo = + new ProcessStartInfo("FireFox.exe", "www.facebook.com") + { + WindowStyle = ProcessWindowStyle.Maximized + }; + + ffProc = Process.Start(startInfo); + } + catch (InvalidOperationException ex) + { + Console.WriteLine(ex.Message); + } + + Console.Write("--> Hit enter to kill {0}...", ffProc.ProcessName); + Console.ReadLine(); + + // Kill the iexplore.exe process. + try + { + ffProc.Kill(); + } + catch (InvalidOperationException ex) + { + Console.WriteLine(ex.Message); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/Chapter_17/ProcessManipulator/ProcessManipulator/Properties/AssemblyInfo.cs b/Chapter_17/ProcessManipulator/ProcessManipulator/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..83b5736 --- /dev/null +++ b/Chapter_17/ProcessManipulator/ProcessManipulator/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ProcessManipulator")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ProcessManipulator")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("08d2355e-8395-4883-95df-b062fd520dd3")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_18/CILCars/CILCars.il b/Chapter_18/CILCars/CILCars.il new file mode 100644 index 0000000..f6451c2 --- /dev/null +++ b/Chapter_18/CILCars/CILCars.il @@ -0,0 +1,96 @@ +// Reference mscorlib.dll and +// System.Windows.Forms.dll. +.assembly extern mscorlib +{ + .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) + .ver 4:0:0:0 +} +.assembly extern System.Windows.Forms +{ + .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) + .ver 4:0:0:0 +} + +// Define the single-file assembly. +.assembly CILCars +{ + .hash algorithm 0x00008004 + .ver 1:0:0:0 +} +.module CILCars.dll + +// Implementation of CILCars.CILCar type. +.namespace CILCars +{ + .class public auto ansi beforefieldinit CILCar + extends [mscorlib]System.Object + { + // The field data of the CILCar. + .field public string petName + .field public int32 currSpeed + + // The custom constructor simply allows the caller + // to assign the field data. + .method public hidebysig specialname rtspecialname + instance void .ctor(int32 c, string p) cil managed + { + .maxstack 8 + + // Load first arg onto the stack and call base class ctor. + ldarg.0 // "this" object, not the int32! + call instance void [mscorlib]System.Object::.ctor() + + // Now load first and second args onto the stack. + ldarg.0 // "this" object + ldarg.1 // int32 arg + + // Store topmost stack (int 32) member in currSpeed field. + stfld int32 CILCars.CILCar::currSpeed + + // Load string arg and store in petName field. + ldarg.0 // "this" object + ldarg.2 // string arg + stfld string CILCars.CILCar::petName + ret + } + } + +.class public auto ansi beforefieldinit CILCarInfo + extends [mscorlib]System.Object +{ + .method public hidebysig static void + Display(class CILCars.CILCar c) cil managed + { + .maxstack 8 + + // We need a local string variable. + .locals init ([0] string caption) + + // Load string and the incoming CILCar onto the stack. + ldstr "{0}'s speed is:" + ldarg.0 + + // Now place the value of the CILCar's petName on the + // stack and call the static String.Format() method. + ldfld string CILCars.CILCar::petName + call string [mscorlib]System.String::Format(string, object) + stloc.0 + + // Now load the value of the currSpeed field and get its string + // representation (note call to ToString()). + ldarg.0 + ldflda int32 CILCars.CILCar::currSpeed + call instance string [mscorlib]System.Int32::ToString() + ldloc.0 + + // Now call the MessageBox.Show() method with loaded values. + call valuetype [System.Windows.Forms] + System.Windows.Forms.DialogResult + [System.Windows.Forms] + System.Windows.Forms.MessageBox::Show(string, string) + pop + ret + } +} + +} diff --git a/Chapter_18/CILCars/CarClient.il b/Chapter_18/CILCars/CarClient.il new file mode 100644 index 0000000..60b9b92 --- /dev/null +++ b/Chapter_18/CILCars/CarClient.il @@ -0,0 +1,53 @@ +// External assembly refs. +.assembly extern mscorlib +{ + .publickeytoken = (B7 7A 5C 56 19 34 E0 89) + .ver 4:0:0:0 +} +.assembly extern CILCars +{ + .ver 1:0:0:0 +} + +// Our executable assembly. +.assembly CarClient +{ + .hash algorithm 0x00008004 + .ver 1:0:0:0 +} +.module CarClient.exe + +// Implementation of Program type. +.namespace CarClient +{ + .class private auto ansi beforefieldinit Program + extends [mscorlib]System.Object + { + .method private hidebysig static void + Main(string[] args) cil managed + { + // Marks the entry point of the *.exe. + .entrypoint + .maxstack 8 + + // Declare a local CILCar variable and push + // values onto the stack for ctor call. + .locals init ([0] class + [CILCars]CILCars.CILCar myCilCar) + ldc.i4 55 + ldstr "Junior" + + // Make new CilCar; store and load reference. + newobj instance void + [CILCars]CILCars.CILCar::.ctor(int32, string) + stloc.0 + ldloc.0 + + // Call Display() and pass in topmost value on stack. + call void [CILCars] + CILCars.CILCarInfo::Display( + class [CILCars]CILCars.CILCar) + ret + } + } +} diff --git a/Chapter_18/CilTypes/CilTypes.il b/Chapter_18/CilTypes/CilTypes.il new file mode 100644 index 0000000..672890d --- /dev/null +++ b/Chapter_18/CilTypes/CilTypes.il @@ -0,0 +1,81 @@ +// List of referenced assemblies. +.assembly extern mscorlib +{ + .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) + .ver 2:0:0:0 +} + +// Our assembly +.assembly CILTypes +{ + .ver 1:0:0:0 +} +// The module of our single-file assembly. +.module CILTypes.dll + +// Our assembly has a single namespace. +.namespace MyNamespace +{ + // An interface definition. + .class public interface IMyInterface {} + + .class public MyBaseClass + { + // Some field data. + .field private string stringField + .field private int32 intField + + // A custom constructor. + .method public hidebysig specialname rtspecialname + instance void .ctor(string s, int32 i) cil managed + { + // TODO: Add implementation code... + } + + // Property syntax. + .method public hidebysig specialname + instance string get_TheString() cil managed + { + // TODO: Add implementation code... + } + + .method public hidebysig specialname + instance void set_TheString(string 'value') cil managed + { + // TODO: Add implementation code... + } + + .property instance string TheString() + { + .get instance string + MyNamespace.MyBaseClass::get_TheString() + .set instance void + MyNamespace. MyBaseClass::set_TheString(string) + } + + } + + // MyDerivedClass now implements IAmAnInterface. + .class public MyDerivedClass + extends MyNamespace.MyBaseClass + implements MyNamespace.IMyInterface {} + + // Shorthand notation for declaring a structure. + .class public sealed value MyStruct{} + + // Enum shorthand. + .class public sealed enum MyEnum + { + .field public static literal valuetype + MyNamespace.MyEnum A = int32(0) + .field public static literal valuetype + MyNamespace.MyEnum B = int32(1) + .field public static literal valuetype + MyNamespace.MyEnum C = int32(2) + } + + // A custom generic class with 1 type parameter. + .class public MyGenericClass`1{} +} + + diff --git a/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder.sln b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder.sln new file mode 100644 index 0000000..aca96be --- /dev/null +++ b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DynamicAsmBuilder", "DynamicAsmBuilder\DynamicAsmBuilder.csproj", "{16A7C997-4292-45FF-A1ED-5028F2F945C3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {16A7C997-4292-45FF-A1ED-5028F2F945C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {16A7C997-4292-45FF-A1ED-5028F2F945C3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {16A7C997-4292-45FF-A1ED-5028F2F945C3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {16A7C997-4292-45FF-A1ED-5028F2F945C3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/App.config b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/DynamicAsmBuilder.csproj b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/DynamicAsmBuilder.csproj new file mode 100644 index 0000000..6563963 --- /dev/null +++ b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/DynamicAsmBuilder.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {16A7C997-4292-45FF-A1ED-5028F2F945C3} + Exe + DynamicAsmBuilder + DynamicAsmBuilder + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/Program.cs b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/Program.cs new file mode 100644 index 0000000..b4d3a67 --- /dev/null +++ b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/Program.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Reflection; +using System.Reflection.Emit; +using System.Threading; + +namespace DynamicAsmBuilder +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** The Amazing Dynamic Assembly Builder App *****"); + // Get the application domain for the current thread. + AppDomain curAppDomain = Thread.GetDomain(); + + // Create the dynamic assembly using our helper f(x). + CreateMyAsm(curAppDomain); + Console.WriteLine("-> Finished creating MyAssembly.dll."); + + // Now load the new assembly from file. + Console.WriteLine("-> Loading MyAssembly.dll from file."); + Assembly a = Assembly.Load("MyAssembly"); + + // Get the HelloWorld type. + Type hello = a.GetType("MyAssembly.HelloWorld"); + + // Create HelloWorld object and call the correct ctor. + Console.Write("-> Enter message to pass HelloWorld class: "); + string msg = Console.ReadLine(); + object[] ctorArgs = new object[1]; + ctorArgs[0] = msg; + object obj = Activator.CreateInstance(hello, ctorArgs); + + // Call SayHello and show returned string. + Console.WriteLine("-> Calling SayHello() via late binding."); + MethodInfo mi = hello.GetMethod("SayHello"); + mi.Invoke(obj, null); + + // Invoke method. + mi = hello.GetMethod("GetMsg"); + Console.WriteLine(mi.Invoke(obj, null)); + + } + + #region Create Assembly + // The caller sends in an AppDomain type. + public static void CreateMyAsm(AppDomain curAppDomain) + { + // Establish general assembly characteristics. + AssemblyName assemblyName = new AssemblyName + { + Name = "MyAssembly", + Version = new Version("1.0.0.0") + }; + + // Create new assembly within the current AppDomain. + AssemblyBuilder assembly = + curAppDomain.DefineDynamicAssembly(assemblyName,AssemblyBuilderAccess.Save); + + // Given that we are building a single-file + // assembly, the name of the module is the same as the assembly. + ModuleBuilder module = + assembly.DefineDynamicModule("MyAssembly", "MyAssembly.dll"); + + // Define a public class named "HelloWorld". + TypeBuilder helloWorldClass = module.DefineType("MyAssembly.HelloWorld", + TypeAttributes.Public); + + // Define a private String member variable named "theMessage". + FieldBuilder msgField = + helloWorldClass.DefineField("theMessage", Type.GetType("System.String"), + attributes: FieldAttributes.Private); + + // Create the custom ctor. + Type[] constructorArgs = new Type[1]; + constructorArgs[0] = typeof(string); + ConstructorBuilder constructor = + helloWorldClass.DefineConstructor(MethodAttributes.Public, + CallingConventions.Standard, + constructorArgs); + ILGenerator constructorIL = constructor.GetILGenerator(); + constructorIL.Emit(OpCodes.Ldarg_0); + Type objectClass = typeof(object); + ConstructorInfo superConstructor = + objectClass.GetConstructor(new Type[0]); + constructorIL.Emit(OpCodes.Call, superConstructor); + constructorIL.Emit(OpCodes.Ldarg_0); + constructorIL.Emit(OpCodes.Ldarg_1); + constructorIL.Emit(OpCodes.Stfld, msgField); + constructorIL.Emit(OpCodes.Ret); + + // Create the default ctor. + helloWorldClass.DefineDefaultConstructor(MethodAttributes.Public); + // Now create the GetMsg() method. + MethodBuilder getMsgMethod = + helloWorldClass.DefineMethod("GetMsg", MethodAttributes.Public, + typeof(string), null); + ILGenerator methodIL = getMsgMethod.GetILGenerator(); + methodIL.Emit(OpCodes.Ldarg_0); + methodIL.Emit(OpCodes.Ldfld, msgField); + methodIL.Emit(OpCodes.Ret); + + // Create the SayHello method. + MethodBuilder sayHiMethod = + helloWorldClass.DefineMethod("SayHello", + MethodAttributes.Public, null, null); + methodIL = sayHiMethod.GetILGenerator(); + methodIL.EmitWriteLine("Hello from the HelloWorld class!"); + methodIL.Emit(OpCodes.Ret); + + // "Bake" the class HelloWorld. + // (Baking is the formal term for emitting the type.) + helloWorldClass.CreateType(); + + // (Optionally) save the assembly to file. + assembly.Save("MyAssembly.dll"); + } + + #endregion + + } +} diff --git a/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/Properties/AssemblyInfo.cs b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..61bceb0 --- /dev/null +++ b/Chapter_18/DynamicAsmBuilder/DynamicAsmBuilder/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DynamicAsmBuilder")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DynamicAsmBuilder")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("16a7c997-4292-45ff-a1ed-5028f2f945c3")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_18/RoundTrip/HelloProgram.cs b/Chapter_18/RoundTrip/HelloProgram.cs new file mode 100644 index 0000000..6f27ce1 --- /dev/null +++ b/Chapter_18/RoundTrip/HelloProgram.cs @@ -0,0 +1,13 @@ +// A simple C# console app. +using System; + +// Note that we are not wrapping our class in a namespace, +// to help simplify the generated CIL code. +class Program +{ + static void Main(string[] args) + { + Console.WriteLine("Hello CIL code!"); + Console.ReadLine(); + } +} \ No newline at end of file diff --git a/Chapter_18/RoundTrip/HelloProgram.il b/Chapter_18/RoundTrip/HelloProgram.il new file mode 100644 index 0000000..287f45f --- /dev/null +++ b/Chapter_18/RoundTrip/HelloProgram.il @@ -0,0 +1,78 @@ + +// Microsoft (R) .NET Framework IL Disassembler. Version 4.7.2046.0 +// Copyright (c) Microsoft Corporation. All rights reserved. + + + +// Metadata version: v4.0.30319 +.assembly extern mscorlib +{ + .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. + .ver 4:0:0:0 +} +// Bring in Windows Forms library. +.assembly extern System.Windows.Forms +{ + .publickeytoken = (B7 7A 5C 56 19 34 E0 89) + .ver 4:0:0:0 +} + +.assembly HelloProgram +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) + .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx + 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. + + // --- The following custom attribute is added automatically, do not uncomment ------- + // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 07 01 00 00 00 00 ) + + .hash algorithm 0x00008004 + .ver 0:0:0:0 +} +.module HelloProgram.exe +// MVID: {6BB46B0A-3AB3-402A-9C56-9371568CF365} +.imagebase 0x00400000 +.file alignment 0x00000200 +.stackreserve 0x00100000 +.subsystem 0x0003 // WINDOWS_CUI +.corflags 0x00000001 // ILONLY +// Image base: 0x0000017383590000 + + +// =============== CLASS MEMBERS DECLARATION =================== + +.class private auto ansi beforefieldinit Program + extends [mscorlib]System.Object +{ + .method private hidebysig static void Main(string[] args) cil managed + { + .entrypoint + // Code size 19 (0x13) + .maxstack 8 + ldstr "CIL is way cool" + call valuetype [System.Windows.Forms] + System.Windows.Forms.DialogResult + [System.Windows.Forms] + System.Windows.Forms.MessageBox::Show(string) + pop + ret + } // end of method Program::Main + + .method public hidebysig specialname rtspecialname + instance void .ctor() cil managed + { + // Code size 8 (0x8) + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0006: nop + IL_0007: ret + } // end of method Program::.ctor + +} // end of class Program + + +// ============================================================= + +// *********** DISASSEMBLY COMPLETE *********************** +// WARNING: Created Win32 resource file C:\GitHub\procsharp\Code\Updated\Chapter_18\RoundTrip\HelloProgram.res diff --git a/Chapter_18/RoundTrip/HelloProgram.res b/Chapter_18/RoundTrip/HelloProgram.res new file mode 100644 index 0000000..180303b Binary files /dev/null and b/Chapter_18/RoundTrip/HelloProgram.res differ diff --git a/Chapter_19/AddWithThreads/AddWithThreads.sln b/Chapter_19/AddWithThreads/AddWithThreads.sln new file mode 100644 index 0000000..7718f6d --- /dev/null +++ b/Chapter_19/AddWithThreads/AddWithThreads.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AddWithThreads", "AddWithThreads\AddWithThreads.csproj", "{A22D282B-10A4-417E-8A2B-6DB8B4895C30}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A22D282B-10A4-417E-8A2B-6DB8B4895C30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A22D282B-10A4-417E-8A2B-6DB8B4895C30}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A22D282B-10A4-417E-8A2B-6DB8B4895C30}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A22D282B-10A4-417E-8A2B-6DB8B4895C30}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/AddWithThreads/AddWithThreads/AddWithThreads.csproj b/Chapter_19/AddWithThreads/AddWithThreads/AddWithThreads.csproj new file mode 100644 index 0000000..245f8e7 --- /dev/null +++ b/Chapter_19/AddWithThreads/AddWithThreads/AddWithThreads.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {A22D282B-10A4-417E-8A2B-6DB8B4895C30} + Exe + AddWithThreads + AddWithThreads + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/AddWithThreads/AddWithThreads/App.config b/Chapter_19/AddWithThreads/AddWithThreads/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/AddWithThreads/AddWithThreads/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/AddWithThreads/AddWithThreads/Program.cs b/Chapter_19/AddWithThreads/AddWithThreads/Program.cs new file mode 100644 index 0000000..ed7e81a --- /dev/null +++ b/Chapter_19/AddWithThreads/AddWithThreads/Program.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace AddWithThreads +{ + #region The AddParams class + class AddParams + { + public int a, b; + + public AddParams(int numb1, int numb2) + { + a = numb1; + b = numb2; + } + } + #endregion + + class Program + { + private static AutoResetEvent waitHandle = new AutoResetEvent(false); + + static void Main(string[] args) + { + Console.WriteLine("***** Adding with Thread objects *****"); + Console.WriteLine("ID of thread in Main(): {0}", + Thread.CurrentThread.ManagedThreadId); + + AddParams ap = new AddParams(10, 10); + Thread t = new Thread(new ParameterizedThreadStart(Add)); + t.Start(ap); + + // Wait here until you are notified + waitHandle.WaitOne(); + + Console.WriteLine("Other thread is done!"); + Console.ReadLine(); + } + + static void Add(object data) + { + if (data is AddParams) + { + Console.WriteLine("ID of thread in Add(): {0}", + Thread.CurrentThread.ManagedThreadId); + + AddParams ap = (AddParams)data; + Console.WriteLine("{0} + {1} is {2}", + ap.a, ap.b, ap.a + ap.b); + + // Tell other thread we are done. + waitHandle.Set(); + } + } + } +} diff --git a/Chapter_19/AddWithThreads/AddWithThreads/Properties/AssemblyInfo.cs b/Chapter_19/AddWithThreads/AddWithThreads/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..16aae4d --- /dev/null +++ b/Chapter_19/AddWithThreads/AddWithThreads/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AddWithThreads")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AddWithThreads")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a22d282b-10a4-417e-8a2b-6db8b4895c30")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate.sln b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate.sln new file mode 100644 index 0000000..3172d04 --- /dev/null +++ b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncCallbackDelegate", "AsyncCallbackDelegate\AsyncCallbackDelegate.csproj", "{6B395ECD-A7AC-4F92-8BF9-A8F094E2C05B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6B395ECD-A7AC-4F92-8BF9-A8F094E2C05B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6B395ECD-A7AC-4F92-8BF9-A8F094E2C05B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6B395ECD-A7AC-4F92-8BF9-A8F094E2C05B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6B395ECD-A7AC-4F92-8BF9-A8F094E2C05B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/App.config b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/AsyncCallbackDelegate.csproj b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/AsyncCallbackDelegate.csproj new file mode 100644 index 0000000..7ea0967 --- /dev/null +++ b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/AsyncCallbackDelegate.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {6B395ECD-A7AC-4F92-8BF9-A8F094E2C05B} + Exe + AsyncCallbackDelegate + AsyncCallbackDelegate + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/Program.cs b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/Program.cs new file mode 100644 index 0000000..008a2ee --- /dev/null +++ b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/Program.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Runtime.Remoting.Messaging; + +namespace AsyncCallbackDelegate +{ + public delegate int BinaryOp(int x, int y); + + class Program + { + private static bool isDone = false; + + static void Main(string[] args) + { + Console.WriteLine("***** AsyncCallbackDelegate Example *****"); + Console.WriteLine("Main() invoked on thread {0}.", + Thread.CurrentThread.ManagedThreadId); + + BinaryOp b = new BinaryOp(Add); + IAsyncResult ar = b.BeginInvoke(10, 10, + new AsyncCallback(AddComplete), + "Main() thanks you for adding these numbers."); + + // Assume other work is performed here... + while (!isDone) + { + Thread.Sleep(1000); + Console.WriteLine("Working...."); + } + + Console.ReadLine(); + } + + #region Target for AsyncCallback delegate + // Don't forget to add a 'using' directive for + // System.Runtime.Remoting.Messaging! + static void AddComplete(IAsyncResult iar) + { + Console.WriteLine("AddComplete() invoked on thread {0}.", + Thread.CurrentThread.ManagedThreadId); + Console.WriteLine("Your addition is complete"); + + // Now get the result. + AsyncResult ar = (AsyncResult)iar; + BinaryOp b = (BinaryOp)ar.AsyncDelegate; + Console.WriteLine("10 + 10 is {0}.", b.EndInvoke(iar)); + + // Retrieve the informational object and cast it to string. + string msg = (string)iar.AsyncState; + Console.WriteLine(msg); + + isDone = true; + } + + #endregion + + #region Target for BinaryOp delegate + static int Add(int x, int y) + { + Console.WriteLine("Add() invoked on thread {0}.", + Thread.CurrentThread.ManagedThreadId); + Thread.Sleep(5000); + return x + y; + } + #endregion + } +} + diff --git a/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/Properties/AssemblyInfo.cs b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..477e642 --- /dev/null +++ b/Chapter_19/AsyncCallbackDelegate/AsyncCallbackDelegate/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AsyncCallbackDelegate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AsyncCallbackDelegate")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6b395ecd-a7ac-4f92-8bf9-a8f094e2c05b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/AsyncDelegate/AsyncDelegate.sln b/Chapter_19/AsyncDelegate/AsyncDelegate.sln new file mode 100644 index 0000000..a57a18e --- /dev/null +++ b/Chapter_19/AsyncDelegate/AsyncDelegate.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncDelegate", "AsyncDelegate\AsyncDelegate.csproj", "{7D40B0A9-8BD1-4745-9CC1-481509B28387}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7D40B0A9-8BD1-4745-9CC1-481509B28387}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7D40B0A9-8BD1-4745-9CC1-481509B28387}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7D40B0A9-8BD1-4745-9CC1-481509B28387}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7D40B0A9-8BD1-4745-9CC1-481509B28387}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/AsyncDelegate/AsyncDelegate/App.config b/Chapter_19/AsyncDelegate/AsyncDelegate/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/AsyncDelegate/AsyncDelegate/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/AsyncDelegate/AsyncDelegate/AsyncDelegate.csproj b/Chapter_19/AsyncDelegate/AsyncDelegate/AsyncDelegate.csproj new file mode 100644 index 0000000..16db123 --- /dev/null +++ b/Chapter_19/AsyncDelegate/AsyncDelegate/AsyncDelegate.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {7D40B0A9-8BD1-4745-9CC1-481509B28387} + Exe + AsyncDelegate + AsyncDelegate + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/AsyncDelegate/AsyncDelegate/Program.cs b/Chapter_19/AsyncDelegate/AsyncDelegate/Program.cs new file mode 100644 index 0000000..47dd7f5 --- /dev/null +++ b/Chapter_19/AsyncDelegate/AsyncDelegate/Program.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace AsyncDelegate +{ + public delegate int BinaryOp(int x, int y); + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Async Delegate Invocation *****"); + + // Print out the ID of the executing thread. + Console.WriteLine("Main() invoked on thread {0}.", + Thread.CurrentThread.ManagedThreadId); + + BinaryOp b = new BinaryOp(Add); + IAsyncResult ar = b.BeginInvoke(10, 10, null, null); + + // This message will keep printing until + // the Add() method is finished. + while (!ar.IsCompleted) + { + Console.WriteLine("Doing more work in Main()!"); + Thread.Sleep(1000); + } + + // Now we know the Add() method is complete. + int answer = b.EndInvoke(ar); + + Console.WriteLine("10 + 10 is {0}.", answer); + Console.ReadLine(); + } + + static int Add(int x, int y) + { + // Print out the ID of the executing thread. + Console.WriteLine("Add() invoked on thread {0}.", + Thread.CurrentThread.ManagedThreadId); + + // Pause to simulate a lengthy operation. + Thread.Sleep(5000); + return x + y; + } + } +} + diff --git a/Chapter_19/AsyncDelegate/AsyncDelegate/Properties/AssemblyInfo.cs b/Chapter_19/AsyncDelegate/AsyncDelegate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6e96019 --- /dev/null +++ b/Chapter_19/AsyncDelegate/AsyncDelegate/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AsyncDelegate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AsyncDelegate")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7d40b0a9-8bd1-4745-9cc1-481509b28387")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach.sln b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach.sln new file mode 100644 index 0000000..5e5f2d0 --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataParallelismWithForEach", "DataParallelismWithForEach\DataParallelismWithForEach.csproj", "{52BB4400-1805-4E0D-9FD9-2B9FCDAB6AE0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {52BB4400-1805-4E0D-9FD9-2B9FCDAB6AE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {52BB4400-1805-4E0D-9FD9-2B9FCDAB6AE0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {52BB4400-1805-4E0D-9FD9-2B9FCDAB6AE0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {52BB4400-1805-4E0D-9FD9-2B9FCDAB6AE0}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.config b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.xaml b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.xaml new file mode 100644 index 0000000..08bc186 --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.xaml.cs b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.xaml.cs new file mode 100644 index 0000000..6f33991 --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace DataParallelismWithForEach +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/DataParallelismWithForEach.csproj b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/DataParallelismWithForEach.csproj new file mode 100644 index 0000000..4fdca8d --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/DataParallelismWithForEach.csproj @@ -0,0 +1,98 @@ + + + + + Debug + AnyCPU + {52BB4400-1805-4E0D-9FD9-2B9FCDAB6AE0} + WinExe + DataParallelismWithForEach + DataParallelismWithForEach + v4.7 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + \ No newline at end of file diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/MainWindow.xaml b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/MainWindow.xaml new file mode 100644 index 0000000..5c24517 --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/MainWindow.xaml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/MainWindow.xaml.cs b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/MainWindow.xaml.cs new file mode 100644 index 0000000..70ac31f --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/MainWindow.xaml.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; + +namespace DataParallelismWithForEach +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : Window + { + // New Window level variable. + private CancellationTokenSource cancelToken = new CancellationTokenSource(); + + public MainWindow() + { + InitializeComponent(); + } + + private void cmdCancel_Click(object sender, RoutedEventArgs e) + { + cancelToken.Cancel(); + } + + private void cmdProcess_Click(object sender, RoutedEventArgs e) + { + // Start a new "task" to process the files. + Task.Factory.StartNew(() => ProcessFiles()); + } + + private void ProcessFiles() + { + // Use ParallelOptions instance to store the CancellationToken + ParallelOptions parOpts = new ParallelOptions + { + CancellationToken = cancelToken.Token, + MaxDegreeOfParallelism = System.Environment.ProcessorCount + }; + + // Load up all *.jpg files, and make a new folder for the modified data. + string[] files = Directory.GetFiles(@".\TestPictures", "*.jpg", + SearchOption.AllDirectories); + string newDir = @".\ModifiedPictures"; + Directory.CreateDirectory(newDir); + + try + { + // Process the image data in a parallel manner! + Parallel.ForEach(files, parOpts, currentFile => + { + parOpts.CancellationToken.ThrowIfCancellationRequested(); + + string filename = Path.GetFileName(currentFile); + using (Bitmap bitmap = new Bitmap(currentFile)) + { + bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); + bitmap.Save(Path.Combine(newDir, filename)); + + //this.Title = $"Processing {filename} on thread {Thread.CurrentThread.ManagedThreadId}"; + + // We need to ensure that the secondary threads access controls + // created on primary thread in a safe manner. + this.Dispatcher.Invoke((Action) delegate + { + this.Title = + $"Processing {filename} on thread {Thread.CurrentThread.ManagedThreadId}"; + }); + } + } + ); + this.Dispatcher.Invoke((Action) delegate { this.Title = "Done!"; }); + } + catch (OperationCanceledException ex) + { + this.Dispatcher.Invoke((Action) delegate { this.Title = ex.Message; }); + } + } + } +} \ No newline at end of file diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/AssemblyInfo.cs b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e0c1529 --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/AssemblyInfo.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DataParallelismWithForEach")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DataParallelismWithForEach")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +//In order to begin building localizable applications, set +//CultureYouAreCodingWith in your .csproj file +//inside a . For example, if you are using US english +//in your source files, set the to en-US. Then uncomment +//the NeutralResourceLanguage attribute below. Update the "en-US" in +//the line below to match the UICulture setting in the project file. + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] + + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Resources.Designer.cs b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Resources.Designer.cs new file mode 100644 index 0000000..9a5319c --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DataParallelismWithForEach.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DataParallelismWithForEach.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Resources.resx b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Settings.Designer.cs b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Settings.Designer.cs new file mode 100644 index 0000000..c922add --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DataParallelismWithForEach.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Settings.settings b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/Chapter_19/DataParallelismWithForEach/DataParallelismWithForEach/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync.sln b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync.sln new file mode 100644 index 0000000..fab1518 --- /dev/null +++ b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FunWithCSharpAsync", "FunWithCSharpAsync\FunWithCSharpAsync.csproj", "{B0C2549E-0CDA-4EE4-B97F-3EFB60BC4807}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C2549E-0CDA-4EE4-B97F-3EFB60BC4807}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C2549E-0CDA-4EE4-B97F-3EFB60BC4807}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C2549E-0CDA-4EE4-B97F-3EFB60BC4807}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C2549E-0CDA-4EE4-B97F-3EFB60BC4807}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/App.config b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/FunWithCSharpAsync.csproj b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/FunWithCSharpAsync.csproj new file mode 100644 index 0000000..910df99 --- /dev/null +++ b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/FunWithCSharpAsync.csproj @@ -0,0 +1,58 @@ + + + + + Debug + AnyCPU + {B0C2549E-0CDA-4EE4-B97F-3EFB60BC4807} + Exe + FunWithCSharpAsync + FunWithCSharpAsync + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 7.1 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 7.1 + + + + + + ..\packages\System.Threading.Tasks.Extensions.4.3.0\lib\portable-net45+win8+wp8+wpa81\System.Threading.Tasks.Extensions.dll + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/Program.cs b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/Program.cs new file mode 100644 index 0000000..0867bef --- /dev/null +++ b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/Program.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace FunWithCSharpAsync +{ + class Program + { + static async Task Main(string[] args) + { + Console.WriteLine(" Fun With Async ===>"); + //This is to prompt Visual Studio to upgrade project to C# 7.1 + List l = default; + //Console.WriteLine(DoWork()); + string message = await DoWorkAsync(); + Console.WriteLine(message); + await MethodReturningVoidAsync(); + Console.WriteLine("Void method complete"); + await MethodReturningVoidAsync(); + await MethodWithProblems(7, -5); + await MethodWithProblemsFixed(7, -5); + Console.WriteLine("Completed"); + Console.ReadLine(); + } + + static string DoWork() + { + Thread.Sleep(5_000); + return "Done with work!"; + } + + static async Task DoWorkAsync() + { + return await Task.Run(() => + { + Thread.Sleep(5_000); + return "Done with work!"; + }); + } + + static async Task MethodReturningVoidAsync() + { + await Task.Run(() => + { + /* Do some work here... */ + Thread.Sleep(4_000); + }); + Console.WriteLine("Void method completed"); + } + + static async Task MutliAwaits() + { + await Task.Run(() => { Thread.Sleep(2_000); }); + Console.WriteLine("Done with first task!"); + + await Task.Run(() => { Thread.Sleep(2_000); }); + Console.WriteLine("Done with second task!"); + + await Task.Run(() => { Thread.Sleep(2_000); }); + Console.WriteLine("Done with third task!"); + } + + static async Task MethodWithTryCatch() + { + try + { + //Do some work + return "Hello"; + } + catch (Exception ex) + { + await LogTheErrors(); + throw; + } + finally + { + await DoMagicCleanUp(); + } + } + + private static Task DoMagicCleanUp() + { + throw new NotImplementedException(); + } + + private static Task LogTheErrors() + { + throw new NotImplementedException(); + } + + static async Task MethodWithProblems(int firstParam, int secondParam) + { + Console.WriteLine("Enter"); + await Task.Run(() => + { + //Call long running method + Thread.Sleep(4_000); + Console.WriteLine("First Complete"); + //Call another long running method that fails because + //the second parameter is out of range + Console.WriteLine("Something bad happened"); + }); + } + + static async Task MethodWithProblemsFixed(int firstParam, int secondParam) + { + Console.WriteLine("Enter"); + if (secondParam < 0) + { + Console.WriteLine("Bad data"); + return; + } + + actualImplementation(); + + async Task actualImplementation() + { + await Task.Run(() => + { + //Call long running method + Thread.Sleep(4_000); + Console.WriteLine("First Complete"); + //Call another long running method that fails because + //the second parameter is out of range + Console.WriteLine("Something bad happened"); + }); + } + } + + static async ValueTask ReturnAnInt() + { + await Task.Delay(1_000); + return 5; + } + } +} \ No newline at end of file diff --git a/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/Properties/AssemblyInfo.cs b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..11a7b8f --- /dev/null +++ b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("FunWithCSharpAsync")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FunWithCSharpAsync")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b0c2549e-0cda-4ee4-b97f-3efb60bc4807")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/packages.config b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/packages.config new file mode 100644 index 0000000..581a850 --- /dev/null +++ b/Chapter_19/FunWithCSharpAsync/FunWithCSharpAsync/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting.sln b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting.sln new file mode 100644 index 0000000..351a9bb --- /dev/null +++ b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultiThreadedPrinting", "MultiThreadedPrinting\MultiThreadedPrinting.csproj", "{2BB50AAD-2B17-46E0-9438-3EA423CFD63B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2BB50AAD-2B17-46E0-9438-3EA423CFD63B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2BB50AAD-2B17-46E0-9438-3EA423CFD63B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2BB50AAD-2B17-46E0-9438-3EA423CFD63B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2BB50AAD-2B17-46E0-9438-3EA423CFD63B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/App.config b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/MultiThreadedPrinting.csproj b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/MultiThreadedPrinting.csproj new file mode 100644 index 0000000..bad0441 --- /dev/null +++ b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/MultiThreadedPrinting.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {2BB50AAD-2B17-46E0-9438-3EA423CFD63B} + Exe + MultiThreadedPrinting + MultiThreadedPrinting + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/Program.cs b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/Program.cs new file mode 100644 index 0000000..567303f --- /dev/null +++ b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/Program.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; + +namespace MultiThreadedPrinting +{ + #region Printer helper class + public class Printer + { + // Lock token. + private object threadLock = new object(); + + public void PrintNumbers() + { + lock (threadLock) + { + // Display Thread info. + Console.WriteLine("-> {0} is executing PrintNumbers()", + Thread.CurrentThread.Name); + + // Print out numbers. + Console.Write("Your numbers: "); + for (int i = 0; i < 10; i++) + { + Random r = new Random(); + Thread.Sleep(100 * r.Next(5)); + Console.Write("{0}, ", i); + } + Console.WriteLine(); + } + } + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("*****Synchronizing Threads *****\n"); + + Printer p = new Printer(); + + // Make 10 threads that are all pointing to the same + // method on the same object. + Thread[] threads = new Thread[10]; + for (int i = 0; i < 10; i++) + { + threads[i] = new Thread(new ThreadStart(p.PrintNumbers)) + { + Name = $"Worker thread #{i}" + }; + } + + // Now start each one. + foreach (Thread t in threads) + t.Start(); + Console.ReadLine(); + } + } +} diff --git a/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/Properties/AssemblyInfo.cs b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..325fec8 --- /dev/null +++ b/Chapter_19/MultiThreadedPrinting/MultiThreadedPrinting/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MultiThreadedPrinting")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MultiThreadedPrinting")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2bb50aad-2b17-46e0-9438-3ea423cfd63b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/MyEBookReader/MyEBookReader.sln b/Chapter_19/MyEBookReader/MyEBookReader.sln new file mode 100644 index 0000000..e790a0d --- /dev/null +++ b/Chapter_19/MyEBookReader/MyEBookReader.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyEBookReader", "MyEBookReader\MyEBookReader.csproj", "{C0145E9D-F324-46DE-9DCE-9E041478B752}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C0145E9D-F324-46DE-9DCE-9E041478B752}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C0145E9D-F324-46DE-9DCE-9E041478B752}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C0145E9D-F324-46DE-9DCE-9E041478B752}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C0145E9D-F324-46DE-9DCE-9E041478B752}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/MyEBookReader/MyEBookReader/App.config b/Chapter_19/MyEBookReader/MyEBookReader/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/MyEBookReader/MyEBookReader/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/MyEBookReader/MyEBookReader/MyEBookReader.csproj b/Chapter_19/MyEBookReader/MyEBookReader/MyEBookReader.csproj new file mode 100644 index 0000000..0e1c7b0 --- /dev/null +++ b/Chapter_19/MyEBookReader/MyEBookReader/MyEBookReader.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {C0145E9D-F324-46DE-9DCE-9E041478B752} + Exe + MyEBookReader + MyEBookReader + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/MyEBookReader/MyEBookReader/Program.cs b/Chapter_19/MyEBookReader/MyEBookReader/Program.cs new file mode 100644 index 0000000..5e7264d --- /dev/null +++ b/Chapter_19/MyEBookReader/MyEBookReader/Program.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; + +namespace MyEBookReader +{ + class Program + { + private static string theEBook = ""; + + static void Main(string[] args) + { + GetBook(); + Console.WriteLine("Downloading book..."); + Console.ReadLine(); + } + + static void GetBook() + { + WebClient wc = new WebClient(); + wc.DownloadStringCompleted += (s, eArgs) => + { + theEBook = eArgs.Result; + Console.WriteLine("Download complete."); + GetStats(); + }; + // The Project Gutenberg EBook of A Tale of Two Cities, by Charles Dickens + // You might have to run it twice if you’ve never visited the site before, since the first + // time you visit there is a message box that pops up, and breaks this code. + wc.DownloadStringAsync(new Uri("http://www.gutenberg.org/files/98/98-8.txt")); + } + static void GetStats() + { + // Get the words from the e-book. + string[] words = theEBook.Split(new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '?', '/' }, + StringSplitOptions.RemoveEmptyEntries); + string[] tenMostCommon = null; + string longestWord = string.Empty; + + Parallel.Invoke( + () => + { + // Now, find the ten most common words. + tenMostCommon = FindTenMostCommon(words); + }, + () => + { + // Get the longest word. + longestWord = FindLongestWord(words); + }); + + // Now that all tasks are complete, build a string to show all stats. + StringBuilder bookStats = new StringBuilder("Ten Most Common Words are:\n"); + foreach (string s in tenMostCommon) + { + bookStats.AppendLine(s); + } + bookStats.AppendFormat("Longest word is: {0}", longestWord); + bookStats.AppendLine(); + Console.WriteLine(bookStats.ToString(), "Book info"); + } + static string[] FindTenMostCommon(string[] words) + { + var frequencyOrder = from word in words + where word.Length > 6 + group word by word into g + orderby g.Count() descending + select g.Key; + + string[] commonWords = (frequencyOrder.Take(10)).ToArray(); + return commonWords; + } + + static string FindLongestWord(string[] words) + { + return (from w in words orderby w.Length descending select w).FirstOrDefault(); + } + + } +} diff --git a/Chapter_19/MyEBookReader/MyEBookReader/Properties/AssemblyInfo.cs b/Chapter_19/MyEBookReader/MyEBookReader/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4b088bf --- /dev/null +++ b/Chapter_19/MyEBookReader/MyEBookReader/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MyEBookReader")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MyEBookReader")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c0145e9d-f324-46de-9dce-9e041478b752")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation.sln b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation.sln new file mode 100644 index 0000000..7c1b313 --- /dev/null +++ b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PLINQDataProcessingWithCancellation", "PLINQDataProcessingWithCancellation\PLINQDataProcessingWithCancellation.csproj", "{5903F9FE-9B78-400D-BAEB-A1B521A8B2B6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5903F9FE-9B78-400D-BAEB-A1B521A8B2B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5903F9FE-9B78-400D-BAEB-A1B521A8B2B6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5903F9FE-9B78-400D-BAEB-A1B521A8B2B6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5903F9FE-9B78-400D-BAEB-A1B521A8B2B6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/App.config b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation.csproj b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation.csproj new file mode 100644 index 0000000..d5cb7f6 --- /dev/null +++ b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {5903F9FE-9B78-400D-BAEB-A1B521A8B2B6} + Exe + PLINQDataProcessingWithCancellation + PLINQDataProcessingWithCancellation + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/Program.cs b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/Program.cs new file mode 100644 index 0000000..b233bbb --- /dev/null +++ b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/Program.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace PLINQDataProcessingWithCancellation +{ + class Program + { + static CancellationTokenSource cancelToken = new CancellationTokenSource(); + + static void Main(string[] args) + { + do + { + Console.WriteLine("Start any key to start processing"); + Console.ReadKey(); + + Console.WriteLine("Processing"); + Task.Factory.StartNew(() => ProcessIntData()); + Console.Write("Enter Q to quit: "); + string answer = Console.ReadLine(); + + // Does user want to quit? + if (answer.Equals("Q", StringComparison.OrdinalIgnoreCase)) + { + cancelToken.Cancel(); + break; + } + } while (true); + Console.ReadLine(); + } + + static void ProcessIntData() + { + // Get a very large array of integers. + int[] source = Enumerable.Range(1, 10_000_000).ToArray(); + + // Find the numbers where num % 3 == 0 is true, returned + // in descending order. + int[] modThreeIsZero = null; + try + { + modThreeIsZero = (from num in source.AsParallel().WithCancellation(cancelToken.Token) + where num % 3 == 0 + orderby num descending + select num).ToArray(); + Console.WriteLine(); + Console.WriteLine($"Found {modThreeIsZero.Count()} numbers that match query!"); + } + catch (OperationCanceledException ex) + { + Console.WriteLine(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/Properties/AssemblyInfo.cs b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a9b7a03 --- /dev/null +++ b/Chapter_19/PLINQDataProcessingWithCancellation/PLINQDataProcessingWithCancellation/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("PLINQDataProcessingWithCancellation")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PLINQDataProcessingWithCancellation")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5903f9fe-9b78-400d-baeb-a1b521a8b2b6")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp.sln b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp.sln new file mode 100644 index 0000000..e493b66 --- /dev/null +++ b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleMultiThreadApp", "SimpleMultiThreadApp\SimpleMultiThreadApp.csproj", "{C1860572-B3BF-420D-9CA3-FA4400BE59F1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C1860572-B3BF-420D-9CA3-FA4400BE59F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C1860572-B3BF-420D-9CA3-FA4400BE59F1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C1860572-B3BF-420D-9CA3-FA4400BE59F1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C1860572-B3BF-420D-9CA3-FA4400BE59F1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/App.config b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/Program.cs b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/Program.cs new file mode 100644 index 0000000..909e750 --- /dev/null +++ b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/Program.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows.Forms; + +namespace SimpleMultiThreadApp +{ + #region The Printer class + public class Printer + { + public void PrintNumbers() + { + // Display Thread info. + Console.WriteLine("-> {0} is executing PrintNumbers()", + Thread.CurrentThread.Name); + + // Print out numbers. + Console.Write("Your numbers: "); + for (int i = 0; i < 10; i++) + { + Console.Write("{0}, ", i); + Thread.Sleep(2000); + } + Console.WriteLine(); + } + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** The Amazing Thread App *****\n"); + Console.Write("Do you want [1] or [2] threads? "); + string threadCount = Console.ReadLine(); + + // Name the current thread. + Thread primaryThread = Thread.CurrentThread; + primaryThread.Name = "Primary"; + + // Display Thread info. + Console.WriteLine("-> {0} is executing Main()", + Thread.CurrentThread.Name); + + // Make worker class. + Printer p = new Printer(); + + switch (threadCount) + { + case "2": + // Now make the thread. + Thread backgroundThread = + new Thread(new ThreadStart(p.PrintNumbers)); + backgroundThread.Name = "Secondary"; + backgroundThread.Start(); + break; + case "1": + p.PrintNumbers(); + break; + default: + Console.WriteLine("I don't know what you want...you get 1 thread."); + goto case "1"; + } + + // Do some additional work. + MessageBox.Show("I'm busy!", "Work on main thread..."); + Console.ReadLine(); + } + + } +} diff --git a/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/Properties/AssemblyInfo.cs b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4a21751 --- /dev/null +++ b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleMultiThreadApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleMultiThreadApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c1860572-b3bf-420d-9ca3-fa4400be59f1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/SimpleMultiThreadApp.csproj b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/SimpleMultiThreadApp.csproj new file mode 100644 index 0000000..1784805 --- /dev/null +++ b/Chapter_19/SimpleMultiThreadApp/SimpleMultiThreadApp/SimpleMultiThreadApp.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {C1860572-B3BF-420D-9CA3-FA4400BE59F1} + Exe + SimpleMultiThreadApp + SimpleMultiThreadApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/SyncDelegateReview/SyncDelegateReview.sln b/Chapter_19/SyncDelegateReview/SyncDelegateReview.sln new file mode 100644 index 0000000..a6b8c04 --- /dev/null +++ b/Chapter_19/SyncDelegateReview/SyncDelegateReview.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SyncDelegateReview", "SyncDelegateReview\SyncDelegateReview.csproj", "{C4E2AEC3-EC48-41C3-8682-254A99972B60}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C4E2AEC3-EC48-41C3-8682-254A99972B60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C4E2AEC3-EC48-41C3-8682-254A99972B60}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C4E2AEC3-EC48-41C3-8682-254A99972B60}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C4E2AEC3-EC48-41C3-8682-254A99972B60}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/SyncDelegateReview/SyncDelegateReview/App.config b/Chapter_19/SyncDelegateReview/SyncDelegateReview/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/SyncDelegateReview/SyncDelegateReview/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/SyncDelegateReview/SyncDelegateReview/Program.cs b/Chapter_19/SyncDelegateReview/SyncDelegateReview/Program.cs new file mode 100644 index 0000000..1c1b722 --- /dev/null +++ b/Chapter_19/SyncDelegateReview/SyncDelegateReview/Program.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace SyncDelegateReview +{ + public delegate int BinaryOp(int x, int y); + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Synch Delegate Review *****"); + + // Print out the ID of the executing thread. + Console.WriteLine("Main() invoked on thread {0}.", + Thread.CurrentThread.ManagedThreadId); + + // Invoke Add() in a synchronous manner. + BinaryOp b = new BinaryOp(Add); + + // Could also write b.Invoke(10, 10); + int answer = b(10, 10); + + // These lines will not execute until + // the Add() method has completed. + Console.WriteLine("Doing more work in Main()!"); + Console.WriteLine("10 + 10 is {0}.", answer); + Console.ReadLine(); + } + + static int Add(int x, int y) + { + // Print out the ID of the executing thread. + Console.WriteLine("Add() invoked on thread {0}.", + Thread.CurrentThread.ManagedThreadId); + + // Pause to simulate a lengthy operation. + Thread.Sleep(5000); + return x + y; + } + } +} + diff --git a/Chapter_19/SyncDelegateReview/SyncDelegateReview/Properties/AssemblyInfo.cs b/Chapter_19/SyncDelegateReview/SyncDelegateReview/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9c12c5d --- /dev/null +++ b/Chapter_19/SyncDelegateReview/SyncDelegateReview/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SyncDelegateReview")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SyncDelegateReview")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c4e2aec3-ec48-41c3-8682-254a99972b60")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/SyncDelegateReview/SyncDelegateReview/SyncDelegateReview.csproj b/Chapter_19/SyncDelegateReview/SyncDelegateReview/SyncDelegateReview.csproj new file mode 100644 index 0000000..d32ca17 --- /dev/null +++ b/Chapter_19/SyncDelegateReview/SyncDelegateReview/SyncDelegateReview.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {C4E2AEC3-EC48-41C3-8682-254A99972B60} + Exe + SyncDelegateReview + SyncDelegateReview + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/TestPictures/butterfly.jpg b/Chapter_19/TestPictures/butterfly.jpg new file mode 100644 index 0000000..d7cfe2c Binary files /dev/null and b/Chapter_19/TestPictures/butterfly.jpg differ diff --git a/Chapter_19/TestPictures/city.jpg b/Chapter_19/TestPictures/city.jpg new file mode 100644 index 0000000..9705feb Binary files /dev/null and b/Chapter_19/TestPictures/city.jpg differ diff --git a/Chapter_19/TestPictures/desert.jpg b/Chapter_19/TestPictures/desert.jpg new file mode 100644 index 0000000..b9742f4 Binary files /dev/null and b/Chapter_19/TestPictures/desert.jpg differ diff --git a/Chapter_19/TestPictures/flower.jpg b/Chapter_19/TestPictures/flower.jpg new file mode 100644 index 0000000..9d686e0 Binary files /dev/null and b/Chapter_19/TestPictures/flower.jpg differ diff --git a/Chapter_19/TestPictures/flowers.jpg b/Chapter_19/TestPictures/flowers.jpg new file mode 100644 index 0000000..88a97e4 Binary files /dev/null and b/Chapter_19/TestPictures/flowers.jpg differ diff --git a/Chapter_19/TestPictures/night.jpg b/Chapter_19/TestPictures/night.jpg new file mode 100644 index 0000000..15f2eb2 Binary files /dev/null and b/Chapter_19/TestPictures/night.jpg differ diff --git a/Chapter_19/TestPictures/sunset.jpg b/Chapter_19/TestPictures/sunset.jpg new file mode 100644 index 0000000..e13c2ab Binary files /dev/null and b/Chapter_19/TestPictures/sunset.jpg differ diff --git a/Chapter_19/TestPictures/surf.jpg b/Chapter_19/TestPictures/surf.jpg new file mode 100644 index 0000000..cc9f601 Binary files /dev/null and b/Chapter_19/TestPictures/surf.jpg differ diff --git a/Chapter_19/TestPictures/tiger.jpg b/Chapter_19/TestPictures/tiger.jpg new file mode 100644 index 0000000..59444a3 Binary files /dev/null and b/Chapter_19/TestPictures/tiger.jpg differ diff --git a/Chapter_19/TestPictures/water.jpg b/Chapter_19/TestPictures/water.jpg new file mode 100644 index 0000000..7656f28 Binary files /dev/null and b/Chapter_19/TestPictures/water.jpg differ diff --git a/Chapter_19/ThreadPoolApp/ThreadPoolApp.sln b/Chapter_19/ThreadPoolApp/ThreadPoolApp.sln new file mode 100644 index 0000000..d8e0867 --- /dev/null +++ b/Chapter_19/ThreadPoolApp/ThreadPoolApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThreadPoolApp", "ThreadPoolApp\ThreadPoolApp.csproj", "{BA084320-EC89-441B-A5E9-AFF1997CE10D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BA084320-EC89-441B-A5E9-AFF1997CE10D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BA084320-EC89-441B-A5E9-AFF1997CE10D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BA084320-EC89-441B-A5E9-AFF1997CE10D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BA084320-EC89-441B-A5E9-AFF1997CE10D}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/ThreadPoolApp/ThreadPoolApp/App.config b/Chapter_19/ThreadPoolApp/ThreadPoolApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/ThreadPoolApp/ThreadPoolApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/ThreadPoolApp/ThreadPoolApp/Program.cs b/Chapter_19/ThreadPoolApp/ThreadPoolApp/Program.cs new file mode 100644 index 0000000..aebf3d2 --- /dev/null +++ b/Chapter_19/ThreadPoolApp/ThreadPoolApp/Program.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; + +namespace ThreadPoolApp +{ + #region Helper class + public class Printer + { + private object lockToken = new object(); + + public void PrintNumbers() + { + lock (lockToken) + { + // Display Thread info. + Console.WriteLine("-> {0} is executing PrintNumbers()", + Thread.CurrentThread.ManagedThreadId); + + // Print out numbers. + Console.Write("Your numbers: "); + for (int i = 0; i < 10; i++) + { + Console.Write("{0}, ", i); + Thread.Sleep(1000); + } + Console.WriteLine(); + } + } + } + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with the CLR Thread Pool *****\n"); + + Console.WriteLine("Main thread started. ThreadID = {0}", + Thread.CurrentThread.ManagedThreadId); + + Printer p = new Printer(); + + WaitCallback workItem = new WaitCallback(PrintTheNumbers); + + // Queue the method 10 times + for (int i = 0; i < 10; i++) + { + ThreadPool.QueueUserWorkItem(workItem, p); + } + + Console.WriteLine("All tasks queued"); + Console.ReadLine(); + } + + static void PrintTheNumbers(object state) + { + Printer task = (Printer)state; + task.PrintNumbers(); + } + } +} diff --git a/Chapter_19/ThreadPoolApp/ThreadPoolApp/Properties/AssemblyInfo.cs b/Chapter_19/ThreadPoolApp/ThreadPoolApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..989a299 --- /dev/null +++ b/Chapter_19/ThreadPoolApp/ThreadPoolApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ThreadPoolApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ThreadPoolApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ba084320-ec89-441b-a5e9-aff1997ce10d")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/ThreadPoolApp/ThreadPoolApp/ThreadPoolApp.csproj b/Chapter_19/ThreadPoolApp/ThreadPoolApp/ThreadPoolApp.csproj new file mode 100644 index 0000000..2e499d6 --- /dev/null +++ b/Chapter_19/ThreadPoolApp/ThreadPoolApp/ThreadPoolApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {BA084320-EC89-441B-A5E9-AFF1997CE10D} + Exe + ThreadPoolApp + ThreadPoolApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/ThreadStats/ThreadStats.sln b/Chapter_19/ThreadStats/ThreadStats.sln new file mode 100644 index 0000000..83269d2 --- /dev/null +++ b/Chapter_19/ThreadStats/ThreadStats.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThreadStats", "ThreadStats\ThreadStats.csproj", "{EEB7DBA4-8C47-4AB5-8217-9FA89A2D39D9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EEB7DBA4-8C47-4AB5-8217-9FA89A2D39D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EEB7DBA4-8C47-4AB5-8217-9FA89A2D39D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EEB7DBA4-8C47-4AB5-8217-9FA89A2D39D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EEB7DBA4-8C47-4AB5-8217-9FA89A2D39D9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/ThreadStats/ThreadStats/App.config b/Chapter_19/ThreadStats/ThreadStats/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/ThreadStats/ThreadStats/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/ThreadStats/ThreadStats/Program.cs b/Chapter_19/ThreadStats/ThreadStats/Program.cs new file mode 100644 index 0000000..f430ea1 --- /dev/null +++ b/Chapter_19/ThreadStats/ThreadStats/Program.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace ThreadStats +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Primary Thread stats *****\n"); + + // Obtain and name the current thread. + Thread primaryThread = Thread.CurrentThread; + primaryThread.Name = "ThePrimaryThread"; + + // Show details of hosting AppDomain/Context. + Console.WriteLine("Name of current AppDomain: {0}", + Thread.GetDomain().FriendlyName); + Console.WriteLine("ID of current Context: {0}", + Thread.CurrentContext.ContextID); + + // Print out some stats about this thread. + Console.WriteLine("Thread Name: {0}", + primaryThread.Name); + Console.WriteLine("Has thread started?: {0}", + primaryThread.IsAlive); + Console.WriteLine("Priority Level: {0}", + primaryThread.Priority); + Console.WriteLine("Thread State: {0}", + primaryThread.ThreadState); + Console.ReadLine(); + } + } +} diff --git a/Chapter_19/ThreadStats/ThreadStats/Properties/AssemblyInfo.cs b/Chapter_19/ThreadStats/ThreadStats/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f4a44eb --- /dev/null +++ b/Chapter_19/ThreadStats/ThreadStats/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ThreadStats")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ThreadStats")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("eeb7dba4-8c47-4ab5-8217-9fa89a2d39d9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/ThreadStats/ThreadStats/ThreadStats.csproj b/Chapter_19/ThreadStats/ThreadStats/ThreadStats.csproj new file mode 100644 index 0000000..18047e6 --- /dev/null +++ b/Chapter_19/ThreadStats/ThreadStats/ThreadStats.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {EEB7DBA4-8C47-4AB5-8217-9FA89A2D39D9} + Exe + ThreadStats + ThreadStats + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_19/TimerApp/TimerApp.sln b/Chapter_19/TimerApp/TimerApp.sln new file mode 100644 index 0000000..f4d0238 --- /dev/null +++ b/Chapter_19/TimerApp/TimerApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.15 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TimerApp", "TimerApp\TimerApp.csproj", "{6D559191-2619-49D0-9FA3-8BA2FBE9DF55}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6D559191-2619-49D0-9FA3-8BA2FBE9DF55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6D559191-2619-49D0-9FA3-8BA2FBE9DF55}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6D559191-2619-49D0-9FA3-8BA2FBE9DF55}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6D559191-2619-49D0-9FA3-8BA2FBE9DF55}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_19/TimerApp/TimerApp/App.config b/Chapter_19/TimerApp/TimerApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_19/TimerApp/TimerApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_19/TimerApp/TimerApp/Program.cs b/Chapter_19/TimerApp/TimerApp/Program.cs new file mode 100644 index 0000000..bfcc5bb --- /dev/null +++ b/Chapter_19/TimerApp/TimerApp/Program.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace TimerApp +{ + class Program + { + static void PrintTime(object state) + { + Console.WriteLine("Time is: {0}", + DateTime.Now.ToLongTimeString()); + } + + static void Main(string[] args) + { + Console.WriteLine("***** Working with Timer type *****\n"); + + // Create the delegate for the Timer type. + TimerCallback timeCB = new TimerCallback(PrintTime); + + // Establish timer settings. + var _ = new Timer( + timeCB, // The TimerCallback delegate type. + "Hello From Main", // Any info to pass into the called method (null for no info). + 0, // Amount of time to wait before starting. + 1000); // Interval of time between calls (in milliseconds). + + Console.WriteLine("Hit Enter key to terminate..."); + Console.ReadLine(); + } + + } +} diff --git a/Chapter_19/TimerApp/TimerApp/Properties/AssemblyInfo.cs b/Chapter_19/TimerApp/TimerApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2808082 --- /dev/null +++ b/Chapter_19/TimerApp/TimerApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("TimerApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("TimerApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6d559191-2619-49d0-9fa3-8ba2fbe9df55")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_19/TimerApp/TimerApp/TimerApp.csproj b/Chapter_19/TimerApp/TimerApp/TimerApp.csproj new file mode 100644 index 0000000..4d85b23 --- /dev/null +++ b/Chapter_19/TimerApp/TimerApp/TimerApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {6D559191-2619-49D0-9FA3-8BA2FBE9DF55} + Exe + TimerApp + TimerApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp.sln b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp.sln new file mode 100644 index 0000000..bcd72d3 --- /dev/null +++ b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.14 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleCSharpConsoleApp", "SimpleCSharpConsoleApp\SimpleCSharpConsoleApp.csproj", "{60E53162-E64F-478C-8509-80630E107226}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {60E53162-E64F-478C-8509-80630E107226}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {60E53162-E64F-478C-8509-80630E107226}.Debug|Any CPU.Build.0 = Debug|Any CPU + {60E53162-E64F-478C-8509-80630E107226}.Release|Any CPU.ActiveCfg = Release|Any CPU + {60E53162-E64F-478C-8509-80630E107226}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/App.config b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Car.cs b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Car.cs new file mode 100644 index 0000000..9f2b6f9 --- /dev/null +++ b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Car.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SimpleCSharpConsoleApp +{ + public class Car + { + public string PetName; + } +} \ No newline at end of file diff --git a/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/ClassDiagram1.cd b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/ClassDiagram1.cd new file mode 100644 index 0000000..3ae6d49 --- /dev/null +++ b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/ClassDiagram1.cd @@ -0,0 +1,25 @@ + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAA= + Program.cs + + + + + + AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Car.cs + + + + + + AAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + SportsCar.cs + + + + \ No newline at end of file diff --git a/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Program.cs b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Program.cs new file mode 100644 index 0000000..190a826 --- /dev/null +++ b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Program.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SimpleCSharpConsoleApp +{ + class Program + { + static void Main(string[] args) + { + // Set up Console UI (CUI) + Console.Title = "My Rocking App"; + Console.ForegroundColor = ConsoleColor.Yellow; + Console.BackgroundColor = ConsoleColor.Blue; + Console.WriteLine("*************************************"); + Console.WriteLine("***** Welcome to My Rocking App *****"); + Console.WriteLine("*************************************"); + Console.BackgroundColor = ConsoleColor.Black; + + // Wait for Enter key to be pressed. + Console.ReadLine(); + MessageBox.Show("All done!"); + } + } +} \ No newline at end of file diff --git a/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Properties/AssemblyInfo.cs b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..280a816 --- /dev/null +++ b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleCSharpConsoleApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleCSharpConsoleApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("60e53162-e64f-478c-8509-80630e107226")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp.csproj b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp.csproj new file mode 100644 index 0000000..5bb83c0 --- /dev/null +++ b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp.csproj @@ -0,0 +1,56 @@ + + + + + Debug + AnyCPU + {60E53162-E64F-478C-8509-80630E107226} + Exe + SimpleCSharpConsoleApp + SimpleCSharpConsoleApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/SportsCar.cs b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/SportsCar.cs new file mode 100644 index 0000000..a1ac723 --- /dev/null +++ b/Chapter_2/SimpleCSharpConsoleApp/SimpleCSharpConsoleApp/SportsCar.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SimpleCSharpConsoleApp +{ + public class SportsCar : Car + { + public string GetPetName() + { + PetName = "Fred"; + return PetName; + } + } +} \ No newline at end of file diff --git a/Chapter_20/BinaryWriterReader/BinaryWriterReader.sln b/Chapter_20/BinaryWriterReader/BinaryWriterReader.sln new file mode 100644 index 0000000..8a15990 --- /dev/null +++ b/Chapter_20/BinaryWriterReader/BinaryWriterReader.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BinaryWriterReader", "BinaryWriterReader\BinaryWriterReader.csproj", "{CA589973-C0C2-4F1D-8500-41EF8CDC49B1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CA589973-C0C2-4F1D-8500-41EF8CDC49B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CA589973-C0C2-4F1D-8500-41EF8CDC49B1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CA589973-C0C2-4F1D-8500-41EF8CDC49B1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CA589973-C0C2-4F1D-8500-41EF8CDC49B1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/BinaryWriterReader/BinaryWriterReader/App.config b/Chapter_20/BinaryWriterReader/BinaryWriterReader/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/BinaryWriterReader/BinaryWriterReader/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/BinaryWriterReader/BinaryWriterReader/BinaryWriterReader.csproj b/Chapter_20/BinaryWriterReader/BinaryWriterReader/BinaryWriterReader.csproj new file mode 100644 index 0000000..8c6bda0 --- /dev/null +++ b/Chapter_20/BinaryWriterReader/BinaryWriterReader/BinaryWriterReader.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {CA589973-C0C2-4F1D-8500-41EF8CDC49B1} + Exe + BinaryWriterReader + BinaryWriterReader + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/BinaryWriterReader/BinaryWriterReader/Program.cs b/Chapter_20/BinaryWriterReader/BinaryWriterReader/Program.cs new file mode 100644 index 0000000..a0645de --- /dev/null +++ b/Chapter_20/BinaryWriterReader/BinaryWriterReader/Program.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BinaryWriterReader +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Binary Writers / Readers *****\n"); + + // Open a binary writer for a file. + FileInfo f = new FileInfo("BinFile.dat"); + using (BinaryWriter bw = new BinaryWriter(f.OpenWrite())) + { + // Print out the type of BaseStream. + // (System.IO.FileStream in this case). + Console.WriteLine("Base stream is: {0}", bw.BaseStream); + + // Create some data to save in the file + double aDouble = 1234.67; + int anInt = 34567; + string aString = "A, B, C"; + + // Write the data + bw.Write(aDouble); + bw.Write(anInt); + bw.Write(aString); + } + + Console.WriteLine("Done!"); + + // Read the binary data from the stream. + using (BinaryReader br = new BinaryReader(f.OpenRead())) + { + Console.WriteLine(br.ReadDouble()); + Console.WriteLine(br.ReadInt32()); + Console.WriteLine(br.ReadString()); + } + + Console.ReadLine(); + } + + } +} diff --git a/Chapter_20/BinaryWriterReader/BinaryWriterReader/Properties/AssemblyInfo.cs b/Chapter_20/BinaryWriterReader/BinaryWriterReader/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..794e02a --- /dev/null +++ b/Chapter_20/BinaryWriterReader/BinaryWriterReader/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("BinaryWriterReader")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("BinaryWriterReader")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ca589973-c0c2-4f1d-8500-41ef8cdc49b1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/CustomSerialization/CustomSerialization.sln b/Chapter_20/CustomSerialization/CustomSerialization.sln new file mode 100644 index 0000000..824b09f --- /dev/null +++ b/Chapter_20/CustomSerialization/CustomSerialization.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomSerialization", "CustomSerialization\CustomSerialization.csproj", "{1D5A3AC8-C9A0-442F-8F02-CF7DAEF4AA25}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1D5A3AC8-C9A0-442F-8F02-CF7DAEF4AA25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1D5A3AC8-C9A0-442F-8F02-CF7DAEF4AA25}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1D5A3AC8-C9A0-442F-8F02-CF7DAEF4AA25}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1D5A3AC8-C9A0-442F-8F02-CF7DAEF4AA25}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/CustomSerialization/CustomSerialization/App.config b/Chapter_20/CustomSerialization/CustomSerialization/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/CustomSerialization/CustomSerialization/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/CustomSerialization/CustomSerialization/CustomSerialization.csproj b/Chapter_20/CustomSerialization/CustomSerialization/CustomSerialization.csproj new file mode 100644 index 0000000..3b9ff46 --- /dev/null +++ b/Chapter_20/CustomSerialization/CustomSerialization/CustomSerialization.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {1D5A3AC8-C9A0-442F-8F02-CF7DAEF4AA25} + Exe + CustomSerialization + CustomSerialization + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/CustomSerialization/CustomSerialization/Program.cs b/Chapter_20/CustomSerialization/CustomSerialization/Program.cs new file mode 100644 index 0000000..aa75422 --- /dev/null +++ b/Chapter_20/CustomSerialization/CustomSerialization/Program.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Soap; +using System.Text; +using System.Threading.Tasks; + +namespace CustomSerialization +{ + #region Type to serialize + [Serializable] + class StringData : ISerializable + { + private string dataItemOne = "First data block"; + private string dataItemTwo = "More data"; + + public StringData() { } + protected StringData(SerializationInfo si, StreamingContext ctx) + { + // Rehydrate member variables from stream. + dataItemOne = si.GetString("First_Item").ToLower(); + dataItemTwo = si.GetString("dataItemTwo").ToLower(); + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext ctx) + { + // Fill up the SerializationInfo object with the formatted data. + info.AddValue("First_Item", dataItemOne.ToUpper()); + info.AddValue("dataItemTwo", dataItemTwo.ToUpper()); + } + } + + [Serializable] + class MoreData + { + private string dataItemOne = "First data block"; + private string dataItemTwo = "More data"; + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + // Called during the serialization process. + dataItemOne = dataItemOne.ToUpper(); + dataItemTwo = dataItemTwo.ToUpper(); + } + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + // Called once the deserialization process is complete. + dataItemOne = dataItemOne.ToLower(); + dataItemTwo = dataItemTwo.ToLower(); + } + } + + #endregion + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Custom Serialization *****"); + + // Recall that this type implements ISerializable. + StringData myData = new StringData(); + + // Save to a local file in SOAP format. + SoapFormatter soapFormat = new SoapFormatter(); + using (Stream fStream = new FileStream("MyData.soap", + FileMode.Create, FileAccess.Write, FileShare.None)) + { + soapFormat.Serialize(fStream, myData); + } + Console.ReadLine(); + } + } +} diff --git a/Chapter_20/CustomSerialization/CustomSerialization/Properties/AssemblyInfo.cs b/Chapter_20/CustomSerialization/CustomSerialization/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..79b0ece --- /dev/null +++ b/Chapter_20/CustomSerialization/CustomSerialization/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CustomSerialization")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CustomSerialization")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1d5a3ac8-c9a0-442f-8f02-cf7daef4aa25")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/DirectoryApp/DirectoryApp.sln b/Chapter_20/DirectoryApp/DirectoryApp.sln new file mode 100644 index 0000000..5d78d8e --- /dev/null +++ b/Chapter_20/DirectoryApp/DirectoryApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DirectoryApp", "DirectoryApp\DirectoryApp.csproj", "{918ADD87-FC3B-45EA-95A1-776D0BB7BDB0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {918ADD87-FC3B-45EA-95A1-776D0BB7BDB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {918ADD87-FC3B-45EA-95A1-776D0BB7BDB0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {918ADD87-FC3B-45EA-95A1-776D0BB7BDB0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {918ADD87-FC3B-45EA-95A1-776D0BB7BDB0}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/DirectoryApp/DirectoryApp/App.config b/Chapter_20/DirectoryApp/DirectoryApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/DirectoryApp/DirectoryApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/DirectoryApp/DirectoryApp/DirectoryApp.csproj b/Chapter_20/DirectoryApp/DirectoryApp/DirectoryApp.csproj new file mode 100644 index 0000000..9834460 --- /dev/null +++ b/Chapter_20/DirectoryApp/DirectoryApp/DirectoryApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {918ADD87-FC3B-45EA-95A1-776D0BB7BDB0} + Exe + DirectoryApp + DirectoryApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/DirectoryApp/DirectoryApp/Program.cs b/Chapter_20/DirectoryApp/DirectoryApp/Program.cs new file mode 100644 index 0000000..973177f --- /dev/null +++ b/Chapter_20/DirectoryApp/DirectoryApp/Program.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.IO; + +namespace DirectoryApp +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Directory(Info) *****\n"); + ShowWindowsDirectoryInfo(); + DisplayImageFiles(); + ModifyAppDirectory(); + FunWithDirectoryType(); + Console.ReadLine(); + } + + #region Display basic info about C:\Windows + static void ShowWindowsDirectoryInfo() + { + // Dump directory information. + DirectoryInfo dir = new DirectoryInfo(@"C:\Windows"); + Console.WriteLine("***** Directory Info *****"); + Console.WriteLine("FullName: {0}", dir.FullName); + Console.WriteLine("Name: {0}", dir.Name); + Console.WriteLine("Parent: {0}", dir.Parent); + Console.WriteLine("Creation: {0}", dir.CreationTime); + Console.WriteLine("Attributes: {0}", dir.Attributes); + Console.WriteLine("Root: {0}", dir.Root); + Console.WriteLine("**************************\n"); + } + #endregion + + #region Display info on JPG files + static void DisplayImageFiles() + { + DirectoryInfo dir = new DirectoryInfo(@"C:\Windows\Web\Wallpaper"); + // Get all files with a *.jpg extension. + FileInfo[] imageFiles = dir.GetFiles("*.jpg", SearchOption.AllDirectories); + + // How many were found? + Console.WriteLine("Found {0} *.jpg files\n", imageFiles.Length); + + // Now print out info for each file. + foreach (FileInfo f in imageFiles) + { + Console.WriteLine("***************************"); + Console.WriteLine("File name: {0}", f.Name); + Console.WriteLine("File size: {0}", f.Length); + Console.WriteLine("Creation: {0}", f.CreationTime); + Console.WriteLine("Attributes: {0}", f.Attributes); + Console.WriteLine("***************************\n"); + } + } + #endregion + + #region Modify directory structure + static void ModifyAppDirectory() + { + DirectoryInfo dir = new DirectoryInfo("."); + + // Create \MyFolder off initial directory. + dir.CreateSubdirectory("MyFolder"); + + // Capture returned DirectoryInfo object. + DirectoryInfo myDataFolder = dir.CreateSubdirectory(@"MyFolder2\Data"); + + // Prints path to ..\MyFolder2\Data. + Console.WriteLine("New Folder is: {0}", myDataFolder); + } + #endregion + + #region Use Directory class + static void FunWithDirectoryType() + { + // List all drives on current computer. + string[] drives = Directory.GetLogicalDrives(); + Console.WriteLine("Here are your drives:"); + foreach (string s in drives) + Console.WriteLine("--> {0} ", s); + + // Delete what was created. + Console.WriteLine("Press Enter to delete directories"); + Console.ReadLine(); + try + { + Directory.Delete(@"C:\MyFolder"); + + // The second parameter specifies whether you + // wish to destroy any subdirectories. + Directory.Delete(@"C:\MyFolder2", true); + } + catch (IOException e) + { + Console.WriteLine(e.Message); + } + } + #endregion + + } +} diff --git a/Chapter_20/DirectoryApp/DirectoryApp/Properties/AssemblyInfo.cs b/Chapter_20/DirectoryApp/DirectoryApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b0616a2 --- /dev/null +++ b/Chapter_20/DirectoryApp/DirectoryApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DirectoryApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DirectoryApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("918add87-fc3b-45ea-95a1-776d0bb7bdb0")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/DriveInfoApp/DriveInfoApp.sln b/Chapter_20/DriveInfoApp/DriveInfoApp.sln new file mode 100644 index 0000000..9910156 --- /dev/null +++ b/Chapter_20/DriveInfoApp/DriveInfoApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DriveInfoApp", "DriveInfoApp\DriveInfoApp.csproj", "{21AC885C-4590-42DB-AA4A-CC801DCFF509}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {21AC885C-4590-42DB-AA4A-CC801DCFF509}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {21AC885C-4590-42DB-AA4A-CC801DCFF509}.Debug|Any CPU.Build.0 = Debug|Any CPU + {21AC885C-4590-42DB-AA4A-CC801DCFF509}.Release|Any CPU.ActiveCfg = Release|Any CPU + {21AC885C-4590-42DB-AA4A-CC801DCFF509}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/DriveInfoApp/DriveInfoApp/App.config b/Chapter_20/DriveInfoApp/DriveInfoApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/DriveInfoApp/DriveInfoApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/DriveInfoApp/DriveInfoApp/DriveInfoApp.csproj b/Chapter_20/DriveInfoApp/DriveInfoApp/DriveInfoApp.csproj new file mode 100644 index 0000000..1cc0907 --- /dev/null +++ b/Chapter_20/DriveInfoApp/DriveInfoApp/DriveInfoApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {21AC885C-4590-42DB-AA4A-CC801DCFF509} + Exe + DriveInfoApp + DriveInfoApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/DriveInfoApp/DriveInfoApp/Program.cs b/Chapter_20/DriveInfoApp/DriveInfoApp/Program.cs new file mode 100644 index 0000000..5c59235 --- /dev/null +++ b/Chapter_20/DriveInfoApp/DriveInfoApp/Program.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DriveInfoApp +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with DriveInfo *****\n"); + + // Get info regarding all drives. + DriveInfo[] myDrives = DriveInfo.GetDrives(); + // Now print drive stats. + foreach (DriveInfo d in myDrives) + { + Console.WriteLine("Name: {0}", d.Name); + Console.WriteLine("Type: {0}", d.DriveType); + + // Check to see whether the drive is mounted. + if (d.IsReady) + { + Console.WriteLine("Free space: {0}", d.TotalFreeSpace); + Console.WriteLine("Format: {0}", d.DriveFormat); + Console.WriteLine("Label: {0}", d.VolumeLabel); + } + Console.WriteLine(); + } + Console.ReadLine(); + } + } + +} diff --git a/Chapter_20/DriveInfoApp/DriveInfoApp/Properties/AssemblyInfo.cs b/Chapter_20/DriveInfoApp/DriveInfoApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..18767e7 --- /dev/null +++ b/Chapter_20/DriveInfoApp/DriveInfoApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DriveInfoApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DriveInfoApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("21ac885c-4590-42db-aa4a-cc801dcff509")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/FileStreamApp/FileStreamApp.sln b/Chapter_20/FileStreamApp/FileStreamApp.sln new file mode 100644 index 0000000..c0fd1f6 --- /dev/null +++ b/Chapter_20/FileStreamApp/FileStreamApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileStreamApp", "FileStreamApp\FileStreamApp.csproj", "{B252B8C3-4223-4E77-A74C-AFCA22F9E34B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B252B8C3-4223-4E77-A74C-AFCA22F9E34B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B252B8C3-4223-4E77-A74C-AFCA22F9E34B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B252B8C3-4223-4E77-A74C-AFCA22F9E34B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B252B8C3-4223-4E77-A74C-AFCA22F9E34B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/FileStreamApp/FileStreamApp/App.config b/Chapter_20/FileStreamApp/FileStreamApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/FileStreamApp/FileStreamApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/FileStreamApp/FileStreamApp/FileStreamApp.csproj b/Chapter_20/FileStreamApp/FileStreamApp/FileStreamApp.csproj new file mode 100644 index 0000000..eb3002a --- /dev/null +++ b/Chapter_20/FileStreamApp/FileStreamApp/FileStreamApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {B252B8C3-4223-4E77-A74C-AFCA22F9E34B} + Exe + FileStreamApp + FileStreamApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/FileStreamApp/FileStreamApp/Program.cs b/Chapter_20/FileStreamApp/FileStreamApp/Program.cs new file mode 100644 index 0000000..fc2d677 --- /dev/null +++ b/Chapter_20/FileStreamApp/FileStreamApp/Program.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FileStreamApp +{ + class Program + { + // Don't forget to import the System.Text and System.IO namespaces. + static void Main(string[] args) + { + Console.WriteLine("***** Fun with FileStreams *****\n"); + + try + { + // Obtain a FileStream object. + using (FileStream fStream = File.Open(@"myMessage.dat", + FileMode.Create)) + { + // Encode a string as an array of bytes. + string msg = "Hello!"; + byte[] msgAsByteArray = Encoding.Default.GetBytes(msg); + + // Write byte[] to file. + fStream.Write(msgAsByteArray, 0, msgAsByteArray.Length); + + // Reset internal position of stream. + fStream.Position = 0; + + // Read the types from file and display to console. + Console.Write("Your message as an array of bytes: "); + byte[] bytesFromFile = new byte[msgAsByteArray.Length]; + for (int i = 0; i < msgAsByteArray.Length; i++) + { + bytesFromFile[i] = (byte)fStream.ReadByte(); + Console.Write(bytesFromFile[i]); + } + + // Display decoded messages. + Console.Write("\nDecoded Message: "); + Console.WriteLine(Encoding.Default.GetString(bytesFromFile)); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + Console.ReadLine(); + } + + } +} diff --git a/Chapter_20/FileStreamApp/FileStreamApp/Properties/AssemblyInfo.cs b/Chapter_20/FileStreamApp/FileStreamApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3565606 --- /dev/null +++ b/Chapter_20/FileStreamApp/FileStreamApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("FileStreamApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FileStreamApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b252b8c3-4223-4e77-a74c-afca22f9e34b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher.sln b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher.sln new file mode 100644 index 0000000..dfee73f --- /dev/null +++ b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyDirectoryWatcher", "MyDirectoryWatcher\MyDirectoryWatcher.csproj", "{F1A3A284-9DDD-4F1E-9548-6828AA29381E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F1A3A284-9DDD-4F1E-9548-6828AA29381E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F1A3A284-9DDD-4F1E-9548-6828AA29381E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F1A3A284-9DDD-4F1E-9548-6828AA29381E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F1A3A284-9DDD-4F1E-9548-6828AA29381E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/App.config b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/MyDirectoryWatcher.csproj b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/MyDirectoryWatcher.csproj new file mode 100644 index 0000000..3b38455 --- /dev/null +++ b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/MyDirectoryWatcher.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {F1A3A284-9DDD-4F1E-9548-6828AA29381E} + Exe + MyDirectoryWatcher + MyDirectoryWatcher + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/Program.cs b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/Program.cs new file mode 100644 index 0000000..52f6a1c --- /dev/null +++ b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/Program.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MyDirectoryWatcher +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** The Amazing File Watcher App *****\n"); + + // Establish the path to the directory to watch. + FileSystemWatcher watcher = new FileSystemWatcher(); + try + { + watcher.Path = @"C:\MyFolder"; + } + catch (ArgumentException ex) + { + Console.WriteLine(ex.Message); + return; + } + // Set up the things to be on the lookout for. + watcher.NotifyFilter = NotifyFilters.LastAccess + | NotifyFilters.LastWrite + | NotifyFilters.FileName + | NotifyFilters.DirectoryName; + + // Only watch text files. + watcher.Filter = "*.txt"; + + // Specify what is done when a file is changed, created, or deleted. + watcher.Changed += (s, e) => + { + Console.WriteLine("File: {0} {1}!", e.FullPath, e.ChangeType); + }; + + watcher.Created += (s, e) => + { + Console.WriteLine("File: {0} {1}!", e.FullPath, e.ChangeType); + }; + + watcher.Deleted += (s, e) => + { + Console.WriteLine("File: {0} {1}!", e.FullPath, e.ChangeType); + }; + + watcher.Renamed += (s, e) => + { + // Specify what is done when a file is renamed. + Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath); + }; + + // Begin watching the directory. + watcher.EnableRaisingEvents = true; + + // Wait for the user to quit the program. + Console.WriteLine(@"Press 'q' to quit app."); + while (Console.Read() != 'q') ; + } + } +} diff --git a/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/Properties/AssemblyInfo.cs b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9ea20b8 --- /dev/null +++ b/Chapter_20/MyDirectoryWatcher/MyDirectoryWatcher/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MyDirectoryWatcher")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MyDirectoryWatcher")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f1a3a284-9ddd-4f1e-9548-6828aa29381e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/SimpleFileIO/SimpleFileIO.sln b/Chapter_20/SimpleFileIO/SimpleFileIO.sln new file mode 100644 index 0000000..00a62bb --- /dev/null +++ b/Chapter_20/SimpleFileIO/SimpleFileIO.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleFileIO", "SimpleFileIO\SimpleFileIO.csproj", "{F0B4A78A-67CA-4D61-A206-1C381F9717CC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F0B4A78A-67CA-4D61-A206-1C381F9717CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F0B4A78A-67CA-4D61-A206-1C381F9717CC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F0B4A78A-67CA-4D61-A206-1C381F9717CC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F0B4A78A-67CA-4D61-A206-1C381F9717CC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/SimpleFileIO/SimpleFileIO/App.config b/Chapter_20/SimpleFileIO/SimpleFileIO/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/SimpleFileIO/SimpleFileIO/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/SimpleFileIO/SimpleFileIO/Program.cs b/Chapter_20/SimpleFileIO/SimpleFileIO/Program.cs new file mode 100644 index 0000000..83ac210 --- /dev/null +++ b/Chapter_20/SimpleFileIO/SimpleFileIO/Program.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SimpleFileIO +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Simple IO with the File Type *****\n"); + try + { + string[] myTasks = { + "Fix bathroom sink", "Call Dave", + "Call Mom and Dad", "Play Xbox 360"}; + + // Write out all data to file on C drive. + File.WriteAllLines(@"tasks.txt", myTasks); + + // Read it all back and print out. + foreach (string task in File.ReadAllLines(@"tasks.txt")) + { + Console.WriteLine("TODO: {0}", task); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + Console.ReadLine(); + } + } + +} diff --git a/Chapter_20/SimpleFileIO/SimpleFileIO/Properties/AssemblyInfo.cs b/Chapter_20/SimpleFileIO/SimpleFileIO/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a9cdfa2 --- /dev/null +++ b/Chapter_20/SimpleFileIO/SimpleFileIO/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleFileIO")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleFileIO")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f0b4a78a-67ca-4d61-a206-1c381f9717cc")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/SimpleFileIO/SimpleFileIO/SimpleFileIO.csproj b/Chapter_20/SimpleFileIO/SimpleFileIO/SimpleFileIO.csproj new file mode 100644 index 0000000..34bdf96 --- /dev/null +++ b/Chapter_20/SimpleFileIO/SimpleFileIO/SimpleFileIO.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {F0B4A78A-67CA-4D61-A206-1C381F9717CC} + Exe + SimpleFileIO + SimpleFileIO + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/SimpleSerialize/SimpleSerialize.sln b/Chapter_20/SimpleSerialize/SimpleSerialize.sln new file mode 100644 index 0000000..a30c59d --- /dev/null +++ b/Chapter_20/SimpleSerialize/SimpleSerialize.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleSerialize", "SimpleSerialize\SimpleSerialize.csproj", "{842EFF40-7E44-45A1-9FF6-47B73D59AF20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {842EFF40-7E44-45A1-9FF6-47B73D59AF20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {842EFF40-7E44-45A1-9FF6-47B73D59AF20}.Debug|Any CPU.Build.0 = Debug|Any CPU + {842EFF40-7E44-45A1-9FF6-47B73D59AF20}.Release|Any CPU.ActiveCfg = Release|Any CPU + {842EFF40-7E44-45A1-9FF6-47B73D59AF20}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/SimpleSerialize/SimpleSerialize/App.config b/Chapter_20/SimpleSerialize/SimpleSerialize/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/SimpleSerialize/SimpleSerialize/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/SimpleSerialize/SimpleSerialize/Program.cs b/Chapter_20/SimpleSerialize/SimpleSerialize/Program.cs new file mode 100644 index 0000000..0e2f792 --- /dev/null +++ b/Chapter_20/SimpleSerialize/SimpleSerialize/Program.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// Gain access to the BinaryFormatter in mscorlib.dll. +using System.Runtime.Serialization.Formatters.Binary; + +// Must reference System.Runtime.Serialization.Formatters.Soap.dll. +using System.Runtime.Serialization.Formatters.Soap; + +// Defined within System.Xml.dll. +using System.Xml.Serialization; +using System.IO; + +namespace SimpleSerialize +{ + #region Types to serialize + [Serializable] + public class Radio + { + public bool hasTweeters; + public bool hasSubWoofers; + public double[] stationPresets; + + [NonSerialized] + public string radioID = "XF-552RR6"; + } + + [Serializable] + public class Car + { + public Radio theRadio = new Radio(); + public bool isHatchBack; + } + + [Serializable] + [XmlRoot(Namespace = "http://www.MyCompany.com")] + public class JamesBondCar : Car + { + [XmlAttribute] + public bool canFly; + [XmlAttribute] + public bool canSubmerge; + + public JamesBondCar(bool skyWorthy, bool seaWorthy) + { + canFly = skyWorthy; + canSubmerge = seaWorthy; + } + // The XmlSerializer demands a default constructor! + public JamesBondCar() { } + + } + + #endregion + + class Program + { + // Be sure to import the System.Runtime.Serialization.Formatters.Binary + // and System.IO namespaces. + static void Main(string[] args) + { + Console.WriteLine("***** Fun with Object Serialization *****\n"); + + // Make a JamesBondCar and set state. + JamesBondCar jbc = new JamesBondCar(); + jbc.canFly = true; + jbc.canSubmerge = false; + jbc.theRadio.stationPresets = new double[] { 89.3, 105.1, 97.1 }; + jbc.theRadio.hasTweeters = true; + + // Now save the car to a specific file in a binary format. + SaveAsBinaryFormat(jbc, "CarData.dat"); + LoadFromBinaryFile("CarData.dat"); + + // Save as SOAP. + SaveAsSoapFormat(jbc, "CarData.soap"); + + // XML + SaveAsXmlFormat(jbc, "CarData.xml"); + + SaveListOfCars(); + + Console.ReadLine(); + } + + #region Load from binary + static void LoadFromBinaryFile(string fileName) + { + BinaryFormatter binFormat = new BinaryFormatter(); + + // Read the JamesBondCar from the binary file. + using (Stream fStream = File.OpenRead(fileName)) + { + JamesBondCar carFromDisk = + (JamesBondCar)binFormat.Deserialize(fStream); + Console.WriteLine("Can this car fly? : {0}", carFromDisk.canFly); + } + } + #endregion + + #region Save as binary + static void SaveAsBinaryFormat(object objGraph, string fileName) + { + // Save object to a file named CarData.dat in binary. + BinaryFormatter binFormat = new BinaryFormatter(); + + using (Stream fStream = new FileStream(fileName, + FileMode.Create, FileAccess.Write, FileShare.None)) + { + binFormat.Serialize(fStream, objGraph); + } + Console.WriteLine("=> Saved car in binary format!"); + } + #endregion + + #region Save as SOAP + // Be sure to import System.Runtime.Serialization.Formatters.Soap + // and reference System.Runtime.Serialization.Formatters.Soap.dll. + static void SaveAsSoapFormat(object objGraph, string fileName) + { + // Save object to a file named CarData.soap in SOAP format. + SoapFormatter soapFormat = new SoapFormatter(); + + using (Stream fStream = new FileStream(fileName, + FileMode.Create, FileAccess.Write, FileShare.None)) + { + soapFormat.Serialize(fStream, objGraph); + } + Console.WriteLine("=> Saved car in SOAP format!"); + } + #endregion + + #region Save as XML + static void SaveAsXmlFormat(object objGraph, string fileName) + { + // Save object to a file named CarData.xml in XML format. + XmlSerializer xmlFormat = new XmlSerializer(typeof(JamesBondCar)); + + using (Stream fStream = new FileStream(fileName, + FileMode.Create, FileAccess.Write, FileShare.None)) + { + xmlFormat.Serialize(fStream, objGraph); + } + Console.WriteLine("=> Saved car in XML format!"); + } + + #endregion + + #region Save LIST of objects + static void SaveListOfCars() + { + // Now persist a List of JamesBondCars. + List myCars = new List(); + myCars.Add(new JamesBondCar(true, true)); + myCars.Add(new JamesBondCar(true, false)); + myCars.Add(new JamesBondCar(false, true)); + myCars.Add(new JamesBondCar(false, false)); + + using (Stream fStream = new FileStream("CarCollection.xml", + FileMode.Create, FileAccess.Write, FileShare.None)) + { + XmlSerializer xmlFormat = new XmlSerializer(typeof(List)); + xmlFormat.Serialize(fStream, myCars); + } + Console.WriteLine("=> Saved list of cars!"); + } + + static void SaveListOfCarsAsBinary() + { + // Save ArrayList object (myCars) as binary. + List myCars = new List(); + + BinaryFormatter binFormat = new BinaryFormatter(); + using (Stream fStream = new FileStream("AllMyCars.dat", + FileMode.Create, FileAccess.Write, FileShare.None)) + { + binFormat.Serialize(fStream, myCars); + } + Console.WriteLine("=> Saved list of cars in binary!"); + } + + #endregion + } +} diff --git a/Chapter_20/SimpleSerialize/SimpleSerialize/Properties/AssemblyInfo.cs b/Chapter_20/SimpleSerialize/SimpleSerialize/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..457584b --- /dev/null +++ b/Chapter_20/SimpleSerialize/SimpleSerialize/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SimpleSerialize")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleSerialize")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("842eff40-7e44-45a1-9ff6-47b73d59af20")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/SimpleSerialize/SimpleSerialize/SimpleSerialize.csproj b/Chapter_20/SimpleSerialize/SimpleSerialize/SimpleSerialize.csproj new file mode 100644 index 0000000..17d6884 --- /dev/null +++ b/Chapter_20/SimpleSerialize/SimpleSerialize/SimpleSerialize.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {842EFF40-7E44-45A1-9FF6-47B73D59AF20} + Exe + SimpleSerialize + SimpleSerialize + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp.sln b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp.sln new file mode 100644 index 0000000..ef5d8a5 --- /dev/null +++ b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StreamWriterReaderApp", "StreamWriterReaderApp\StreamWriterReaderApp.csproj", "{0EED6049-C719-4C43-B88E-646917995F06}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0EED6049-C719-4C43-B88E-646917995F06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0EED6049-C719-4C43-B88E-646917995F06}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0EED6049-C719-4C43-B88E-646917995F06}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0EED6049-C719-4C43-B88E-646917995F06}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/App.config b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/Program.cs b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/Program.cs new file mode 100644 index 0000000..169639a --- /dev/null +++ b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/Program.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StreamWriterReaderApp +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with StreamWriter / StreamReader *****\n"); + + // Get a StreamWriter and write string data. + using (StreamWriter writer = File.CreateText("reminders.txt")) + { + writer.WriteLine("Don't forget Mother's Day this year..."); + writer.WriteLine("Don't forget Father's Day this year..."); + writer.WriteLine("Don't forget these numbers:"); + for (int i = 0; i < 10; i++) + writer.Write(i + " "); + + // Insert a new line. + writer.Write(writer.NewLine); + } + + Console.WriteLine("Created file and wrote some thoughts..."); + + // Now read data from file. + Console.WriteLine("Here are your thoughts:\n"); + using (StreamReader sr = File.OpenText("reminders.txt")) + { + string input = null; + while ((input = sr.ReadLine()) != null) + { + Console.WriteLine(input); + } + } + + Console.ReadLine(); + } + } +} diff --git a/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/Properties/AssemblyInfo.cs b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d0b4ba9 --- /dev/null +++ b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("StreamWriterReaderApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("StreamWriterReaderApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0eed6049-c719-4c43-b88e-646917995f06")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/StreamWriterReaderApp.csproj b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/StreamWriterReaderApp.csproj new file mode 100644 index 0000000..135cf4e --- /dev/null +++ b/Chapter_20/StreamWriterReaderApp/StreamWriterReaderApp/StreamWriterReaderApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {0EED6049-C719-4C43-B88E-646917995F06} + Exe + StreamWriterReaderApp + StreamWriterReaderApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_20/StringReaderWriterApp/StringReaderWriterApp.sln b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp.sln new file mode 100644 index 0000000..2ee28ca --- /dev/null +++ b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StringReaderWriterApp", "StringReaderWriterApp\StringReaderWriterApp.csproj", "{1B896998-B60E-4698-8532-1C7C839F92E3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1B896998-B60E-4698-8532-1C7C839F92E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1B896998-B60E-4698-8532-1C7C839F92E3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1B896998-B60E-4698-8532-1C7C839F92E3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1B896998-B60E-4698-8532-1C7C839F92E3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/App.config b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/Program.cs b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/Program.cs new file mode 100644 index 0000000..24278ba --- /dev/null +++ b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/Program.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StringReaderWriterApp +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Fun with StringWriter / StringReader *****\n"); + + // Create a StringWriter and emit character data to memory. + using (StringWriter strWriter = new StringWriter()) + { + strWriter.WriteLine("Don't forget Mother's Day this year..."); + Console.WriteLine("Contents of StringWriter:\n{0}", strWriter); + + // Get the internal StringBuilder. + StringBuilder sb = strWriter.GetStringBuilder(); + sb.Insert(0, "Hey!! "); + Console.WriteLine("-> {0}", sb.ToString()); + sb.Remove(0, "Hey!! ".Length); + Console.WriteLine("-> {0}", sb.ToString()); + } + + using (StringWriter strWriter = new StringWriter()) + { + strWriter.WriteLine("Don't forget Mother's Day this year..."); + Console.WriteLine("Contents of StringWriter:\n{0}", strWriter); + + // Read data from the StringWriter. + using (StringReader strReader = new StringReader(strWriter.ToString())) + { + string input = null; + while ((input = strReader.ReadLine()) != null) + { + Console.WriteLine(input); + } + } + } + + Console.ReadLine(); + } + } +} diff --git a/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/Properties/AssemblyInfo.cs b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e9ed56c --- /dev/null +++ b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("StringReaderWriterApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("StringReaderWriterApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1b896998-b60e-4698-8532-1c7c839f92e3")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/StringReaderWriterApp.csproj b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/StringReaderWriterApp.csproj new file mode 100644 index 0000000..f908a70 --- /dev/null +++ b/Chapter_20/StringReaderWriterApp/StringReaderWriterApp/StringReaderWriterApp.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {1B896998-B60E-4698-8532-1C7C839F92E3} + Exe + StringReaderWriterApp + StringReaderWriterApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_21/AutoLotDAL/AutoLotClient/App.config b/Chapter_21/AutoLotDAL/AutoLotClient/App.config new file mode 100644 index 0000000..88fa402 --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotClient/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_21/AutoLotDAL/AutoLotClient/AutoLotClient.csproj b/Chapter_21/AutoLotDAL/AutoLotClient/AutoLotClient.csproj new file mode 100644 index 0000000..d83823d --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotClient/AutoLotClient.csproj @@ -0,0 +1,58 @@ + + + + + Debug + AnyCPU + {8AEA202E-4C42-4279-94B3-E984DF267769} + Exe + AutoLotClient + AutoLotClient + v4.5.2 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + {76eba30b-7574-4562-9746-e0edc6a31e78} + AutoLotDAL + + + + \ No newline at end of file diff --git a/Chapter_21/AutoLotDAL/AutoLotClient/Program.cs b/Chapter_21/AutoLotDAL/AutoLotClient/Program.cs new file mode 100644 index 0000000..a4722a0 --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotClient/Program.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.BulkImport; +using AutoLotDAL.DataOperations; +using AutoLotDAL.Models; + +namespace AutoLotClient +{ + class Program + { + static void Main(string[] args) + { + InventoryDAL dal = new InventoryDAL(); + var list = dal.GetAllInventory(); + Console.WriteLine(" ************** All Cars ************** "); + Console.WriteLine("CarId\tMake\tColor\tPet Name"); + foreach (var itm in list) + { + Console.WriteLine($"{itm.CarId}\t{itm.Make}\t{itm.Color}\t{itm.PetName}"); + } + Console.WriteLine(); + var car = dal.GetCar(list.OrderBy(x => x.Color).Select(x => x.CarId).First()); + Console.WriteLine(" ************** First Car By Color ************** "); + Console.WriteLine("CarId\tMake\tColor\tPet Name"); + Console.WriteLine($"{car.CarId}\t{car.Make}\t{car.Color}\t{car.PetName}"); + + try + { + dal.DeleteCar(5); + Console.WriteLine("Car deleted."); + } + catch (Exception ex) + { + Console.WriteLine($"An exception occurred: {ex.Message}"); + } + //dal.InsertAuto(new Car {Color = "Blue", Make = "Pilot", PetName = "TowMonster"}); + //list = dal.GetAllInventory(); + //var newCar = list.First(x => x.PetName == "TowMonster"); + //Console.WriteLine(" ************** New Car ************** "); + //Console.WriteLine("CarId\tMake\tColor\tPet Name"); + //Console.WriteLine($"{newCar.CarId}\t{newCar.Make}\t{newCar.Color}\t{newCar.PetName}"); + //dal.DeleteCar(newCar.CarId); + var petName = dal.LookUpPetName(car.CarId); + Console.WriteLine(" ************** New Car ************** "); + Console.WriteLine($"Car pet name: {petName}"); + DoBulkCopy(); + //MoveCustomer(); + Console.Write("Press enter to continue..."); + Console.ReadLine(); + } + + public static void MoveCustomer() + { + Console.WriteLine("***** Simple Transaction Example *****\n"); + + // A simple way to allow the tx to succeed or not. + bool throwEx = true; + + Console.Write("Do you want to throw an exception (Y or N): "); + var userAnswer = Console.ReadLine(); + if (userAnswer?.ToLower() == "n") + { + throwEx = false; + } + + var dal = new InventoryDAL(); + + // Process customer 1 – enter the id for the customer to move. + dal.ProcessCreditRisk(throwEx, 1); + Console.WriteLine("Check CreditRisk table for results"); + Console.ReadLine(); + } + + public static void DoBulkCopy() + { + Console.WriteLine(" ************** Do Bulk Copy ************** "); + var cars = new List + { + new Car() {Color = "Blue", Make = "Honda", PetName = "MyCar1"}, + new Car() {Color = "Red", Make = "Volvo", PetName = "MyCar2"}, + new Car() {Color = "White", Make = "VW", PetName = "MyCar3"}, + new Car() {Color = "Yellow", Make = "Toyota", PetName = "MyCar4"} + }; + ProcessBulkImport.ExecuteBulkImport(cars, "Inventory"); + InventoryDAL dal = new InventoryDAL(); + var list = dal.GetAllInventory(); + Console.WriteLine(" ************** All Cars ************** "); + Console.WriteLine("CarId\tMake\tColor\tPet Name"); + foreach (var itm in list) + { + Console.WriteLine($"{itm.CarId}\t{itm.Make}\t{itm.Color}\t{itm.PetName}"); + } + Console.WriteLine(); + } + } +} \ No newline at end of file diff --git a/Chapter_21/AutoLotDAL/AutoLotClient/Properties/AssemblyInfo.cs b/Chapter_21/AutoLotDAL/AutoLotClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f8461c0 --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotClient")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8aea202e-4c42-4279-94b3-e984df267769")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_21/AutoLotDAL/AutoLotDAL.sln b/Chapter_21/AutoLotDAL/AutoLotDAL.sln new file mode 100644 index 0000000..8816935 --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotDAL.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL", "AutoLotDAL\AutoLotDAL.csproj", "{76EBA30B-7574-4562-9746-E0EDC6A31E78}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotClient", "AutoLotClient\AutoLotClient.csproj", "{8AEA202E-4C42-4279-94B3-E984DF267769}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {76EBA30B-7574-4562-9746-E0EDC6A31E78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {76EBA30B-7574-4562-9746-E0EDC6A31E78}.Debug|Any CPU.Build.0 = Debug|Any CPU + {76EBA30B-7574-4562-9746-E0EDC6A31E78}.Release|Any CPU.ActiveCfg = Release|Any CPU + {76EBA30B-7574-4562-9746-E0EDC6A31E78}.Release|Any CPU.Build.0 = Release|Any CPU + {8AEA202E-4C42-4279-94B3-E984DF267769}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8AEA202E-4C42-4279-94B3-E984DF267769}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8AEA202E-4C42-4279-94B3-E984DF267769}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8AEA202E-4C42-4279-94B3-E984DF267769}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_21/AutoLotDAL/AutoLotDAL/AutoLotDAL.csproj b/Chapter_21/AutoLotDAL/AutoLotDAL/AutoLotDAL.csproj new file mode 100644 index 0000000..583ec7f --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotDAL/AutoLotDAL.csproj @@ -0,0 +1,50 @@ + + + + + Debug + AnyCPU + {76EBA30B-7574-4562-9746-E0EDC6A31E78} + Library + Properties + AutoLotDAL + AutoLotDAL + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_21/AutoLotDAL/AutoLotDAL/BulkImport/MyDataReader.cs b/Chapter_21/AutoLotDAL/AutoLotDAL/BulkImport/MyDataReader.cs new file mode 100644 index 0000000..20b981f --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotDAL/BulkImport/MyDataReader.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Reflection; +using AutoLotDAL.Models; + +namespace AutoLotDAL.BulkImport +{ + public interface IMyDataReader : IDataReader + { + List Records { get; set; } + } + + public class MyDataReader : IMyDataReader + { + private int _currentIndex = -1; + private readonly PropertyInfo[] _propertyInfos; + private readonly Dictionary _nameDictionary; + + public MyDataReader() + { + _propertyInfos = typeof(T).GetProperties(); + _nameDictionary = _propertyInfos + .Select((x, index) => new { x.Name, index }) + .ToDictionary(pair => pair.Name, pair => pair.index); + } + + public MyDataReader(List records) : this() + { + Records = records; + } + public List Records { get; set; } + + public void Dispose() + { + + } +public bool Read() +{ + if ((_currentIndex + 1) >= Records.Count) return false; + _currentIndex++; + return true; +} + +public int FieldCount + => _propertyInfos.Length; + +public string GetName(int i) + => i >= 0 && i < FieldCount ? _propertyInfos[i].Name : string.Empty; + +public int GetOrdinal(string name) + => _nameDictionary.ContainsKey(name) ? _nameDictionary[name] : -1; + +public object GetValue(int i) + => _propertyInfos[i].GetValue(Records[_currentIndex]); + +//public object GetValue(int i) +//{ +// Car currentRecord = Records[_currentIndex] as Car; +// switch (i) +// { +// case 0: return currentRecord.CarId; +// case 1: return currentRecord.Color; +// case 2: return currentRecord.Make; +// case 3: return currentRecord.PetName; +// default: return string.Empty; +// } +//} + + public string GetDataTypeName(int i) => throw new NotImplementedException(); + + public Type GetFieldType(int i) => throw new NotImplementedException(); + + public int GetValues(object[] values) => throw new NotImplementedException(); + + public bool GetBoolean(int i) => throw new NotImplementedException(); + + public byte GetByte(int i) => throw new NotImplementedException(); + + public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) + => throw new NotImplementedException(); + + public char GetChar(int i) => throw new NotImplementedException(); + + public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) + => throw new NotImplementedException(); + + public Guid GetGuid(int i) => throw new NotImplementedException(); + + public short GetInt16(int i) => throw new NotImplementedException(); + + public int GetInt32(int i) => throw new NotImplementedException(); + + public long GetInt64(int i) => throw new NotImplementedException(); + + public float GetFloat(int i) => throw new NotImplementedException(); + + public double GetDouble(int i) => throw new NotImplementedException(); + + public string GetString(int i) => throw new NotImplementedException(); + + public decimal GetDecimal(int i) => throw new NotImplementedException(); + + public DateTime GetDateTime(int i) => throw new NotImplementedException(); + + public IDataReader GetData(int i) => throw new NotImplementedException(); + + public bool IsDBNull(int i) => throw new NotImplementedException(); + + object IDataRecord.this[int i] => throw new NotImplementedException(); + + object IDataRecord.this[string name] => throw new NotImplementedException(); + + public void Close() => throw new NotImplementedException(); + + public DataTable GetSchemaTable() => throw new NotImplementedException(); + + public bool NextResult() => throw new NotImplementedException(); + + public int Depth { get; } + + public bool IsClosed { get; } + + public int RecordsAffected { get; } + + } +} diff --git a/Chapter_21/AutoLotDAL/AutoLotDAL/BulkImport/ProcessBulkImport.cs b/Chapter_21/AutoLotDAL/AutoLotDAL/BulkImport/ProcessBulkImport.cs new file mode 100644 index 0000000..f1e7dd2 --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotDAL/BulkImport/ProcessBulkImport.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; + +namespace AutoLotDAL.BulkImport +{ + public static class ProcessBulkImport + { + private static SqlConnection _sqlConnection = null; + + private static readonly string _connectionString = + @"Data Source = (localdb)\mssqllocaldb;Integrated Security=true;Initial Catalog=AutoLot"; + + private static void OpenConnection() + { + _sqlConnection = new SqlConnection {ConnectionString = _connectionString}; + _sqlConnection.Open(); + } + + private static void CloseConnection() + { + if (_sqlConnection?.State != ConnectionState.Closed) + { + _sqlConnection?.Close(); + } + } + + public static void ExecuteBulkImport(IEnumerable records, string tableName) + { + OpenConnection(); + using (SqlConnection conn = _sqlConnection) + { + SqlBulkCopy bc = new SqlBulkCopy(conn) + { + DestinationTableName = tableName + }; + var dataReader = new MyDataReader(records.ToList()); + try + { + bc.WriteToServer(dataReader); + } + catch (Exception ex) + { + //Should do something here + } + finally + { + CloseConnection(); + } + } + } + } +} \ No newline at end of file diff --git a/Chapter_21/AutoLotDAL/AutoLotDAL/DataOperations/InventoryDAL.cs b/Chapter_21/AutoLotDAL/AutoLotDAL/DataOperations/InventoryDAL.cs new file mode 100644 index 0000000..7d320d0 --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotDAL/DataOperations/InventoryDAL.cs @@ -0,0 +1,305 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Data; +using System.Data.SqlClient; +using AutoLotDAL.Models; + +namespace AutoLotDAL.DataOperations +{ + public class InventoryDAL + { + private readonly string _connectionString; + private SqlConnection _sqlConnection = null; + + public InventoryDAL() : this( + @"Data Source = (localdb)\mssqllocaldb;Integrated Security=true;Initial Catalog=AutoLot") + { + } + + public InventoryDAL(string connectionString) + => _connectionString = connectionString; + + private void OpenConnection() + { + _sqlConnection = new SqlConnection {ConnectionString = _connectionString}; + _sqlConnection.Open(); + } + + private void CloseConnection() + { + if (_sqlConnection?.State != ConnectionState.Closed) + { + _sqlConnection?.Close(); + } + } + + public List GetAllInventory() + { + OpenConnection(); + // This will hold the records. + List inventory = new List(); + + // Prep command object. + string sql = "Select * From Inventory"; + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + command.CommandType = CommandType.Text; + SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection); + while (dataReader.Read()) + { + inventory.Add(new Car + { + CarId = (int) dataReader["CarId"], + Color = (string) dataReader["Color"], + Make = (string) dataReader["Make"], + PetName = (string) dataReader["PetName"] + }); + } + dataReader.Close(); + } + return inventory; + } + + public Car GetCar(int id) + { + OpenConnection(); + Car car = null; + string sql = $"Select * From Inventory where CarId = {id}"; + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + command.CommandType = CommandType.Text; + SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection); + while (dataReader.Read()) + { + car = new Car + { + CarId = (int) dataReader["CarId"], + Color = (string) dataReader["Color"], + Make = (string) dataReader["Make"], + PetName = (string) dataReader["PetName"] + }; + } + dataReader.Close(); + } + return car; + } + + public void InsertAuto(string color, string make, string petName) + { + OpenConnection(); + // Format and execute SQL statement. + string sql = $"Insert Into Inventory (Make, Color, PetName) Values ('{make}', '{color}', '{petName}')"; + + // Execute using our connection. + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + command.CommandType = CommandType.Text; + command.ExecuteNonQuery(); + } + CloseConnection(); + } + //public void InsertAuto(Car car) + //{ + // OpenConnection(); + // // Format and execute SQL statement. + // string sql = "Insert Into Inventory (Make, Color, PetName) Values " + + // $"('{car.Make}', '{car.Color}', '{car.PetName}')"; + + // // Execute using our connection. + // using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + // { + // command.CommandType = CommandType.Text; + // command.ExecuteNonQuery(); + // } + // CloseConnection(); + //} + public void InsertAuto(Car car) + { + OpenConnection(); + // Note the "placeholders" in the SQL query. + string sql = "Insert Into Inventory" + + "(Make, Color, PetName) Values" + + "(@Make, @Color, @PetName)"; + + // This command will have internal parameters. + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + // Fill params collection. + SqlParameter parameter = new SqlParameter + { + ParameterName = "@Make", + Value = car.Make, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + parameter = new SqlParameter + { + ParameterName = "@Color", + Value = car.Color, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + parameter = new SqlParameter + { + ParameterName = "@PetName", + Value = car.PetName, + SqlDbType = SqlDbType.Char, + Size = 10 + }; + command.Parameters.Add(parameter); + + command.ExecuteNonQuery(); + CloseConnection(); + } + } + + public void DeleteCar(int id) + { + OpenConnection(); + // Get ID of car to delete, then do so. + string sql = $"Delete from Inventory where CarId = '{id}'"; + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + try + { + command.CommandType = CommandType.Text; + command.ExecuteNonQuery(); + } + catch (SqlException ex) + { + Exception error = new Exception("Sorry! That car is on order!", ex); + throw error; + } + } + CloseConnection(); + } + + public void UpdateCarPetName(int id, string newPetName) + { + OpenConnection(); + // Get ID of car to modify the pet name. + string sql = $"Update Inventory Set PetName = '{newPetName}' Where CarId = '{id}'"; + using (SqlCommand command = new SqlCommand(sql, _sqlConnection)) + { + command.ExecuteNonQuery(); + } + CloseConnection(); + } + + public string LookUpPetName(int carId) + { + OpenConnection(); + string carPetName; + + // Establish name of stored proc. + using (SqlCommand command = new SqlCommand("GetPetName", _sqlConnection)) + { + command.CommandType = CommandType.StoredProcedure; + + // Input param. + SqlParameter param = new SqlParameter + { + ParameterName = "@carId", + SqlDbType = SqlDbType.Int, + Value = carId, + Direction = ParameterDirection.Input + }; + command.Parameters.Add(param); + + // Output param. + param = new SqlParameter + { + ParameterName = "@petName", + SqlDbType = SqlDbType.Char, + Size = 10, + Direction = ParameterDirection.Output + }; + command.Parameters.Add(param); + + // Execute the stored proc. + command.ExecuteNonQuery(); + + // Return output param. + carPetName = (string) command.Parameters["@petName"].Value; + CloseConnection(); + } + return carPetName; + } + + public void ProcessCreditRisk(bool throwEx, int custId) + { + OpenConnection(); + // First, look up current name based on customer ID. + string fName; + string lName; + var cmdSelect = + new SqlCommand($"Select * from Customers where CustId = {custId}", + _sqlConnection); + using (var dataReader = cmdSelect.ExecuteReader()) + { + if (dataReader.HasRows) + { + dataReader.Read(); + fName = (string) dataReader["FirstName"]; + lName = (string) dataReader["LastName"]; + } + else + { + CloseConnection(); + return; + } + } + + // Create command objects that represent each step of the operation. + var cmdRemove = + new SqlCommand($"Delete from Customers where CustId = {custId}", + _sqlConnection); + + var cmdInsert = + new SqlCommand("Insert Into CreditRisks" + + $"(FirstName, LastName) Values('{fName}', '{lName}')", + _sqlConnection); + + // We will get this from the connection object. + SqlTransaction tx = null; + try + { + tx = _sqlConnection.BeginTransaction(); + + // Enlist the commands into this transaction. + cmdInsert.Transaction = tx; + cmdRemove.Transaction = tx; + + // Execute the commands. + cmdInsert.ExecuteNonQuery(); + cmdRemove.ExecuteNonQuery(); + + // Simulate error. + if (throwEx) + { + throw new Exception("Sorry! Database error! Tx failed..."); + } + + // Commit it! + tx.Commit(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + // Any error will roll back transaction. Using the new conditional access operator to check for null. + tx?.Rollback(); + } + finally + { + CloseConnection(); + } + } + } +} \ No newline at end of file diff --git a/Chapter_21/AutoLotDAL/AutoLotDAL/Models/Car.cs b/Chapter_21/AutoLotDAL/AutoLotDAL/Models/Car.cs new file mode 100644 index 0000000..a23246e --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotDAL/Models/Car.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutoLotDAL.Models +{ + public class Car + { + public int CarId { get; set; } + public string Color { get; set; } + public string Make { get; set; } + public string PetName { get; set; } + } +} \ No newline at end of file diff --git a/Chapter_21/AutoLotDAL/AutoLotDAL/Properties/AssemblyInfo.cs b/Chapter_21/AutoLotDAL/AutoLotDAL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..761ad1d --- /dev/null +++ b/Chapter_21/AutoLotDAL/AutoLotDAL/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDAL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDAL")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("76eba30b-7574-4562-9746-e0edc6a31e78")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_21/AutoLotDataReader/AutoLotDataReader.sln b/Chapter_21/AutoLotDataReader/AutoLotDataReader.sln new file mode 100644 index 0000000..a8f974e --- /dev/null +++ b/Chapter_21/AutoLotDataReader/AutoLotDataReader.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDataReader", "AutoLotDataReader\AutoLotDataReader.csproj", "{1721ABF8-F2C2-4720-A4B5-B3816039E4CD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1721ABF8-F2C2-4720-A4B5-B3816039E4CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1721ABF8-F2C2-4720-A4B5-B3816039E4CD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1721ABF8-F2C2-4720-A4B5-B3816039E4CD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1721ABF8-F2C2-4720-A4B5-B3816039E4CD}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_21/AutoLotDataReader/AutoLotDataReader/App.config b/Chapter_21/AutoLotDataReader/AutoLotDataReader/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_21/AutoLotDataReader/AutoLotDataReader/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_21/AutoLotDataReader/AutoLotDataReader/AutoLotDataReader.csproj b/Chapter_21/AutoLotDataReader/AutoLotDataReader/AutoLotDataReader.csproj new file mode 100644 index 0000000..8542725 --- /dev/null +++ b/Chapter_21/AutoLotDataReader/AutoLotDataReader/AutoLotDataReader.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {1721ABF8-F2C2-4720-A4B5-B3816039E4CD} + Exe + AutoLotDataReader + AutoLotDataReader + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_21/AutoLotDataReader/AutoLotDataReader/Program.cs b/Chapter_21/AutoLotDataReader/AutoLotDataReader/Program.cs new file mode 100644 index 0000000..43823bb --- /dev/null +++ b/Chapter_21/AutoLotDataReader/AutoLotDataReader/Program.cs @@ -0,0 +1,93 @@ +using System; +using System.Data.SqlClient; +using static System.Console; + +namespace AutoLotDataReader +{ + class Program + { + static void FirstVersion() + { + WriteLine("***** Fun with Data Readers *****\n"); + // Create and open a connection. + using (SqlConnection connection = new SqlConnection()) + { + connection.ConnectionString = + @"Data Source=(localdb)\mssqllocaldb;Integrated Security=true;" + + "Initial Catalog=AutoLot"; + connection.Open(); + + // Create a SQL command object. + string sql = "Select * From Inventory"; + SqlCommand myCommand = new SqlCommand(sql, connection); + + // Obtain a data reader a la ExecuteReader(). + using (SqlDataReader myDataReader = myCommand.ExecuteReader()) + { + // Loop over the results. + while (myDataReader.Read()) + { + WriteLine($"-> Make: {myDataReader["Make"]}, PetName: {myDataReader["PetName"]}, Color: {myDataReader["Color"]}."); + } + } + } + ReadLine(); + } + static void Main(string[] args) + { + WriteLine("***** Fun with Data Readers *****\n"); + // Create a connection string via the builder object. + var cnStringBuilder = new SqlConnectionStringBuilder + { + InitialCatalog = "AutoLot", + DataSource = @"(localdb)\mssqllocaldb", + ConnectTimeout = 30, + IntegratedSecurity = true + }; + + // Create an open a connection. + using (var connection = new SqlConnection()) + { + connection.ConnectionString = cnStringBuilder.ConnectionString; + connection.Open(); + ShowConnectionStatus(connection); + + // Create a SQL command object. + string sql = "Select * From Inventory;Select * from Customers"; + + using (SqlCommand myCommand = new SqlCommand(sql, connection)) + { + //iterate over the inventory & customers + // Obtain a data reader a la ExecuteReader(). + using (SqlDataReader myDataReader = myCommand.ExecuteReader()) + { + do + { + while (myDataReader.Read()) + { + WriteLine("***** Record *****"); + for (int i = 0; i < myDataReader.FieldCount; i++) + { + WriteLine($"{myDataReader.GetName(i)} = {myDataReader.GetValue(i)}"); + } + WriteLine(); + } + } while (myDataReader.NextResult()); + } + } + } + ReadLine(); + + } + static void ShowConnectionStatus(SqlConnection connection) + { + // Show various stats about current connection object. + WriteLine("***** Info about your connection *****"); + WriteLine($"Database location: {connection.DataSource}"); + WriteLine($"Database name: {connection.Database}"); + WriteLine($"Timeout: {connection.ConnectionTimeout}"); + WriteLine($"Connection state: {connection.State}\n"); + } + + } +} diff --git a/Chapter_21/AutoLotDataReader/AutoLotDataReader/Properties/AssemblyInfo.cs b/Chapter_21/AutoLotDataReader/AutoLotDataReader/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0e69fa8 --- /dev/null +++ b/Chapter_21/AutoLotDataReader/AutoLotDataReader/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDataReader")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDataReader")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1721abf8-f2c2-4720-a4b5-b3816039e4cd")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_21/DataProviderFactory/DataProviderFactory.sln b/Chapter_21/DataProviderFactory/DataProviderFactory.sln new file mode 100644 index 0000000..3598017 --- /dev/null +++ b/Chapter_21/DataProviderFactory/DataProviderFactory.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataProviderFactory", "DataProviderFactory\DataProviderFactory.csproj", "{399FF950-414F-4FFB-9E73-0DC7D8E0AD27}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {399FF950-414F-4FFB-9E73-0DC7D8E0AD27}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {399FF950-414F-4FFB-9E73-0DC7D8E0AD27}.Debug|Any CPU.Build.0 = Debug|Any CPU + {399FF950-414F-4FFB-9E73-0DC7D8E0AD27}.Release|Any CPU.ActiveCfg = Release|Any CPU + {399FF950-414F-4FFB-9E73-0DC7D8E0AD27}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_21/DataProviderFactory/DataProviderFactory/App.config b/Chapter_21/DataProviderFactory/DataProviderFactory/App.config new file mode 100644 index 0000000..4e8264e --- /dev/null +++ b/Chapter_21/DataProviderFactory/DataProviderFactory/App.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_21/DataProviderFactory/DataProviderFactory/DataProviderFactory.csproj b/Chapter_21/DataProviderFactory/DataProviderFactory/DataProviderFactory.csproj new file mode 100644 index 0000000..dae4a13 --- /dev/null +++ b/Chapter_21/DataProviderFactory/DataProviderFactory/DataProviderFactory.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {399FF950-414F-4FFB-9E73-0DC7D8E0AD27} + Exe + DataProviderFactory + DataProviderFactory + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_21/DataProviderFactory/DataProviderFactory/Program.cs b/Chapter_21/DataProviderFactory/DataProviderFactory/Program.cs new file mode 100644 index 0000000..d63a164 --- /dev/null +++ b/Chapter_21/DataProviderFactory/DataProviderFactory/Program.cs @@ -0,0 +1,77 @@ +using System; +using System.Configuration; +using System.Data.Common; +using System.Data.SqlClient; +using static System.Console; + +namespace DataFactoryProvider +{ + class Program + { + static void Main(string[] args) + { + WriteLine("***** Fun with Data Provider Factories *****\n"); + + // Get Connection string/provider from *.config. + string dataProvider = + ConfigurationManager.AppSettings["provider"]; + //string connectionString = + // ConfigurationManager.AppSettings["connectionString"]; + //string connectionString = + // ConfigurationManager.ConnectionStrings["AutoLotSqlProvider"].ConnectionString; + string connectionString = + ConfigurationManager.ConnectionStrings["AutoLotOleDbProvider"].ConnectionString; + + // Get the factory provider. + DbProviderFactory factory = DbProviderFactories.GetFactory(dataProvider); + + // Now get the connection object. + using (DbConnection connection = factory.CreateConnection()) + { + if (connection == null) + { + ShowError("Connection"); + return; + } + WriteLine($"Your connection object is a: {connection.GetType().Name}"); + connection.ConnectionString = connectionString; + connection.Open(); + + var sqlConnection = connection as SqlConnection; + if (sqlConnection != null) + { + // Print out which version of SQL Server is used. + WriteLine(sqlConnection.ServerVersion); + } + + // Make command object. + DbCommand command = factory.CreateCommand(); + if (command == null) + { + ShowError("Command"); + return; + } + WriteLine($"Your command object is a: {command.GetType().Name}"); + command.Connection = connection; + command.CommandText = "Select * From Inventory"; + + // Print out data with data reader. + using (DbDataReader dataReader = command.ExecuteReader()) + { + WriteLine($"Your data reader object is a: {dataReader.GetType().Name}"); + + WriteLine("\n***** Current Inventory *****"); + while (dataReader.Read()) + WriteLine($"-> Car #{dataReader["CarId"]} is a {dataReader["Make"]}."); + } + } + ReadLine(); + } + + private static void ShowError(string objectName) + { + WriteLine($"There was an issue creating the {objectName}"); + ReadLine(); + } + } +} diff --git a/Chapter_21/DataProviderFactory/DataProviderFactory/Properties/AssemblyInfo.cs b/Chapter_21/DataProviderFactory/DataProviderFactory/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3018f2a --- /dev/null +++ b/Chapter_21/DataProviderFactory/DataProviderFactory/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DataProviderFactory")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DataProviderFactory")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("399ff950-414f-4ffb-9e73-0dc7d8e0ad27")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_21/MyConnectionFactory/MyConnectionFactory.sln b/Chapter_21/MyConnectionFactory/MyConnectionFactory.sln new file mode 100644 index 0000000..a04ef08 --- /dev/null +++ b/Chapter_21/MyConnectionFactory/MyConnectionFactory.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyConnectionFactory", "MyConnectionFactory\MyConnectionFactory.csproj", "{AD8E46D9-668B-44E3-9DE9-34B1F2DD09BE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AD8E46D9-668B-44E3-9DE9-34B1F2DD09BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AD8E46D9-668B-44E3-9DE9-34B1F2DD09BE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AD8E46D9-668B-44E3-9DE9-34B1F2DD09BE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AD8E46D9-668B-44E3-9DE9-34B1F2DD09BE}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_21/MyConnectionFactory/MyConnectionFactory/App.config b/Chapter_21/MyConnectionFactory/MyConnectionFactory/App.config new file mode 100644 index 0000000..cc6ec6f --- /dev/null +++ b/Chapter_21/MyConnectionFactory/MyConnectionFactory/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_21/MyConnectionFactory/MyConnectionFactory/MyConnectionFactory.csproj b/Chapter_21/MyConnectionFactory/MyConnectionFactory/MyConnectionFactory.csproj new file mode 100644 index 0000000..ef7e9ab --- /dev/null +++ b/Chapter_21/MyConnectionFactory/MyConnectionFactory/MyConnectionFactory.csproj @@ -0,0 +1,55 @@ + + + + + Debug + AnyCPU + {AD8E46D9-668B-44E3-9DE9-34B1F2DD09BE} + Exe + MyConnectionFactory + MyConnectionFactory + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + Designer + + + + \ No newline at end of file diff --git a/Chapter_21/MyConnectionFactory/MyConnectionFactory/Program.cs b/Chapter_21/MyConnectionFactory/MyConnectionFactory/Program.cs new file mode 100644 index 0000000..23c51af --- /dev/null +++ b/Chapter_21/MyConnectionFactory/MyConnectionFactory/Program.cs @@ -0,0 +1,66 @@ +using System; +using System.Configuration; +// Need these to get definitions of common interfaces, +// and various connection objects for our test. +using System.Data; +using System.Data.Odbc; +using System.Data.OleDb; +using System.Data.SqlClient; +using static System.Console; + +namespace MyConnectionFactory +{ + // A list of possible providers. + enum DataProvider + { SqlServer, OleDb, Odbc, None } + + class Program + { + static void Main(string[] args) + { + WriteLine("**** Very Simple Connection Factory *****\n"); + // Read the provider key. + string dataProviderString = ConfigurationManager.AppSettings["provider"]; + // Transform string to enum. + DataProvider dataProvider = DataProvider.None; + if (Enum.IsDefined(typeof (DataProvider), dataProviderString)) + { + dataProvider = (DataProvider) Enum.Parse(typeof (DataProvider), dataProviderString); + } + else + { + WriteLine("Sorry, no provider exists!"); + ReadLine(); + return; + } + // Get a specific connection. + IDbConnection myConnection = GetConnection(dataProvider); + WriteLine($"Your connection is a {myConnection?.GetType().Name ?? "unrecognized type"}"); + // Open, use and close connection... + ReadLine(); + } + + // This method returns a specific connection object + // based on the value of a DataProvider enum. + static IDbConnection GetConnection(DataProvider dataProvider) + { + IDbConnection connection = null; + switch (dataProvider) + { + case DataProvider.SqlServer: + connection = new SqlConnection(); + break; + case DataProvider.OleDb: + connection = new OleDbConnection(); + break; + case DataProvider.Odbc: + connection = new OdbcConnection(); + break; + default: + return null; + } + return connection; + } + + } +} diff --git a/Chapter_21/MyConnectionFactory/MyConnectionFactory/Properties/AssemblyInfo.cs b/Chapter_21/MyConnectionFactory/MyConnectionFactory/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..29f15d5 --- /dev/null +++ b/Chapter_21/MyConnectionFactory/MyConnectionFactory/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MyConnectionFactory")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MyConnectionFactory")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ad8e46d9-668b-44e3-9de9-34b1f2dd09be")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp.sln b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp.sln new file mode 100644 index 0000000..03300da --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotConsoleApp", "AutoLotConsoleApp\AutoLotConsoleApp.csproj", "{325CB72D-12AA-4837-A44C-0E8394B135BF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {325CB72D-12AA-4837-A44C-0E8394B135BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {325CB72D-12AA-4837-A44C-0E8394B135BF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {325CB72D-12AA-4837-A44C-0E8394B135BF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {325CB72D-12AA-4837-A44C-0E8394B135BF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/App.config b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/App.config new file mode 100644 index 0000000..e837250 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/App.config @@ -0,0 +1,23 @@ + + + + +
    + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/AutoLotConsoleApp.csproj b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/AutoLotConsoleApp.csproj new file mode 100644 index 0000000..9d0fe04 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/AutoLotConsoleApp.csproj @@ -0,0 +1,69 @@ + + + + + Debug + AnyCPU + {325CB72D-12AA-4837-A44C-0E8394B135BF} + Exe + AutoLotConsoleApp + AutoLotConsoleApp + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/AutoLotEntities.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/AutoLotEntities.cs new file mode 100644 index 0000000..9a16423 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/AutoLotEntities.cs @@ -0,0 +1,28 @@ +namespace AutoLotConsoleApp.EF +{ + using System; + using System.Data.Entity; + using System.ComponentModel.DataAnnotations.Schema; + using System.Linq; + + public partial class AutoLotEntities : DbContext + { + public AutoLotEntities() + : base("name=AutoLotConnection") + { + } + + public virtual DbSet CreditRisks { get; set; } + public virtual DbSet Customers { get; set; } + public virtual DbSet Cars { get; set; } + public virtual DbSet Orders { get; set; } + + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + modelBuilder.Entity() + .HasMany(e => e.Orders) + .WithRequired(e => e.Car) + .WillCascadeOnDelete(false); + } + } +} diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Car.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Car.cs new file mode 100644 index 0000000..bb110e3 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Car.cs @@ -0,0 +1,31 @@ +namespace AutoLotConsoleApp.EF +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Data.Entity.Spatial; + + [Table("Inventory")] + public partial class Car + { + public Car() + { + Orders = new HashSet(); + } + + [Key] + public int CarId { get; set; } + + [StringLength(50)] + public string Make { get; set; } + + [StringLength(50)] + public string Color { get; set; } + + [StringLength(50),Column("PetName")] + public string CarNickName { get; set; } + + public virtual ICollection Orders { get; set; } + } +} diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/CarPartial.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/CarPartial.cs new file mode 100644 index 0000000..27af750 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/CarPartial.cs @@ -0,0 +1,14 @@ +using System; + +namespace AutoLotConsoleApp.EF +{ + public partial class Car + { + public override string ToString() + { + // Since the PetName column could be empty, supply + // the default name of **No Name**. + return $"{this.CarNickName ?? "**No Name**"} is a {this.Color} {this.Make} with ID {this.CarId}."; + } + } +} \ No newline at end of file diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/CreditRisk.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/CreditRisk.cs new file mode 100644 index 0000000..4143f24 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/CreditRisk.cs @@ -0,0 +1,20 @@ +namespace AutoLotConsoleApp.EF +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Data.Entity.Spatial; + + public partial class CreditRisk + { + [Key] + public int CustID { get; set; } + + [StringLength(50)] + public string FirstName { get; set; } + + [StringLength(50)] + public string LastName { get; set; } + } +} diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Customer.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Customer.cs new file mode 100644 index 0000000..1f15371 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Customer.cs @@ -0,0 +1,27 @@ +namespace AutoLotConsoleApp.EF +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Data.Entity.Spatial; + + public partial class Customer + { + public Customer() + { + Orders = new HashSet(); + } + + [Key] + public int CustID { get; set; } + + [StringLength(50)] + public string FirstName { get; set; } + + [StringLength(50)] + public string LastName { get; set; } + + public virtual ICollection Orders { get; set; } + } +} diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Order.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Order.cs new file mode 100644 index 0000000..2ca3e20 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/EF/Order.cs @@ -0,0 +1,25 @@ +namespace AutoLotConsoleApp.EF +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Data.Entity.Spatial; + + public partial class Order + { + public int OrderId { get; set; } + + public int CustId { get; set; } + + //public int CarId { get; set; } + [Column("CarId")] + public int Foo { get; set; } + + public virtual Customer Customer { get; set; } + + [ForeignKey(nameof(Foo))] + public virtual Car Car { get; set; } + } + +} \ No newline at end of file diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Models/ShortCar.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Models/ShortCar.cs new file mode 100644 index 0000000..bd639cd --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Models/ShortCar.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutoLotConsoleApp.Models +{ + public class ShortCar + { + public int CarId { get; set; } + public string Make { get; set; } + public override string ToString() => $"{this.Make} with ID {this.CarId}."; + } +} diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Program.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Program.cs new file mode 100644 index 0000000..574927d --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Program.cs @@ -0,0 +1,224 @@ +using System; +using System.CodeDom; +using System.Collections.Generic; +using System.Data.Entity; +using System.Data.Entity.Infrastructure; +using System.Data.Entity.Migrations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotConsoleApp.EF; +using AutoLotConsoleApp.Models; +using static System.Console; + +namespace AutoLotConsoleApp +{ + class Program + { + static void Main(string[] args) + { + WriteLine("***** Fun with ADO.NET EF *****\n"); + int carId = AddNewRecord(); + RemoveRecord(carId); + //RemoveRecordUsingEntityState(carId); + //WriteLine(carId); + PrintAllInventory(); + //FunWithLinqQueries(); + //RemoveRecordsWithLinq(); + //UpdateRecord(carId); + //WriteLine("*******************************\n"); + //PrintAllInventory(); + ReadLine(); + } + + private static int AddNewRecord() + { + // Add record to the Inventory table of the AutoLot database. + using (var context = new AutoLotEntities()) + { + try + { + var car = new Car() + {Make = "Yugo", Color = "Brown", CarNickName = "Brownie"}; + context.Cars.Add(car); + context.SaveChanges(); + return car.CarId; + } + catch (Exception ex) + { + WriteLine(ex.InnerException?.Message); + return 0; + } + } + } + + private static void AddNewRecords(IEnumerable carsToAdd) + { + using (var context = new AutoLotEntities()) + { + context.Cars.AddRange(carsToAdd); + context.SaveChanges(); + } + } + + private static void PrintAllInventory() + { + // Select all items from the Inventory table of AutoLot, + // and print out the data using our custom ToString() + // of the Car entity class. + using (var context = new AutoLotEntities()) + { + foreach (Car c in context.Cars) + { + WriteLine(c); + } + foreach (Car c in context.Cars.SqlQuery( + "Select CarId,Make,Color,PetName as CarNickName from Inventory where Make=@p0", "BMW")) + { + WriteLine(c); + } + foreach (ShortCar c in context.Database.SqlQuery(typeof(ShortCar), "Select CarId,Make from Inventory")) + { + WriteLine(c); + } + foreach (Car c in context.Cars.Where(c => c.Make == "BMW")) + { + WriteLine(c); + } + WriteLine(context.Cars.Find(5)); + foreach (Car c in context.Cars) + { + foreach (Order o in c.Orders) + { + WriteLine(o.OrderId); + } + } + foreach (Car c in context.Cars.Include(c => c.Orders)) + { + foreach (Order o in c.Orders) + { + WriteLine(o.OrderId); + } + } + context.Configuration.LazyLoadingEnabled = false; + foreach (Car c in context.Cars) + { + context.Entry(c).Collection(x => x.Orders).Load(); + foreach (Order o in c.Orders) + { + WriteLine(o.OrderId); + } + } + foreach (Order o in context.Orders) + { + context.Entry(o).Reference(x => x.Car).Load(); + } + } + } + + private static void FunWithLinqQueries() + { + using (var context = new AutoLotEntities()) + { + // Get all data from the Inventory table. + // could also write: + // var allData = (from item in context.Inventories select item).ToArray(); + var allData = context.Cars.ToArray(); + + // Get a projection of new data. + var colorsMakes = from item in allData select new {item.Color, item.Make}; + foreach (var item in colorsMakes) + { + WriteLine(item); + } + + // Get only items where Color == "Black" + var blackCars = from item in allData where item.Color == "Black" select item; + foreach (var item in blackCars) + { + WriteLine(item); + } + } + } + + private static void ChainingLinqQueries() + { + using (var context = new AutoLotEntities()) + { + //Not executed + DbSet allData = context.Cars; + + //Not Executed. + var colorsMakes = from item in allData select new {item.Color, item.Make}; + + //Now it's executed + foreach (var item in colorsMakes) + { + WriteLine(item); + } + } + } + + private static void RemoveRecord(int carId) + { + // Find a car to delete by primary key. + using (var context = new AutoLotEntities()) + { + // See if we have it. + Car carToDelete = context.Cars.Find(carId); + if (carToDelete != null) + { + context.Cars.Remove(carToDelete); + //This code is purely demonstrative to show the entity state changed to Deleted + if (context.Entry(carToDelete).State != EntityState.Deleted) + { + throw new Exception("Unable to delete the record"); + } + context.SaveChanges(); + } + } + } + + private static void RemoveMultipleRecords(IEnumerable carsToRemove) + { + using (var context = new AutoLotEntities()) + { + //Each record must be loaded in the DbChangeTracker + context.Cars.RemoveRange(carsToRemove); + context.SaveChanges(); + } + } + + private static void RemoveRecordUsingEntityState(int carId) + { + using (var context = new AutoLotEntities()) + { + Car carToDelete = new Car() {CarId = carId}; + context.Entry(carToDelete).State = EntityState.Deleted; + try + { + context.SaveChanges(); + } + catch (DbUpdateConcurrencyException ex) + { + WriteLine(ex); + } + } + } + + private static void UpdateRecord(int carId) + { + using (var context = new AutoLotEntities()) + { + // Grab the car, change it, save! + Car carToUpdate = context.Cars.Find(carId); + if (carToUpdate != null) + { + WriteLine(context.Entry(carToUpdate).State); + carToUpdate.Color = "Blue"; + WriteLine(context.Entry(carToUpdate).State); + } + } + } + } +} \ No newline at end of file diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Properties/AssemblyInfo.cs b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4717f36 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotConsoleApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotConsoleApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("325cb72d-12aa-4837-a44c-0e8394b135bf")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/packages.config b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/packages.config new file mode 100644 index 0000000..bb66824 --- /dev/null +++ b/Chapter_22/AutoLotConsoleApp/AutoLotConsoleApp/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/App.config b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/App.config new file mode 100644 index 0000000..7e1d79c --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/App.config @@ -0,0 +1,17 @@ + + + + +
    + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/AutoLotDAL.Models.csproj b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/AutoLotDAL.Models.csproj new file mode 100644 index 0000000..d999eb7 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/AutoLotDAL.Models.csproj @@ -0,0 +1,63 @@ + + + + + Debug + AnyCPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB} + Library + Properties + AutoLotDAL.Models + AutoLotDAL.Models + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Base/EntityBase.cs b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Base/EntityBase.cs new file mode 100644 index 0000000..3ad6386 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Base/EntityBase.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations; + +namespace AutoLotDAL.Models.Base +{ + public class EntityBase + { + [Key] + public int Id { get; set; } + [Timestamp] + public byte[] Timestamp { get; set; } + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/CreditRisk.cs b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/CreditRisk.cs new file mode 100644 index 0000000..489182d --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/CreditRisk.cs @@ -0,0 +1,17 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Models +{ + public partial class CreditRisk : EntityBase + { + [StringLength(50)] + [Index("IDX_CreditRisk_Name", IsUnique = true, Order = 2)] + public string FirstName { get; set; } + + [StringLength(50)] + [Index("IDX_CreditRisk_Name", IsUnique = true, Order = 1)] + public string LastName { get; set; } + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Customer.cs b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Customer.cs new file mode 100644 index 0000000..4ae33fe --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Customer.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Models +{ +public partial class Customer : EntityBase +{ + [StringLength(50)] + public string FirstName { get; set; } + + [StringLength(50)] + public string LastName { get; set; } + + public virtual ICollection Orders { get; set; } = new HashSet(); + + [NotMapped] + public string FullName => $"{FirstName} {LastName}"; +} +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Inventory.cs b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Inventory.cs new file mode 100644 index 0000000..e0bc757 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Inventory.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Models +{ + [Table("Inventory")] + public partial class Inventory : EntityBase + { + [StringLength(50)] + public string Make { get; set; } + + [StringLength(50)] + public string Color { get; set; } + + [StringLength(50)] + public string PetName { get; set; } + + public virtual ICollection Orders { get; set; } + = new HashSet(); + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/InventoryPartial.cs b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/InventoryPartial.cs new file mode 100644 index 0000000..7665a50 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/InventoryPartial.cs @@ -0,0 +1,17 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace AutoLotDAL.Models +{ + public partial class Inventory + { + public override string ToString() + { + // Since the PetName column could be empty, supply + // the default name of **No Name**. + return $"{this.PetName ?? "**No Name**"} is a {this.Color} {this.Make} with ID {this.Id}."; + } + [NotMapped] + public string MakeColor => $"{Make} + ({Color})"; + + } +} \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Order.cs b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Order.cs new file mode 100644 index 0000000..9a0eee6 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Order.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations.Schema; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Models +{ + public partial class Order : EntityBase + { + public int CustomerId { get; set; } + public int CarId { get; set; } + [ForeignKey(nameof(CustomerId))] + public virtual Customer Customer { get; set; } + [ForeignKey(nameof(CarId))] + public virtual Inventory Car { get; set; } + } + +} \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Properties/AssemblyInfo.cs b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9a35541 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDAL.Models")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDAL.Models")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9a917d7c-885e-4d9a-818f-9955871a4fbb")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.Models/packages.config b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/packages.config new file mode 100644 index 0000000..4409173 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.Models/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL.sln b/Chapter_22/AutoLotDAL/AutoLotDAL.sln new file mode 100644 index 0000000..8ecb11f --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL", "AutoLotDAL\AutoLotDAL.csproj", "{7E5A8812-C303-4AE0-A6E7-4AC96EC11624}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotTestDrive", "AutoLotTestDrive\AutoLotTestDrive.csproj", "{764C55F4-4B69-4960-90A5-F1AD21AB857A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL.Models", "AutoLotDAL.Models\AutoLotDAL.Models.csproj", "{9A917D7C-885E-4D9A-818F-9955871A4FBB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624}.Release|Any CPU.Build.0 = Release|Any CPU + {764C55F4-4B69-4960-90A5-F1AD21AB857A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {764C55F4-4B69-4960-90A5-F1AD21AB857A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {764C55F4-4B69-4960-90A5-F1AD21AB857A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {764C55F4-4B69-4960-90A5-F1AD21AB857A}.Release|Any CPU.Build.0 = Release|Any CPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/App.config b/Chapter_22/AutoLotDAL/AutoLotDAL/App.config new file mode 100644 index 0000000..d31b2b7 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/App.config @@ -0,0 +1,22 @@ + + + + +
    + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/AutoLotDAL.csproj b/Chapter_22/AutoLotDAL/AutoLotDAL/AutoLotDAL.csproj new file mode 100644 index 0000000..28978e9 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/AutoLotDAL.csproj @@ -0,0 +1,86 @@ + + + + + Debug + AnyCPU + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624} + Library + Properties + AutoLotDAL + AutoLotDAL + v4.7 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + + + + + + + 201707262145588_Initial.cs + + + + 201707262157358_Final.cs + + + + + + + + + + + + + + 201707262145588_Initial.cs + + + 201707262157358_Final.cs + + + + + {9a917d7c-885e-4d9a-818f-9955871a4fbb} + AutoLotDAL.Models + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/EF/AutoLotEntities.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/EF/AutoLotEntities.cs new file mode 100644 index 0000000..b095df6 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/EF/AutoLotEntities.cs @@ -0,0 +1,72 @@ +using System; +using System.Data.Entity; +using System.Data.Entity.Core.Objects; +using System.Data.Entity.Infrastructure.Interception; +using AutoLotDAL.Interception; +using AutoLotDAL.Models; + +namespace AutoLotDAL.EF +{ + public partial class AutoLotEntities : DbContext + { + //static readonly DatabaseLogger DatabaseLogger = new DatabaseLogger("sqllog.txt"); + public AutoLotEntities() + : base("name=AutoLotConnection") + { + //DbInterception.Add(new ConsoleWriterInterceptor()); + + //DatabaseLogger.StartLogging(); + //DbInterception.Add(DatabaseLogger); + + //var context = (this as IObjectContextAdapter).ObjectContext; + //context.ObjectMaterialized += OnObjectMaterialized; + //context.SavingChanges += OnSavingChanges; + } + + protected override void Dispose(bool disposing) + { + //DbInterception.Remove(DatabaseLogger); + //DatabaseLogger.StopLogging(); + //base.Dispose(disposing); + } + + private void OnSavingChanges(object sender, EventArgs eventArgs) + { + //Sender is of type ObjectContext. Can get current and original values, and + // cancel /modify the save operation as desired. + var context = sender as ObjectContext; + if (context == null) return; + foreach (ObjectStateEntry item in + context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added)) + { + //Do something important here + if ((item.Entity as Inventory) != null) + { + var entity = (Inventory)item.Entity; + if (entity.Color == "Red") + { + item.RejectPropertyChanges(nameof(entity.Color)); + } + } + } + + } + + private void OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e) + { + } + + public virtual DbSet CreditRisks { get; set; } + public virtual DbSet Customers { get; set; } + public virtual DbSet Cars { get; set; } + public virtual DbSet Orders { get; set; } + + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + modelBuilder.Entity() + .HasMany(e => e.Orders) + .WithRequired(e => e.Car) + .WillCascadeOnDelete(false); + } + } +} \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/EF/MyDataInitializer.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/EF/MyDataInitializer.cs new file mode 100644 index 0000000..18b66ef --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/EF/MyDataInitializer.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Data.Entity.Migrations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.EF +{ + public class MyDataInitializer : DropCreateDatabaseAlways + { + protected override void Seed(AutoLotEntities context) + { + var customers = new List + { + new Customer {FirstName = "Dave", LastName = "Brenner"}, + new Customer {FirstName = "Matt", LastName = "Walton"}, + new Customer {FirstName = "Steve", LastName = "Hagen"}, + new Customer {FirstName = "Pat", LastName = "Walton"}, + new Customer {FirstName = "Bad", LastName = "Customer"}, + }; + customers.ForEach(x => context.Customers.AddOrUpdate( + c => new {c.FirstName, c.LastName}, x)); + var cars = new List + { + new Inventory {Make = "VW", Color = "Black", PetName = "Zippy"}, + new Inventory {Make = "Ford", Color = "Rust", PetName = "Rusty"}, + new Inventory {Make = "Saab", Color = "Black", PetName = "Mel"}, + new Inventory {Make = "Yugo", Color = "Yellow", PetName = "Clunker"}, + new Inventory {Make = "BMW", Color = "Black", PetName = "Bimmer"}, + new Inventory {Make = "BMW", Color = "Green", PetName = "Hank"}, + new Inventory {Make = "BMW", Color = "Pink", PetName = "Pinky"}, + new Inventory {Make = "Pinto", Color = "Black", PetName = "Pete"}, + new Inventory {Make = "Yugo", Color = "Brown", PetName = "Brownie"}, + }; + context.Cars.AddOrUpdate(x => new {x.Make, x.Color}, cars.ToArray()); + var orders = new List + { + new Order {Car = cars[0], Customer = customers[0]}, + new Order {Car = cars[1], Customer = customers[1]}, + new Order {Car = cars[2], Customer = customers[2]}, + new Order {Car = cars[3], Customer = customers[3]}, + }; + orders.ForEach(x => context.Orders.AddOrUpdate(c => new {c.CarId, c.CustomerId}, x)); + + context.CreditRisks.AddOrUpdate(x => new {x.FirstName, x.LastName}, + new CreditRisk + { + Id = customers[4].Id, + FirstName = customers[4].FirstName, + LastName = customers[4].LastName, + }); + } + } +} \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs new file mode 100644 index 0000000..91ad0db --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Data.Entity.Infrastructure.Interception; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using static System.Console; + +namespace AutoLotDAL.Interception +{ + public class ConsoleWriterInterceptor : IDbCommandInterceptor + { + private void WriteInfo(bool isAsync, string commandText) + { + WriteLine($"IsAsync: {isAsync}, Command Text: {commandText}"); + } + public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync,command.CommandText); + } + + public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.Designer.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.Designer.cs new file mode 100644 index 0000000..0ad26a2 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.Designer.cs @@ -0,0 +1,29 @@ +// +namespace AutoLotDAL.Migrations +{ + using System.CodeDom.Compiler; + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] + public sealed partial class Initial : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(Initial)); + + string IMigrationMetadata.Id + { + get { return "201707262145588_Initial"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.cs new file mode 100644 index 0000000..ab5da5a --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.cs @@ -0,0 +1,69 @@ +namespace AutoLotDAL.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class Initial : DbMigration + { + public override void Up() + { + CreateTable( + "dbo.Inventory", + c => new + { + CarId = c.Int(nullable: false, identity: true), + Make = c.String(maxLength: 50), + Color = c.String(maxLength: 50), + PetName = c.String(maxLength: 50), + }) + .PrimaryKey(t => t.CarId); + + CreateTable( + "dbo.Orders", + c => new + { + OrderId = c.Int(nullable: false, identity: true), + CustId = c.Int(nullable: false), + CarId = c.Int(nullable: false), + }) + .PrimaryKey(t => t.OrderId) + .ForeignKey("dbo.Customers", t => t.CustId, cascadeDelete: true) + .ForeignKey("dbo.Inventory", t => t.CarId) + .Index(t => t.CustId) + .Index(t => t.CarId); + + CreateTable( + "dbo.Customers", + c => new + { + CustID = c.Int(nullable: false, identity: true), + FirstName = c.String(maxLength: 50), + LastName = c.String(maxLength: 50), + }) + .PrimaryKey(t => t.CustID); + + CreateTable( + "dbo.CreditRisks", + c => new + { + CustID = c.Int(nullable: false, identity: true), + FirstName = c.String(maxLength: 50), + LastName = c.String(maxLength: 50), + }) + .PrimaryKey(t => t.CustID); + + } + + public override void Down() + { + DropForeignKey("dbo.Orders", "CarId", "dbo.Inventory"); + DropForeignKey("dbo.Orders", "CustId", "dbo.Customers"); + DropIndex("dbo.Orders", new[] { "CarId" }); + DropIndex("dbo.Orders", new[] { "CustId" }); + DropTable("dbo.CreditRisks"); + DropTable("dbo.Customers"); + DropTable("dbo.Orders"); + DropTable("dbo.Inventory"); + } + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.resx b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.resx new file mode 100644 index 0000000..a510e0b --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262145588_Initial.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + H4sIAAAAAAAEAO1azW7jNhC+F+g7CDoWqZVkUaAN7F2kTlIYzR/iZNHbgpHGDrEUpYpUEKPok/XQR+ordPRPUaIs2XG8LRZ72YicH858MxzO+J+//h5/ePGZ9QyRoAGf2EejQ9sC7gYe5cuJHcvF9z/aH95/+8343PNfrI/FvnfJPqTkYmI/SRmeOI5wn8AnYuRTNwpEsJAjN/Ad4gXO8eHhT87RkQPIwkZeljW+i7mkPqR/4J/TgLsQypiwq8ADJvLvuDJPuVrXxAcREhcm9mksg8tAnp1ejs4vbOuUUYJKzIEtbItwHkgiUcWTBwFzGQV8OQ/xA2H3qxBw34IwAbnqJ9X2vqc4PE5O4VSEBSs3FjLwBzI8epebxdHJNzKuXZoNDXeOBpar5NSp8Sb2jD8Dl0G0si1d2smURcnOmnEzT4xKsgOrWjwokYCASf4dWNOYyTiCCYdYRoQdWLfxI6Pur7C6Dz4Dn/CYMVVBVBHXah/w020UhBDJ1R0scrWnJJp5tuXUSR2dtqSsk2WnmnH57ti2rlEF8sigRIFigTkeEX4BDhGR4N0SKSFCJ848SO3YUEATd0U+QyENYYfBY1tX5OUS+FI+TewfMFou6At4xYdcgQdOMdSQRkYxrJMxDVgQ7VrILcjkP68u5po802Vqak3gTeQhlGzrDli6LJ5omIVzBb1PxaaLKPDvAqaiOV/7NA/iyE30Dgwb7km0BFlXbOxUYdIZPCmPYYGTkuwpaFLZm4RNSfhWgTNFi66Xt4ZHn1jvi0dktj0YC6wZwVigtbdWKfCgXbVisUUzbamhmL7eplfvIKmUHBInBdW+7pcEgGcbXDA53VsFygWNxG5SsybokuxIziZXwABo6xeACfqbQTsCj8o7Kj4PBHdJ9xXe/2d4m4B0KkTg0tRCWpIsEF1X9px71hp4Z1qrwYHKI3poiHhBFfARZ+u4uOFnwECCdepmj5MpES7xmsbCY3h9NSrvkkqjvEyqq/NdQwrCE6IEF4Thy08g4CmXTSxT7tKQsG6DaGQDgiA5bilEXzmDEHiC3e7D95beqMUS6aUQzQnr7DN2FFx1w61Rtpi8ay6oK/cqT0gdcbqLOxi/MW5MB+vlurbH5yDcmE6/lfRXx02WvJBGIgVEufz8wkoXKYiWm+9BQH75iTwr6ihI+M5BVidCNlWqbOKqAaM6g6IMaLDIEbSGvIjiNg5VNl3HpLzTW9kolYLGSDF+U6WywlF2GYogHQ/rL43yCDUTNIC1PtcrjAp99RukfsoeFmi+rJom6E5j/RKZagSy5vzGpLWNAYoioYyzqs3pZH3Ooh/qGBqi4ysShliuKA3S/Is1z7qj0+/nw3uHfsbDcUVLC7HUtpSEdiFL0FaT/pQHaRl3RiR5JEnFNPX8xjY9qxiCrZCmJI6mu4rYKzYn/6/lrqxLrCSYZt7NaS/wTH6St9NCVnFzB23anyaMRO0NiWnAYp935nIzj6yjqLLIvvTnkPcLa1pkn/rzKNuBKpfyY5PP2NHM2bi7Gk5rFKB1APSChzEp9AVIdn0MB4eBzmTOsr2mmtPQrOt0bV5S1nxrKDM7uAyA6Z4cW91Wm/u2vNiHu9dM2umZsxbPtDw/zFyU17DKSPncn1f14FVZVV+/HF8rddUW3q7qrw383UH81eMberxR9uhbSull+aOVOeO85Fg/HG7UINkW20ITPVMvqT/mKyHBHyUbRvPf2ZRRPG+14YpwugAhs7abfXx4dKwNmb+cga8jhMf6Tn33NHuliXHXNgcHTnzUcSt/JpH7lExttBZexXPwdPWVeGrD1I24DhxR7nFYuBNP1+eDqYhGF2LGPXiZ2H+kJCfW7LdPGdWBlWp4Yh1af243VOwtNyEaIHb4aG1vI4CdeLfR9X+lwNOb/LuNPFPV8NU9+3DP9iOXfQ5Z8j7mG89U3mqKYnpm/+eHJtuPSd7W8V0NsV2MQQY4fs9Dj2YXs3saoDi7a66RvUMmtvcYoJOznDZw7GGeerQxN3SnTRORzoFIG3/jHKFjXrJmXNIqRh227G2e0jpB6Rwg1DymtAq/3HFJTVkjNF/5kANGIs0eAMa+8jNyzDmCLisWyY/KObi1qC/3zPgiKHKPplGxRX9ygiQepoTTSNIFcSUuuyBE+tuRj4TFuOXcfwRvxm9iGcYSjwz+I6sZMEliXfLTuU9d5/FNmP4k6jWOgGpSPALc8J9jyrxS74uWh4mBRZId8wIz8aVMCs3lquR0HfCejHLzlUn9HvyQITNxw+fkGTbR7UHAJSyJuypaOWYm6x1RN/v4jJJlRHyR86jo8U/EsOe/vP8XxzOc+k0xAAA= + + + dbo + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.Designer.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.Designer.cs new file mode 100644 index 0000000..fd70503 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.Designer.cs @@ -0,0 +1,29 @@ +// +namespace AutoLotDAL.Migrations +{ + using System.CodeDom.Compiler; + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] + public sealed partial class Final : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(Final)); + + string IMigrationMetadata.Id + { + get { return "201707262157358_Final"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.cs new file mode 100644 index 0000000..92488bb --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.cs @@ -0,0 +1,84 @@ +namespace AutoLotDAL.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class Final : DbMigration + { + public override void Up() + { + DropForeignKey("dbo.Orders", "CarId", "dbo.Inventory"); + DropForeignKey("dbo.Orders", "CustId", "dbo.Customers"); + RenameColumn(table: "dbo.Orders", name: "CustId", newName: "CustomerId"); + RenameIndex(table: "dbo.Orders", name: "IX_CustId", newName: "IX_CustomerId"); + DropPrimaryKey("dbo.Inventory"); + DropPrimaryKey("dbo.Orders"); + DropPrimaryKey("dbo.Customers"); + DropPrimaryKey("dbo.CreditRisks"); + DropColumn("dbo.Inventory", "CarId"); + DropColumn("dbo.Orders", "OrderId"); + DropColumn("dbo.Customers", "CustID"); + DropColumn("dbo.CreditRisks", "CustID"); + AddColumn("dbo.Inventory", "Id", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Inventory", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.Orders", "Id", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Orders", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.Customers", "Id", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Customers", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.CreditRisks", "Id", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.CreditRisks", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddPrimaryKey("dbo.Inventory", "Id"); + AddPrimaryKey("dbo.Orders", "Id"); + AddPrimaryKey("dbo.Customers", "Id"); + AddPrimaryKey("dbo.CreditRisks", "Id"); + CreateIndex("dbo.CreditRisks", new[] { "LastName", "FirstName" }, unique: true, name: "IDX_CreditRisk_Name"); + AddForeignKey("dbo.Orders", "CarId", "dbo.Inventory", "Id"); + AddForeignKey("dbo.Orders", "CustomerId", "dbo.Customers", "Id", cascadeDelete: true); + //DropColumn("dbo.Inventory", "CarId"); + //DropColumn("dbo.Orders", "OrderId"); + //DropColumn("dbo.Customers", "CustID"); + //DropColumn("dbo.CreditRisks", "CustID"); + } + + public override void Down() + { + DropForeignKey("dbo.Orders", "CustomerId", "dbo.Customers"); + DropForeignKey("dbo.Orders", "CarId", "dbo.Inventory"); + DropColumn("dbo.CreditRisks", "Timestamp"); + DropColumn("dbo.CreditRisks", "Id"); + DropColumn("dbo.Customers", "Timestamp"); + DropColumn("dbo.Customers", "Id"); + DropColumn("dbo.Orders", "Timestamp"); + DropColumn("dbo.Orders", "Id"); + DropColumn("dbo.Inventory", "Timestamp"); + DropColumn("dbo.Inventory", "Id"); + AddColumn("dbo.CreditRisks", "CustID", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Customers", "CustID", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Orders", "OrderId", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Inventory", "CarId", c => c.Int(nullable: false, identity: true)); + //DropForeignKey("dbo.Orders", "CustomerId", "dbo.Customers"); + //DropForeignKey("dbo.Orders", "CarId", "dbo.Inventory"); + DropIndex("dbo.CreditRisks", "IDX_CreditRisk_Name"); + DropPrimaryKey("dbo.CreditRisks"); + DropPrimaryKey("dbo.Customers"); + DropPrimaryKey("dbo.Orders"); + DropPrimaryKey("dbo.Inventory"); + //DropColumn("dbo.CreditRisks", "Timestamp"); + //DropColumn("dbo.CreditRisks", "Id"); + //DropColumn("dbo.Customers", "Timestamp"); + //DropColumn("dbo.Customers", "Id"); + //DropColumn("dbo.Orders", "Timestamp"); + //DropColumn("dbo.Orders", "Id"); + //DropColumn("dbo.Inventory", "Timestamp"); + //DropColumn("dbo.Inventory", "Id"); + AddPrimaryKey("dbo.CreditRisks", "CustID"); + AddPrimaryKey("dbo.Customers", "CustID"); + AddPrimaryKey("dbo.Orders", "OrderId"); + AddPrimaryKey("dbo.Inventory", "CarId"); + RenameIndex(table: "dbo.Orders", name: "IX_CustomerId", newName: "IX_CustId"); + RenameColumn(table: "dbo.Orders", name: "CustomerId", newName: "CustId"); + AddForeignKey("dbo.Orders", "CustId", "dbo.Customers", "CustID", cascadeDelete: true); + AddForeignKey("dbo.Orders", "CarId", "dbo.Inventory", "CarId"); + } + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.resx b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.resx new file mode 100644 index 0000000..13be860 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/201707262157358_Final.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + H4sIAAAAAAAEAO1bW0/jRhR+r9T/YPmxohhYVdqiZFdsgAqVmwis+oYG+ySMdjz2esaUqOov60N/Uv9Cj+/jGd9CINlFiBcynnOd75w5Ocf5759/Rx8ffWY9QCRowMf27vaObQF3A4/y+diO5ezn9/bHDz/+MDry/Efrc7HvXbIPKbkY2/dShvuOI9x78InY9qkbBSKYyW038B3iBc7ezs6vzu6uA8jCRl6WNbqKuaQ+pB/w4yTgLoQyJuws8ICJfB2fTFOu1jnxQYTEhbF9EMvgNJCHB6fbR8e2dcAoQSWmwGa2RTgPJJGo4v6NgKmMAj6fhrhA2PUiBNw3I0xArvp+tX2oFTt7iRVORViwcmMhA39Jhrvvcrc4OvmTnGuXbkPHHaGD5SKxOnXe2D7hD8BlEC1sS5e2P2FRsrPm3OwktkuyLat6uFUiAQGT/G1Zk5jJOIIxh1hGhG1Zl/Edo+7vsLgOvgAf85gxVUFUEZ/VFnDpMgpCiOTiCmaF2p5tOXU6RycsyRSazJ4TLt/t2dY5Cid3DMrzV2yfonHwG3CIiATvkkgJEU94QOpBQ7om64x8gUIaAg7DxrbOyOMp8Lm8H9u/YJwc00fwioVcgRtOMciQRkYx9MmYBCyIXlrIJcjkn5cWc41hLyTxw0LQJ8pJAsokB8RRhMlncZZyS0XVFHjfLP8JpzsJ/DCWYGLrnDzQeUqq6X0ReQh527oClj4W9zTM0k4VIrfFpuMo8K8CpkZd/ux2GsSRm3g5aNlwTaI5yLpiI6cK584gT3ksF+ApyVtwNwde6keI+mX28CErs/he4wZNXz1oiphoDZoiqgZrlR9so2rFwwbNtEeGYvrzJr0GB3Ol5DLxXFC9hXSjrGMaibVcdKdkPXK+18TQcaEuEYD6ddoWoE8LwAg8Kq+o+LJkCJZ0b0H4FoSbDsI2uB8IEbg0ZahdOEXc1U0+4p7VE4SZj9UQRksR4zREVKMKY3vX1tF7wQ+BgQTrwM2+OE+IcIlnuhzN8IZqVN7LlUZ5aVxX5ydDCgYRRAmKCcOzExiWlEsz4ih3aUhYt0M0soGhmphaCtCfHEIIPImybsOHSFaLW1ODUpB2CH3+GTkKrrrhZpSAbafb/iWqOl6lvaEjTj/iDsZrxk2bYWsATpvpg5BD1gWaLHMhjUQKiHL5+Z2aPqQgGi7nGwH5/SzyBK5DIOE7BVlZhGyqPGmCysBQnUFRqRgscvj0kBex2MShSqV9TMqyo5GNUsxojBTnmyqVRZiyq6VO0/HQf2OUJtRcYACrP9ErjAp99eujbuUAD5hfUU0XdOewYVlMdQLpsb81Y63igKJCKOOs6r87WQO+aNQ7LZ360RkJQ6yslM59vmJNs7b95Ofp8k1tP+PhuKKht11qW0pCv5A5aE+TssiDtOI8JJLckaSWmni+sU3PKi3BVkhTEod5XEXsFZuT/2u5KxtfKAnGzLs57THa5Cd5Oy36lGPuoE0HJ4SRqKHGnwQs9nn7HdJOnbW6VfpsZTiHvJGtssiXhvMo+9Qql3JxOB+lZFc5Kcsmr5GjHYpxAxpHb9SwdRgNAllrahkKs+wSWh5iLXQvAy+1Hq0hpKNO7eBGTEbNZcurgEh1ez4dJWWhsTxQ2klfBitKA0FloiwP51X1CFRW1errxItSK66AmKqmfAJmOojfULNB1BjloL6llF6WhVr5N8pLsf63OYzaLNtiW+ikB+olddl0IST428mG7elXNmEU7a02nBFOZ+iprGNq7+3s7mlvhXw7b2g4Qnhs6Gsaa+/70sStvZ3dJeeW6vsR/IFE7n0yENT6rxXPpV+HeCae2tsPz8TVaAtHwZ/5u1atnq6auJ2eXvKVgNcBJnMen4ox2j8n3IPHsf1XSrZvnfxxW1FuWalH9q0d6+/VBvmDZZNVxX4LOGou8b5bKBkjqGcKeX3i9IoySVvB9hox0BvWhxjXpT9uk8Uywve2rBNxw+nXGDde4+EmEf9CoFpFz91n13MDKF19irnJuWU+HVjzmHId86W2ltOrmEOuPnlc78F3tZk3efIbniOag4HuAZty0l2jwuwr7Nj27gI84SyjLTlJbB8kNjFvGfi0DRk7Z4xN/FtHcx0jyJ4JZKMYdX65sRFl41CycyZXOzGlb/7tTiBryrZC85mNXGLKaLaPMPaVnwxhzhF0XrFIfkDEwa1FfbnnhM+CIvdoGhVb9J4FSOJhSjiIJJ0RV+JjF4RI3xz7TFiMW478O/BO+EUssXhBk8G/YzUHJkmsS346Sq3rPLoI0xchn8MEVJOiCXDBP8WUeaXexw2VVQuLJDvm5VpyljIp2+aLktN5wAcyyt1XJvVr8EOGzMQFn5IHeIpuNwJOYU7cRdEFbGfSfxB1t48OKZlHxBc5j4oePyKGPf/xw/8fmFDIOTcAAA== + + + dbo + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/Configuration.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/Configuration.cs new file mode 100644 index 0000000..5a3d88c --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Migrations/Configuration.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using AutoLotDAL.Models; +using System.Data.Entity.Migrations; + +namespace AutoLotDAL.Migrations +{ + + internal sealed class Configuration : DbMigrationsConfiguration + { + public Configuration() + { + AutomaticMigrationsEnabled = false; + } + + protected override void Seed(AutoLotDAL.EF.AutoLotEntities context) + { + var customers = new List + { + new Customer {FirstName = "Dave", LastName = "Brenner"}, + new Customer {FirstName = "Matt", LastName = "Walton"}, + new Customer {FirstName = "Steve", LastName = "Hagen"}, + new Customer {FirstName = "Pat", LastName = "Walton"}, + new Customer {FirstName = "Bad", LastName = "Customer"}, + }; + customers.ForEach(x => context.Customers.AddOrUpdate( + c => new { c.FirstName, c.LastName }, x)); + var cars = new List + { + new Inventory {Make = "VW", Color = "Black", PetName = "Zippy"}, + new Inventory {Make = "Ford", Color = "Rust", PetName = "Rusty"}, + new Inventory {Make = "Saab", Color = "Black", PetName = "Mel"}, + new Inventory {Make = "Yugo", Color = "Yellow", PetName = "Clunker"}, + new Inventory {Make = "BMW", Color = "Black", PetName = "Bimmer"}, + new Inventory {Make = "BMW", Color = "Green", PetName = "Hank"}, + new Inventory {Make = "BMW", Color = "Pink", PetName = "Pinky"}, + new Inventory {Make = "Pinto", Color = "Black", PetName = "Pete"}, + new Inventory {Make = "Yugo", Color = "Brown", PetName = "Brownie"}, + }; + context.Cars.AddOrUpdate(x => new { x.Make, x.Color }, cars.ToArray()); + var orders = new List + { + new Order {Car = cars[0], Customer = customers[0]}, + new Order {Car = cars[1], Customer = customers[1]}, + new Order {Car = cars[2], Customer = customers[2]}, + new Order {Car = cars[3], Customer = customers[3]}, + }; + orders.ForEach(x => context.Orders.AddOrUpdate(c => new { c.CarId, c.CustomerId }, x)); + + context.CreditRisks.AddOrUpdate(x => new { x.FirstName, x.LastName }, + new CreditRisk + { + Id = customers[4].Id, + FirstName = customers[4].FirstName, + LastName = customers[4].LastName, + }); + } + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Properties/AssemblyInfo.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4511695 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDAL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDAL")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7e5a8812-c303-4ae0-a6e7-4ac96ec11624")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/BaseRepo.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/BaseRepo.cs new file mode 100644 index 0000000..0aabc4d --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/BaseRepo.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Data.Entity.Infrastructure; +using System.Linq; +using AutoLotDAL.EF; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Repos +{ + public class BaseRepo : IDisposable, IRepo where T : EntityBase, new() + { + private readonly DbSet _table; + private readonly AutoLotEntities _db; + protected AutoLotEntities Context => _db; + + public BaseRepo() + { + _db = new AutoLotEntities(); + _table = _db.Set(); + } + + public void Dispose() + { + _db?.Dispose(); + } + + public int Add(T entity) + { + _table.Add(entity); + return SaveChanges(); + } + + public int AddRange(IList entities) + { + _table.AddRange(entities); + return SaveChanges(); + } + + public int Save(T entity) + { + _db.Entry(entity).State = EntityState.Modified; + return SaveChanges(); + } + + public int Delete(int id, byte[] timeStamp) + { + _db.Entry(new T() {Id = id, Timestamp = timeStamp}).State = EntityState.Deleted; + return SaveChanges(); + } + + + public int Delete(T entity) + { + _db.Entry(entity).State = EntityState.Deleted; + return SaveChanges(); + } + + public T GetOne(int? id) => _table.Find(id); + + public virtual List GetAll() => _table.ToList(); + + public List ExecuteQuery(string sql) => _table.SqlQuery(sql).ToList(); + + public List ExecuteQuery(string sql, object[] sqlParametersObjects) + => _table.SqlQuery(sql, sqlParametersObjects).ToList(); + + internal int SaveChanges() + { + try + { + return _db.SaveChanges(); + } + catch (DbUpdateConcurrencyException ex) + { + //Thrown when there is a concurrency error + //for now, just rethrow the exception + throw; + } + catch (DbUpdateException ex) + { + //Thrown when database update fails + //Examine the inner exception(s) for additional + //details and affected objects + //for now, just rethrow the exception + throw; + } + catch (CommitFailedException ex) + { + //handle transaction failures here + //for now, just rethrow the exception + throw; + } + catch (Exception ex) + { + //some other exception happened and should be handled + throw; + } + } + } +} \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/IRepo.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/IRepo.cs new file mode 100644 index 0000000..b9f04f8 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/IRepo.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace AutoLotDAL.Repos +{ +public interface IRepo +{ + int Add(T entity); + int AddRange(IList entities); + int Save(T entity); + int Delete(int id, byte[] timeStamp); + int Delete(T entity); + T GetOne(int? id); + List GetAll(); + + List ExecuteQuery(string sql); + List ExecuteQuery(string sql, object[] sqlParametersObjects); +} +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/InventoryRepo.cs b/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/InventoryRepo.cs new file mode 100644 index 0000000..d662761 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/Repos/InventoryRepo.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.Repos +{ + public class InventoryRepo : BaseRepo + { + public override List GetAll() + => Context.Cars.OrderBy(x=>x.PetName).ToList(); + } +} diff --git a/Chapter_22/AutoLotDAL/AutoLotDAL/packages.config b/Chapter_22/AutoLotDAL/AutoLotDAL/packages.config new file mode 100644 index 0000000..bb66824 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotDAL/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotTestDrive/App.config b/Chapter_22/AutoLotDAL/AutoLotTestDrive/App.config new file mode 100644 index 0000000..101725c --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotTestDrive/App.config @@ -0,0 +1,23 @@ + + + + +
    + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotTestDrive/AutoLotTestDrive.csproj b/Chapter_22/AutoLotDAL/AutoLotTestDrive/AutoLotTestDrive.csproj new file mode 100644 index 0000000..abad961 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotTestDrive/AutoLotTestDrive.csproj @@ -0,0 +1,70 @@ + + + + + Debug + AnyCPU + {764C55F4-4B69-4960-90A5-F1AD21AB857A} + Exe + AutoLotTestDrive + AutoLotTestDrive + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + + + + + + + + + + + {9a917d7c-885e-4d9a-818f-9955871a4fbb} + AutoLotDAL.Models + + + {7e5a8812-c303-4ae0-a6e7-4ac96ec11624} + AutoLotDAL + + + + \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotTestDrive/Program.cs b/Chapter_22/AutoLotDAL/AutoLotTestDrive/Program.cs new file mode 100644 index 0000000..cfb05b4 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotTestDrive/Program.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Data.Entity.Infrastructure; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.EF; +using AutoLotDAL.Models; +using AutoLotDAL.Repos; + +namespace AutoLotTestDrive +{ + class Program + { + static void Main(string[] args) + { + //Database.SetInitializer(new MyDataInitializer()); + Console.WriteLine("***** Fun with ADO.NET EF Code First *****\n"); + + using (var context = new AutoLotEntities()) + { + foreach (Inventory c in context.Cars) + { + Console.WriteLine(c); + } + } + Console.WriteLine("***** Using a Repository *****\n"); + using (var repo = new InventoryRepo()) + { + foreach (Inventory c in repo.GetAll()) + { + Console.WriteLine(c); + } + } + TestConcurrency(); + Console.ReadLine(); + } + + private static void AddNewRecord(Inventory car) + { + using (var repo = new InventoryRepo()) + { + repo.Add(car); + } + } + + private static void UpdateRecord(int carId) + { + using (var repo = new InventoryRepo()) + { + // Grab the car, change it, save! + var carToUpdate = repo.GetOne(carId); + if (carToUpdate == null) return; + carToUpdate.Color = "Blue"; + repo.Save(carToUpdate); + } + } + + private static void RemoveRecordByCar(Inventory carToDelete) + { + using (var repo = new InventoryRepo()) + { + repo.Delete(carToDelete); + } + } + + private static void RemoveRecordById(int carId, byte[] timeStamp) + { + using (var repo = new InventoryRepo()) + { + repo.Delete(carId, timeStamp); + } + } + + private static void TestConcurrency() + { + var repo1 = new InventoryRepo(); + //Use a second repo to make sure using a different context + var repo2 = new InventoryRepo(); + var car1 = repo1.GetOne(1); + var car2 = repo2.GetOne(1); + car1.PetName = "NewName"; + repo1.Save(car1); + car2.PetName = "OtherName"; + try + { + repo2.Save(car2); + } + catch (DbUpdateConcurrencyException ex) + { + var entry = ex.Entries.Single(); + var currentValues = entry.CurrentValues; + var originalValues = entry.OriginalValues; + var dbValues = entry.GetDatabaseValues(); + Console.WriteLine(" ******** Concurrency ************"); + Console.WriteLine("Type\tPetName"); + Console.WriteLine($"Current:\t{currentValues[nameof(Inventory.PetName)]}"); + Console.WriteLine($"Orig:\t{originalValues[nameof(Inventory.PetName)]}"); + Console.WriteLine($"db:\t{dbValues[nameof(Inventory.PetName)]}"); + } + } + } +} \ No newline at end of file diff --git a/Chapter_22/AutoLotDAL/AutoLotTestDrive/Properties/AssemblyInfo.cs b/Chapter_22/AutoLotDAL/AutoLotTestDrive/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8cad79c --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotTestDrive/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotTestDrive")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotTestDrive")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("764c55f4-4b69-4960-90a5-f1ad21ab857a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_22/AutoLotDAL/AutoLotTestDrive/packages.config b/Chapter_22/AutoLotDAL/AutoLotTestDrive/packages.config new file mode 100644 index 0000000..bb66824 --- /dev/null +++ b/Chapter_22/AutoLotDAL/AutoLotTestDrive/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/App.config b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/App.config new file mode 100644 index 0000000..7e1d79c --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/App.config @@ -0,0 +1,17 @@ + + + + +
    + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/AutoLotDAL.Models.csproj b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/AutoLotDAL.Models.csproj new file mode 100644 index 0000000..d999eb7 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/AutoLotDAL.Models.csproj @@ -0,0 +1,63 @@ + + + + + Debug + AnyCPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB} + Library + Properties + AutoLotDAL.Models + AutoLotDAL.Models + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Base/EntityBase.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Base/EntityBase.cs new file mode 100644 index 0000000..3ad6386 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Base/EntityBase.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations; + +namespace AutoLotDAL.Models.Base +{ + public class EntityBase + { + [Key] + public int Id { get; set; } + [Timestamp] + public byte[] Timestamp { get; set; } + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/CreditRisk.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/CreditRisk.cs new file mode 100644 index 0000000..489182d --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/CreditRisk.cs @@ -0,0 +1,17 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Models +{ + public partial class CreditRisk : EntityBase + { + [StringLength(50)] + [Index("IDX_CreditRisk_Name", IsUnique = true, Order = 2)] + public string FirstName { get; set; } + + [StringLength(50)] + [Index("IDX_CreditRisk_Name", IsUnique = true, Order = 1)] + public string LastName { get; set; } + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Customer.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Customer.cs new file mode 100644 index 0000000..4ae33fe --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Customer.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Models +{ +public partial class Customer : EntityBase +{ + [StringLength(50)] + public string FirstName { get; set; } + + [StringLength(50)] + public string LastName { get; set; } + + public virtual ICollection Orders { get; set; } = new HashSet(); + + [NotMapped] + public string FullName => $"{FirstName} {LastName}"; +} +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Inventory.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Inventory.cs new file mode 100644 index 0000000..e0bc757 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Inventory.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Models +{ + [Table("Inventory")] + public partial class Inventory : EntityBase + { + [StringLength(50)] + public string Make { get; set; } + + [StringLength(50)] + public string Color { get; set; } + + [StringLength(50)] + public string PetName { get; set; } + + public virtual ICollection Orders { get; set; } + = new HashSet(); + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/InventoryPartial.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/InventoryPartial.cs new file mode 100644 index 0000000..7665a50 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/InventoryPartial.cs @@ -0,0 +1,17 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace AutoLotDAL.Models +{ + public partial class Inventory + { + public override string ToString() + { + // Since the PetName column could be empty, supply + // the default name of **No Name**. + return $"{this.PetName ?? "**No Name**"} is a {this.Color} {this.Make} with ID {this.Id}."; + } + [NotMapped] + public string MakeColor => $"{Make} + ({Color})"; + + } +} \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Order.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Order.cs new file mode 100644 index 0000000..9a0eee6 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Order.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations.Schema; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Models +{ + public partial class Order : EntityBase + { + public int CustomerId { get; set; } + public int CarId { get; set; } + [ForeignKey(nameof(CustomerId))] + public virtual Customer Customer { get; set; } + [ForeignKey(nameof(CarId))] + public virtual Inventory Car { get; set; } + } + +} \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Properties/AssemblyInfo.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9a35541 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDAL.Models")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDAL.Models")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9a917d7c-885e-4d9a-818f-9955871a4fbb")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/packages.config b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/packages.config new file mode 100644 index 0000000..4409173 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL.Models/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/App.config b/Chapter_23/AutoLotWCFService/AutoLotDAL/App.config new file mode 100644 index 0000000..d31b2b7 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/App.config @@ -0,0 +1,22 @@ + + + + +
    + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/AutoLotDAL.csproj b/Chapter_23/AutoLotWCFService/AutoLotDAL/AutoLotDAL.csproj new file mode 100644 index 0000000..28978e9 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/AutoLotDAL.csproj @@ -0,0 +1,86 @@ + + + + + Debug + AnyCPU + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624} + Library + Properties + AutoLotDAL + AutoLotDAL + v4.7 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + + + + + + + 201707262145588_Initial.cs + + + + 201707262157358_Final.cs + + + + + + + + + + + + + + 201707262145588_Initial.cs + + + 201707262157358_Final.cs + + + + + {9a917d7c-885e-4d9a-818f-9955871a4fbb} + AutoLotDAL.Models + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/EF/AutoLotEntities.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/EF/AutoLotEntities.cs new file mode 100644 index 0000000..ad889a0 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/EF/AutoLotEntities.cs @@ -0,0 +1,73 @@ +using System; +using System.Data.Entity; +using System.Data.Entity.Core.Objects; +using System.Data.Entity.Infrastructure; +using System.Data.Entity.Infrastructure.Interception; +using AutoLotDAL.Interception; +using AutoLotDAL.Models; + +namespace AutoLotDAL.EF +{ + public partial class AutoLotEntities : DbContext + { + //static readonly DatabaseLogger DatabaseLogger = new DatabaseLogger("sqllog.txt"); + public AutoLotEntities() + : base("name=AutoLotConnection") + { + //DbInterception.Add(new ConsoleWriterInterceptor()); + + //DatabaseLogger.StartLogging(); + //DbInterception.Add(DatabaseLogger); + + //var context = (this as IObjectContextAdapter).ObjectContext; + //context.ObjectMaterialized += OnObjectMaterialized; + //context.SavingChanges += OnSavingChanges; + } + + protected override void Dispose(bool disposing) + { + //DbInterception.Remove(DatabaseLogger); + //DatabaseLogger.StopLogging(); + //base.Dispose(disposing); + } + + private void OnSavingChanges(object sender, EventArgs eventArgs) + { + //Sender is of type ObjectContext. Can get current and original values, and + // cancel /modify the save operation as desired. + var context = sender as ObjectContext; + if (context == null) return; + foreach (ObjectStateEntry item in + context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added)) + { + //Do something important here + if ((item.Entity as Inventory) != null) + { + var entity = (Inventory)item.Entity; + if (entity.Color == "Red") + { + item.RejectPropertyChanges(nameof(entity.Color)); + } + } + } + + } + + private void OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e) + { + } + + public virtual DbSet CreditRisks { get; set; } + public virtual DbSet Customers { get; set; } + public virtual DbSet Cars { get; set; } + public virtual DbSet Orders { get; set; } + + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + modelBuilder.Entity() + .HasMany(e => e.Orders) + .WithRequired(e => e.Car) + .WillCascadeOnDelete(false); + } + } +} \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/EF/MyDataInitializer.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/EF/MyDataInitializer.cs new file mode 100644 index 0000000..18b66ef --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/EF/MyDataInitializer.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Data.Entity.Migrations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.EF +{ + public class MyDataInitializer : DropCreateDatabaseAlways + { + protected override void Seed(AutoLotEntities context) + { + var customers = new List + { + new Customer {FirstName = "Dave", LastName = "Brenner"}, + new Customer {FirstName = "Matt", LastName = "Walton"}, + new Customer {FirstName = "Steve", LastName = "Hagen"}, + new Customer {FirstName = "Pat", LastName = "Walton"}, + new Customer {FirstName = "Bad", LastName = "Customer"}, + }; + customers.ForEach(x => context.Customers.AddOrUpdate( + c => new {c.FirstName, c.LastName}, x)); + var cars = new List + { + new Inventory {Make = "VW", Color = "Black", PetName = "Zippy"}, + new Inventory {Make = "Ford", Color = "Rust", PetName = "Rusty"}, + new Inventory {Make = "Saab", Color = "Black", PetName = "Mel"}, + new Inventory {Make = "Yugo", Color = "Yellow", PetName = "Clunker"}, + new Inventory {Make = "BMW", Color = "Black", PetName = "Bimmer"}, + new Inventory {Make = "BMW", Color = "Green", PetName = "Hank"}, + new Inventory {Make = "BMW", Color = "Pink", PetName = "Pinky"}, + new Inventory {Make = "Pinto", Color = "Black", PetName = "Pete"}, + new Inventory {Make = "Yugo", Color = "Brown", PetName = "Brownie"}, + }; + context.Cars.AddOrUpdate(x => new {x.Make, x.Color}, cars.ToArray()); + var orders = new List + { + new Order {Car = cars[0], Customer = customers[0]}, + new Order {Car = cars[1], Customer = customers[1]}, + new Order {Car = cars[2], Customer = customers[2]}, + new Order {Car = cars[3], Customer = customers[3]}, + }; + orders.ForEach(x => context.Orders.AddOrUpdate(c => new {c.CarId, c.CustomerId}, x)); + + context.CreditRisks.AddOrUpdate(x => new {x.FirstName, x.LastName}, + new CreditRisk + { + Id = customers[4].Id, + FirstName = customers[4].FirstName, + LastName = customers[4].LastName, + }); + } + } +} \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs new file mode 100644 index 0000000..91ad0db --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Interception/ConsoleWriterInterceptor.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Data.Entity.Infrastructure.Interception; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using static System.Console; + +namespace AutoLotDAL.Interception +{ + public class ConsoleWriterInterceptor : IDbCommandInterceptor + { + private void WriteInfo(bool isAsync, string commandText) + { + WriteLine($"IsAsync: {isAsync}, Command Text: {commandText}"); + } + public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync,command.CommandText); + } + + public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + + public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) + { + WriteInfo(interceptionContext.IsAsync, command.CommandText); + } + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.Designer.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.Designer.cs new file mode 100644 index 0000000..0ad26a2 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.Designer.cs @@ -0,0 +1,29 @@ +// +namespace AutoLotDAL.Migrations +{ + using System.CodeDom.Compiler; + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] + public sealed partial class Initial : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(Initial)); + + string IMigrationMetadata.Id + { + get { return "201707262145588_Initial"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.cs new file mode 100644 index 0000000..ab5da5a --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.cs @@ -0,0 +1,69 @@ +namespace AutoLotDAL.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class Initial : DbMigration + { + public override void Up() + { + CreateTable( + "dbo.Inventory", + c => new + { + CarId = c.Int(nullable: false, identity: true), + Make = c.String(maxLength: 50), + Color = c.String(maxLength: 50), + PetName = c.String(maxLength: 50), + }) + .PrimaryKey(t => t.CarId); + + CreateTable( + "dbo.Orders", + c => new + { + OrderId = c.Int(nullable: false, identity: true), + CustId = c.Int(nullable: false), + CarId = c.Int(nullable: false), + }) + .PrimaryKey(t => t.OrderId) + .ForeignKey("dbo.Customers", t => t.CustId, cascadeDelete: true) + .ForeignKey("dbo.Inventory", t => t.CarId) + .Index(t => t.CustId) + .Index(t => t.CarId); + + CreateTable( + "dbo.Customers", + c => new + { + CustID = c.Int(nullable: false, identity: true), + FirstName = c.String(maxLength: 50), + LastName = c.String(maxLength: 50), + }) + .PrimaryKey(t => t.CustID); + + CreateTable( + "dbo.CreditRisks", + c => new + { + CustID = c.Int(nullable: false, identity: true), + FirstName = c.String(maxLength: 50), + LastName = c.String(maxLength: 50), + }) + .PrimaryKey(t => t.CustID); + + } + + public override void Down() + { + DropForeignKey("dbo.Orders", "CarId", "dbo.Inventory"); + DropForeignKey("dbo.Orders", "CustId", "dbo.Customers"); + DropIndex("dbo.Orders", new[] { "CarId" }); + DropIndex("dbo.Orders", new[] { "CustId" }); + DropTable("dbo.CreditRisks"); + DropTable("dbo.Customers"); + DropTable("dbo.Orders"); + DropTable("dbo.Inventory"); + } + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.resx b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.resx new file mode 100644 index 0000000..a510e0b --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262145588_Initial.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + H4sIAAAAAAAEAO1azW7jNhC+F+g7CDoWqZVkUaAN7F2kTlIYzR/iZNHbgpHGDrEUpYpUEKPok/XQR+ordPRPUaIs2XG8LRZ72YicH858MxzO+J+//h5/ePGZ9QyRoAGf2EejQ9sC7gYe5cuJHcvF9z/aH95/+8343PNfrI/FvnfJPqTkYmI/SRmeOI5wn8AnYuRTNwpEsJAjN/Ad4gXO8eHhT87RkQPIwkZeljW+i7mkPqR/4J/TgLsQypiwq8ADJvLvuDJPuVrXxAcREhcm9mksg8tAnp1ejs4vbOuUUYJKzIEtbItwHkgiUcWTBwFzGQV8OQ/xA2H3qxBw34IwAbnqJ9X2vqc4PE5O4VSEBSs3FjLwBzI8epebxdHJNzKuXZoNDXeOBpar5NSp8Sb2jD8Dl0G0si1d2smURcnOmnEzT4xKsgOrWjwokYCASf4dWNOYyTiCCYdYRoQdWLfxI6Pur7C6Dz4Dn/CYMVVBVBHXah/w020UhBDJ1R0scrWnJJp5tuXUSR2dtqSsk2WnmnH57ti2rlEF8sigRIFigTkeEX4BDhGR4N0SKSFCJ848SO3YUEATd0U+QyENYYfBY1tX5OUS+FI+TewfMFou6At4xYdcgQdOMdSQRkYxrJMxDVgQ7VrILcjkP68u5po802Vqak3gTeQhlGzrDli6LJ5omIVzBb1PxaaLKPDvAqaiOV/7NA/iyE30Dgwb7km0BFlXbOxUYdIZPCmPYYGTkuwpaFLZm4RNSfhWgTNFi66Xt4ZHn1jvi0dktj0YC6wZwVigtbdWKfCgXbVisUUzbamhmL7eplfvIKmUHBInBdW+7pcEgGcbXDA53VsFygWNxG5SsybokuxIziZXwABo6xeACfqbQTsCj8o7Kj4PBHdJ9xXe/2d4m4B0KkTg0tRCWpIsEF1X9px71hp4Z1qrwYHKI3poiHhBFfARZ+u4uOFnwECCdepmj5MpES7xmsbCY3h9NSrvkkqjvEyqq/NdQwrCE6IEF4Thy08g4CmXTSxT7tKQsG6DaGQDgiA5bilEXzmDEHiC3e7D95beqMUS6aUQzQnr7DN2FFx1w61Rtpi8ay6oK/cqT0gdcbqLOxi/MW5MB+vlurbH5yDcmE6/lfRXx02WvJBGIgVEufz8wkoXKYiWm+9BQH75iTwr6ihI+M5BVidCNlWqbOKqAaM6g6IMaLDIEbSGvIjiNg5VNl3HpLzTW9kolYLGSDF+U6WywlF2GYogHQ/rL43yCDUTNIC1PtcrjAp99RukfsoeFmi+rJom6E5j/RKZagSy5vzGpLWNAYoioYyzqs3pZH3Ooh/qGBqi4ysShliuKA3S/Is1z7qj0+/nw3uHfsbDcUVLC7HUtpSEdiFL0FaT/pQHaRl3RiR5JEnFNPX8xjY9qxiCrZCmJI6mu4rYKzYn/6/lrqxLrCSYZt7NaS/wTH6St9NCVnFzB23anyaMRO0NiWnAYp935nIzj6yjqLLIvvTnkPcLa1pkn/rzKNuBKpfyY5PP2NHM2bi7Gk5rFKB1APSChzEp9AVIdn0MB4eBzmTOsr2mmtPQrOt0bV5S1nxrKDM7uAyA6Z4cW91Wm/u2vNiHu9dM2umZsxbPtDw/zFyU17DKSPncn1f14FVZVV+/HF8rddUW3q7qrw383UH81eMberxR9uhbSull+aOVOeO85Fg/HG7UINkW20ITPVMvqT/mKyHBHyUbRvPf2ZRRPG+14YpwugAhs7abfXx4dKwNmb+cga8jhMf6Tn33NHuliXHXNgcHTnzUcSt/JpH7lExttBZexXPwdPWVeGrD1I24DhxR7nFYuBNP1+eDqYhGF2LGPXiZ2H+kJCfW7LdPGdWBlWp4Yh1af243VOwtNyEaIHb4aG1vI4CdeLfR9X+lwNOb/LuNPFPV8NU9+3DP9iOXfQ5Z8j7mG89U3mqKYnpm/+eHJtuPSd7W8V0NsV2MQQY4fs9Dj2YXs3saoDi7a66RvUMmtvcYoJOznDZw7GGeerQxN3SnTRORzoFIG3/jHKFjXrJmXNIqRh227G2e0jpB6Rwg1DymtAq/3HFJTVkjNF/5kANGIs0eAMa+8jNyzDmCLisWyY/KObi1qC/3zPgiKHKPplGxRX9ygiQepoTTSNIFcSUuuyBE+tuRj4TFuOXcfwRvxm9iGcYSjwz+I6sZMEliXfLTuU9d5/FNmP4k6jWOgGpSPALc8J9jyrxS74uWh4mBRZId8wIz8aVMCs3lquR0HfCejHLzlUn9HvyQITNxw+fkGTbR7UHAJSyJuypaOWYm6x1RN/v4jJJlRHyR86jo8U/EsOe/vP8XxzOc+k0xAAA= + + + dbo + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.Designer.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.Designer.cs new file mode 100644 index 0000000..fd70503 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.Designer.cs @@ -0,0 +1,29 @@ +// +namespace AutoLotDAL.Migrations +{ + using System.CodeDom.Compiler; + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] + public sealed partial class Final : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(Final)); + + string IMigrationMetadata.Id + { + get { return "201707262157358_Final"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.cs new file mode 100644 index 0000000..92488bb --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.cs @@ -0,0 +1,84 @@ +namespace AutoLotDAL.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class Final : DbMigration + { + public override void Up() + { + DropForeignKey("dbo.Orders", "CarId", "dbo.Inventory"); + DropForeignKey("dbo.Orders", "CustId", "dbo.Customers"); + RenameColumn(table: "dbo.Orders", name: "CustId", newName: "CustomerId"); + RenameIndex(table: "dbo.Orders", name: "IX_CustId", newName: "IX_CustomerId"); + DropPrimaryKey("dbo.Inventory"); + DropPrimaryKey("dbo.Orders"); + DropPrimaryKey("dbo.Customers"); + DropPrimaryKey("dbo.CreditRisks"); + DropColumn("dbo.Inventory", "CarId"); + DropColumn("dbo.Orders", "OrderId"); + DropColumn("dbo.Customers", "CustID"); + DropColumn("dbo.CreditRisks", "CustID"); + AddColumn("dbo.Inventory", "Id", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Inventory", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.Orders", "Id", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Orders", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.Customers", "Id", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Customers", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddColumn("dbo.CreditRisks", "Id", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.CreditRisks", "Timestamp", c => c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion")); + AddPrimaryKey("dbo.Inventory", "Id"); + AddPrimaryKey("dbo.Orders", "Id"); + AddPrimaryKey("dbo.Customers", "Id"); + AddPrimaryKey("dbo.CreditRisks", "Id"); + CreateIndex("dbo.CreditRisks", new[] { "LastName", "FirstName" }, unique: true, name: "IDX_CreditRisk_Name"); + AddForeignKey("dbo.Orders", "CarId", "dbo.Inventory", "Id"); + AddForeignKey("dbo.Orders", "CustomerId", "dbo.Customers", "Id", cascadeDelete: true); + //DropColumn("dbo.Inventory", "CarId"); + //DropColumn("dbo.Orders", "OrderId"); + //DropColumn("dbo.Customers", "CustID"); + //DropColumn("dbo.CreditRisks", "CustID"); + } + + public override void Down() + { + DropForeignKey("dbo.Orders", "CustomerId", "dbo.Customers"); + DropForeignKey("dbo.Orders", "CarId", "dbo.Inventory"); + DropColumn("dbo.CreditRisks", "Timestamp"); + DropColumn("dbo.CreditRisks", "Id"); + DropColumn("dbo.Customers", "Timestamp"); + DropColumn("dbo.Customers", "Id"); + DropColumn("dbo.Orders", "Timestamp"); + DropColumn("dbo.Orders", "Id"); + DropColumn("dbo.Inventory", "Timestamp"); + DropColumn("dbo.Inventory", "Id"); + AddColumn("dbo.CreditRisks", "CustID", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Customers", "CustID", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Orders", "OrderId", c => c.Int(nullable: false, identity: true)); + AddColumn("dbo.Inventory", "CarId", c => c.Int(nullable: false, identity: true)); + //DropForeignKey("dbo.Orders", "CustomerId", "dbo.Customers"); + //DropForeignKey("dbo.Orders", "CarId", "dbo.Inventory"); + DropIndex("dbo.CreditRisks", "IDX_CreditRisk_Name"); + DropPrimaryKey("dbo.CreditRisks"); + DropPrimaryKey("dbo.Customers"); + DropPrimaryKey("dbo.Orders"); + DropPrimaryKey("dbo.Inventory"); + //DropColumn("dbo.CreditRisks", "Timestamp"); + //DropColumn("dbo.CreditRisks", "Id"); + //DropColumn("dbo.Customers", "Timestamp"); + //DropColumn("dbo.Customers", "Id"); + //DropColumn("dbo.Orders", "Timestamp"); + //DropColumn("dbo.Orders", "Id"); + //DropColumn("dbo.Inventory", "Timestamp"); + //DropColumn("dbo.Inventory", "Id"); + AddPrimaryKey("dbo.CreditRisks", "CustID"); + AddPrimaryKey("dbo.Customers", "CustID"); + AddPrimaryKey("dbo.Orders", "OrderId"); + AddPrimaryKey("dbo.Inventory", "CarId"); + RenameIndex(table: "dbo.Orders", name: "IX_CustomerId", newName: "IX_CustId"); + RenameColumn(table: "dbo.Orders", name: "CustomerId", newName: "CustId"); + AddForeignKey("dbo.Orders", "CustId", "dbo.Customers", "CustID", cascadeDelete: true); + AddForeignKey("dbo.Orders", "CarId", "dbo.Inventory", "CarId"); + } + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.resx b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.resx new file mode 100644 index 0000000..13be860 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/201707262157358_Final.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + H4sIAAAAAAAEAO1bW0/jRhR+r9T/YPmxohhYVdqiZFdsgAqVmwis+oYG+ySMdjz2esaUqOov60N/Uv9Cj+/jGd9CINlFiBcynnOd75w5Ocf5759/Rx8ffWY9QCRowMf27vaObQF3A4/y+diO5ezn9/bHDz/+MDry/Efrc7HvXbIPKbkY2/dShvuOI9x78InY9qkbBSKYyW038B3iBc7ezs6vzu6uA8jCRl6WNbqKuaQ+pB/w4yTgLoQyJuws8ICJfB2fTFOu1jnxQYTEhbF9EMvgNJCHB6fbR8e2dcAoQSWmwGa2RTgPJJGo4v6NgKmMAj6fhrhA2PUiBNw3I0xArvp+tX2oFTt7iRVORViwcmMhA39Jhrvvcrc4OvmTnGuXbkPHHaGD5SKxOnXe2D7hD8BlEC1sS5e2P2FRsrPm3OwktkuyLat6uFUiAQGT/G1Zk5jJOIIxh1hGhG1Zl/Edo+7vsLgOvgAf85gxVUFUEZ/VFnDpMgpCiOTiCmaF2p5tOXU6RycsyRSazJ4TLt/t2dY5Cid3DMrzV2yfonHwG3CIiATvkkgJEU94QOpBQ7om64x8gUIaAg7DxrbOyOMp8Lm8H9u/YJwc00fwioVcgRtOMciQRkYx9MmYBCyIXlrIJcjkn5cWc41hLyTxw0LQJ8pJAsokB8RRhMlncZZyS0XVFHjfLP8JpzsJ/DCWYGLrnDzQeUqq6X0ReQh527oClj4W9zTM0k4VIrfFpuMo8K8CpkZd/ux2GsSRm3g5aNlwTaI5yLpiI6cK584gT3ksF+ApyVtwNwde6keI+mX28CErs/he4wZNXz1oiphoDZoiqgZrlR9so2rFwwbNtEeGYvrzJr0GB3Ol5DLxXFC9hXSjrGMaibVcdKdkPXK+18TQcaEuEYD6ddoWoE8LwAg8Kq+o+LJkCJZ0b0H4FoSbDsI2uB8IEbg0ZahdOEXc1U0+4p7VE4SZj9UQRksR4zREVKMKY3vX1tF7wQ+BgQTrwM2+OE+IcIlnuhzN8IZqVN7LlUZ5aVxX5ydDCgYRRAmKCcOzExiWlEsz4ih3aUhYt0M0soGhmphaCtCfHEIIPImybsOHSFaLW1ODUpB2CH3+GTkKrrrhZpSAbafb/iWqOl6lvaEjTj/iDsZrxk2bYWsATpvpg5BD1gWaLHMhjUQKiHL5+Z2aPqQgGi7nGwH5/SzyBK5DIOE7BVlZhGyqPGmCysBQnUFRqRgscvj0kBex2MShSqV9TMqyo5GNUsxojBTnmyqVRZiyq6VO0/HQf2OUJtRcYACrP9ErjAp99eujbuUAD5hfUU0XdOewYVlMdQLpsb81Y63igKJCKOOs6r87WQO+aNQ7LZ360RkJQ6yslM59vmJNs7b95Ofp8k1tP+PhuKKht11qW0pCv5A5aE+TssiDtOI8JJLckaSWmni+sU3PKi3BVkhTEod5XEXsFZuT/2u5KxtfKAnGzLs57THa5Cd5Oy36lGPuoE0HJ4SRqKHGnwQs9nn7HdJOnbW6VfpsZTiHvJGtssiXhvMo+9Qql3JxOB+lZFc5Kcsmr5GjHYpxAxpHb9SwdRgNAllrahkKs+wSWh5iLXQvAy+1Hq0hpKNO7eBGTEbNZcurgEh1ez4dJWWhsTxQ2klfBitKA0FloiwP51X1CFRW1errxItSK66AmKqmfAJmOojfULNB1BjloL6llF6WhVr5N8pLsf63OYzaLNtiW+ikB+olddl0IST428mG7elXNmEU7a02nBFOZ+iprGNq7+3s7mlvhXw7b2g4Qnhs6Gsaa+/70sStvZ3dJeeW6vsR/IFE7n0yENT6rxXPpV+HeCae2tsPz8TVaAtHwZ/5u1atnq6auJ2eXvKVgNcBJnMen4ox2j8n3IPHsf1XSrZvnfxxW1FuWalH9q0d6+/VBvmDZZNVxX4LOGou8b5bKBkjqGcKeX3i9IoySVvB9hox0BvWhxjXpT9uk8Uywve2rBNxw+nXGDde4+EmEf9CoFpFz91n13MDKF19irnJuWU+HVjzmHId86W2ltOrmEOuPnlc78F3tZk3efIbniOag4HuAZty0l2jwuwr7Nj27gI84SyjLTlJbB8kNjFvGfi0DRk7Z4xN/FtHcx0jyJ4JZKMYdX65sRFl41CycyZXOzGlb/7tTiBryrZC85mNXGLKaLaPMPaVnwxhzhF0XrFIfkDEwa1FfbnnhM+CIvdoGhVb9J4FSOJhSjiIJJ0RV+JjF4RI3xz7TFiMW478O/BO+EUssXhBk8G/YzUHJkmsS346Sq3rPLoI0xchn8MEVJOiCXDBP8WUeaXexw2VVQuLJDvm5VpyljIp2+aLktN5wAcyyt1XJvVr8EOGzMQFn5IHeIpuNwJOYU7cRdEFbGfSfxB1t48OKZlHxBc5j4oePyKGPf/xw/8fmFDIOTcAAA== + + + dbo + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/Configuration.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/Configuration.cs new file mode 100644 index 0000000..5a3d88c --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Migrations/Configuration.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using AutoLotDAL.Models; +using System.Data.Entity.Migrations; + +namespace AutoLotDAL.Migrations +{ + + internal sealed class Configuration : DbMigrationsConfiguration + { + public Configuration() + { + AutomaticMigrationsEnabled = false; + } + + protected override void Seed(AutoLotDAL.EF.AutoLotEntities context) + { + var customers = new List + { + new Customer {FirstName = "Dave", LastName = "Brenner"}, + new Customer {FirstName = "Matt", LastName = "Walton"}, + new Customer {FirstName = "Steve", LastName = "Hagen"}, + new Customer {FirstName = "Pat", LastName = "Walton"}, + new Customer {FirstName = "Bad", LastName = "Customer"}, + }; + customers.ForEach(x => context.Customers.AddOrUpdate( + c => new { c.FirstName, c.LastName }, x)); + var cars = new List + { + new Inventory {Make = "VW", Color = "Black", PetName = "Zippy"}, + new Inventory {Make = "Ford", Color = "Rust", PetName = "Rusty"}, + new Inventory {Make = "Saab", Color = "Black", PetName = "Mel"}, + new Inventory {Make = "Yugo", Color = "Yellow", PetName = "Clunker"}, + new Inventory {Make = "BMW", Color = "Black", PetName = "Bimmer"}, + new Inventory {Make = "BMW", Color = "Green", PetName = "Hank"}, + new Inventory {Make = "BMW", Color = "Pink", PetName = "Pinky"}, + new Inventory {Make = "Pinto", Color = "Black", PetName = "Pete"}, + new Inventory {Make = "Yugo", Color = "Brown", PetName = "Brownie"}, + }; + context.Cars.AddOrUpdate(x => new { x.Make, x.Color }, cars.ToArray()); + var orders = new List + { + new Order {Car = cars[0], Customer = customers[0]}, + new Order {Car = cars[1], Customer = customers[1]}, + new Order {Car = cars[2], Customer = customers[2]}, + new Order {Car = cars[3], Customer = customers[3]}, + }; + orders.ForEach(x => context.Orders.AddOrUpdate(c => new { c.CarId, c.CustomerId }, x)); + + context.CreditRisks.AddOrUpdate(x => new { x.FirstName, x.LastName }, + new CreditRisk + { + Id = customers[4].Id, + FirstName = customers[4].FirstName, + LastName = customers[4].LastName, + }); + } + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Properties/AssemblyInfo.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4511695 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoLotDAL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoLotDAL")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7e5a8812-c303-4ae0-a6e7-4ac96ec11624")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/BaseRepo.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/BaseRepo.cs new file mode 100644 index 0000000..0aabc4d --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/BaseRepo.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Data.Entity.Infrastructure; +using System.Linq; +using AutoLotDAL.EF; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Repos +{ + public class BaseRepo : IDisposable, IRepo where T : EntityBase, new() + { + private readonly DbSet _table; + private readonly AutoLotEntities _db; + protected AutoLotEntities Context => _db; + + public BaseRepo() + { + _db = new AutoLotEntities(); + _table = _db.Set(); + } + + public void Dispose() + { + _db?.Dispose(); + } + + public int Add(T entity) + { + _table.Add(entity); + return SaveChanges(); + } + + public int AddRange(IList entities) + { + _table.AddRange(entities); + return SaveChanges(); + } + + public int Save(T entity) + { + _db.Entry(entity).State = EntityState.Modified; + return SaveChanges(); + } + + public int Delete(int id, byte[] timeStamp) + { + _db.Entry(new T() {Id = id, Timestamp = timeStamp}).State = EntityState.Deleted; + return SaveChanges(); + } + + + public int Delete(T entity) + { + _db.Entry(entity).State = EntityState.Deleted; + return SaveChanges(); + } + + public T GetOne(int? id) => _table.Find(id); + + public virtual List GetAll() => _table.ToList(); + + public List ExecuteQuery(string sql) => _table.SqlQuery(sql).ToList(); + + public List ExecuteQuery(string sql, object[] sqlParametersObjects) + => _table.SqlQuery(sql, sqlParametersObjects).ToList(); + + internal int SaveChanges() + { + try + { + return _db.SaveChanges(); + } + catch (DbUpdateConcurrencyException ex) + { + //Thrown when there is a concurrency error + //for now, just rethrow the exception + throw; + } + catch (DbUpdateException ex) + { + //Thrown when database update fails + //Examine the inner exception(s) for additional + //details and affected objects + //for now, just rethrow the exception + throw; + } + catch (CommitFailedException ex) + { + //handle transaction failures here + //for now, just rethrow the exception + throw; + } + catch (Exception ex) + { + //some other exception happened and should be handled + throw; + } + } + } +} \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/IRepo.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/IRepo.cs new file mode 100644 index 0000000..e9e82cf --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/IRepo.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using AutoLotDAL.Models.Base; + +namespace AutoLotDAL.Repos +{ +public interface IRepo +{ + int Add(T entity); + int AddRange(IList entities); + int Save(T entity); + int Delete(int id, byte[] timeStamp); + int Delete(T entity); + T GetOne(int? id); + List GetAll(); + + List ExecuteQuery(string sql); + List ExecuteQuery(string sql, object[] sqlParametersObjects); +} +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/InventoryRepo.cs b/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/InventoryRepo.cs new file mode 100644 index 0000000..d662761 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/Repos/InventoryRepo.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AutoLotDAL.Models; + +namespace AutoLotDAL.Repos +{ + public class InventoryRepo : BaseRepo + { + public override List GetAll() + => Context.Cars.OrderBy(x=>x.PetName).ToList(); + } +} diff --git a/Chapter_23/AutoLotWCFService/AutoLotDAL/packages.config b/Chapter_23/AutoLotWCFService/AutoLotDAL/packages.config new file mode 100644 index 0000000..bb66824 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotDAL/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotWCFService.sln b/Chapter_23/AutoLotWCFService/AutoLotWCFService.sln new file mode 100644 index 0000000..f6994f5 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotWCFService.sln @@ -0,0 +1,54 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL", "AutoLotDAL\AutoLotDAL.csproj", "{7E5A8812-C303-4AE0-A6E7-4AC96EC11624}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoLotDAL.Models", "AutoLotDAL.Models\AutoLotDAL.Models.csproj", "{9A917D7C-885E-4D9A-818F-9955871A4FBB}" +EndProject +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "AutoLotWCFService", "AutoLotWCFService\", "{4C19C0BC-7A1D-4AF7-95AC-F963C5C15962}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.7" + ProjectReferences = "{9a917d7c-885e-4d9a-818f-9955871a4fbb}|AutoLotDAL.Models.dll;{7e5a8812-c303-4ae0-a6e7-4ac96ec11624}|AutoLotDAL.dll;" + Debug.AspNetCompiler.VirtualPath = "/localhost_51819" + Debug.AspNetCompiler.PhysicalPath = "AutoLotWCFService\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_51819\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_51819" + Release.AspNetCompiler.PhysicalPath = "AutoLotWCFService\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_51819\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "51819" + SlnRelativePath = "AutoLotWCFService\" + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7E5A8812-C303-4AE0-A6E7-4AC96EC11624}.Release|Any CPU.Build.0 = Release|Any CPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9A917D7C-885E-4D9A-818F-9955871A4FBB}.Release|Any CPU.Build.0 = Release|Any CPU + {4C19C0BC-7A1D-4AF7-95AC-F963C5C15962}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C19C0BC-7A1D-4AF7-95AC-F963C5C15962}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C19C0BC-7A1D-4AF7-95AC-F963C5C15962}.Release|Any CPU.ActiveCfg = Debug|Any CPU + {4C19C0BC-7A1D-4AF7-95AC-F963C5C15962}.Release|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/AutoLotService.cs b/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/AutoLotService.cs new file mode 100644 index 0000000..180c902 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/AutoLotService.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.ServiceModel; +using System.ServiceModel.Web; +using System.Text; +using AutoLotDAL.Models; +using AutoLotDAL.Repos; +using AutoMapper; + +public class AutoLotService : IAutoLotService +{ + public AutoLotService() + { + Mapper.Initialize(cfg => cfg.CreateMap()); + } + + public void InsertCar(string make, string color, string petname) + { + var repo = new InventoryRepo(); + repo.Add(new Inventory { Color = color, Make = make, PetName = petname }); + repo.Dispose(); + } + + public void InsertCar(InventoryRecord car) + { + var repo = new InventoryRepo(); + repo.Add(new Inventory { Color = car.Color, Make = car.Make, PetName = car.PetName }); + repo.Dispose(); + } + + public List GetInventory() + { + var repo = new InventoryRepo(); + var records = repo.GetAll(); + var results = Mapper.Map>(records); + repo.Dispose(); + return results; + } +} \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/IAutoLotService.cs b/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/IAutoLotService.cs new file mode 100644 index 0000000..3f47958 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/IAutoLotService.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.ServiceModel; +using System.ServiceModel.Web; +using System.Text; + +[ServiceContract] +public interface IAutoLotService +{ + [OperationContract] + void InsertCar(string make, string color, string petname); + + [OperationContract(Name = "InsertCarWithDetails")] + void InsertCar(InventoryRecord car); + + [OperationContract] + List GetInventory(); +} \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/InventoryRecord.cs b/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/InventoryRecord.cs new file mode 100644 index 0000000..0783bae --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotWCFService/App_Code/InventoryRecord.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +[DataContract] +public class InventoryRecord +{ + [DataMember] + public int ID; + [DataMember] + public string Make; + [DataMember] + public string Color; + [DataMember] + public string PetName; +} \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotWCFService/Service.svc b/Chapter_23/AutoLotWCFService/AutoLotWCFService/Service.svc new file mode 100644 index 0000000..426d177 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotWCFService/Service.svc @@ -0,0 +1 @@ +<%@ ServiceHost Language="C#" Debug="true" Service="AutoLotService" CodeBehind="~/App_Code/AutoLotService.cs" %> \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotWCFService/Web.Debug.config b/Chapter_23/AutoLotWCFService/AutoLotWCFService/Web.Debug.config new file mode 100644 index 0000000..da6e960 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotWCFService/Web.Debug.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotWCFService/Web.config b/Chapter_23/AutoLotWCFService/AutoLotWCFService/Web.config new file mode 100644 index 0000000..187f2d4 --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotWCFService/Web.config @@ -0,0 +1,52 @@ + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/AutoLotWCFService/AutoLotWCFService/packages.config b/Chapter_23/AutoLotWCFService/AutoLotWCFService/packages.config new file mode 100644 index 0000000..3c41f0b --- /dev/null +++ b/Chapter_23/AutoLotWCFService/AutoLotWCFService/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/App.config b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/App.config new file mode 100644 index 0000000..77c4b53 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/App.config @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.disco b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.disco new file mode 100644 index 0000000..1f46fc9 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.disco @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.wsdl b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.wsdl new file mode 100644 index 0000000..0780107 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.wsdl @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.xsd b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.xsd new file mode 100644 index 0000000..1db1379 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.xsd @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.wsdl b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.wsdl new file mode 100644 index 0000000..53841a6 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.wsdl @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.xsd b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.xsd new file mode 100644 index 0000000..d58e7f3 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.cs new file mode 100644 index 0000000..3a547f0 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.cs @@ -0,0 +1,60 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace MagicEightBallServiceClient.ServiceReference1 { + + + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + [System.ServiceModel.ServiceContractAttribute(Namespace="http://MyCompany.com", ConfigurationName="ServiceReference1.IEightBall")] + public interface IEightBall { + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IEightBall/ObtainAnswerToQuestion", ReplyAction="http://MyCompany.com/IEightBall/ObtainAnswerToQuestionResponse")] + string ObtainAnswerToQuestion(string userQuestion); + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IEightBall/ObtainAnswerToQuestion", ReplyAction="http://MyCompany.com/IEightBall/ObtainAnswerToQuestionResponse")] + System.Threading.Tasks.Task ObtainAnswerToQuestionAsync(string userQuestion); + } + + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public interface IEightBallChannel : MagicEightBallServiceClient.ServiceReference1.IEightBall, System.ServiceModel.IClientChannel { + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public partial class EightBallClient : System.ServiceModel.ClientBase, MagicEightBallServiceClient.ServiceReference1.IEightBall { + + public EightBallClient() { + } + + public EightBallClient(string endpointConfigurationName) : + base(endpointConfigurationName) { + } + + public EightBallClient(string endpointConfigurationName, string remoteAddress) : + base(endpointConfigurationName, remoteAddress) { + } + + public EightBallClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : + base(endpointConfigurationName, remoteAddress) { + } + + public EightBallClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : + base(binding, remoteAddress) { + } + + public string ObtainAnswerToQuestion(string userQuestion) { + return base.Channel.ObtainAnswerToQuestion(userQuestion); + } + + public System.Threading.Tasks.Task ObtainAnswerToQuestionAsync(string userQuestion) { + return base.Channel.ObtainAnswerToQuestionAsync(userQuestion); + } + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.svcmap b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.svcmap new file mode 100644 index 0000000..ad28ac6 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.svcmap @@ -0,0 +1,35 @@ + + + + false + true + true + + false + false + false + + + true + Auto + true + true + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration.svcinfo b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration.svcinfo new file mode 100644 index 0000000..d7cc98d --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration.svcinfo @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration91.svcinfo b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration91.svcinfo new file mode 100644 index 0000000..6bdbb87 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration91.svcinfo @@ -0,0 +1,201 @@ + + + + + + + BasicHttpBinding_IEightBall + + + + + + + + + + + + + + + + + + + + + StrongWildcard + + + + + + 65536 + + + + + + + + + System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + System.Text.UTF8Encoding + + + Buffered + + + + + + Text + + + System.ServiceModel.Configuration.BasicHttpSecurityElement + + + None + + + System.ServiceModel.Configuration.HttpTransportSecurityElement + + + None + + + None + + + System.Security.Authentication.ExtendedProtection.Configuration.ExtendedProtectionPolicyElement + + + Never + + + TransportSelected + + + (Collection) + + + + + + System.ServiceModel.Configuration.BasicHttpMessageSecurityElement + + + UserName + + + Default + + + + + + + + + http://localhost:8080/MagicEightBallService + + + + + + basicHttpBinding + + + BasicHttpBinding_IEightBall + + + ServiceReference1.IEightBall + + + System.ServiceModel.Configuration.AddressHeaderCollectionElement + + + <Header /> + + + System.ServiceModel.Configuration.IdentityElement + + + System.ServiceModel.Configuration.UserPrincipalNameElement + + + + + + System.ServiceModel.Configuration.ServicePrincipalNameElement + + + + + + System.ServiceModel.Configuration.DnsElement + + + + + + System.ServiceModel.Configuration.RsaElement + + + + + + System.ServiceModel.Configuration.CertificateElement + + + + + + System.ServiceModel.Configuration.CertificateReferenceElement + + + My + + + LocalMachine + + + FindBySubjectDistinguishedName + + + + + + False + + + BasicHttpBinding_IEightBall + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/MagicEightBallServiceClient.csproj b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/MagicEightBallServiceClient.csproj new file mode 100644 index 0000000..53fa7cd --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/MagicEightBallServiceClient.csproj @@ -0,0 +1,88 @@ + + + + + Debug + AnyCPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006} + Exe + MagicEightBallServiceClient + MagicEightBallServiceClient + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + True + True + Reference.svcmap + + + + + + + + + Designer + + + + Designer + + + + + + + + + + + + + + + + + + + + WCF Proxy Generator + Reference.cs + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/MagicEightBallServiceClient.sln b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/MagicEightBallServiceClient.sln new file mode 100644 index 0000000..454434f --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/MagicEightBallServiceClient.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicEightBallServiceClient", "MagicEightBallServiceClient\MagicEightBallServiceClient.csproj", "{79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Debug|Any CPU.Build.0 = Debug|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Release|Any CPU.ActiveCfg = Release|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Program.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Program.cs new file mode 100644 index 0000000..f42821c --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Program.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MagicEightBallServiceClient.ServiceReference1; + +namespace MagicEightBallServiceClient +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Ask the Magic 8 Ball *****\n"); + + using (EightBallClient ball = new EightBallClient()) + { + Console.Write("Your question: "); + string question = Console.ReadLine(); + string answer = + ball.ObtainAnswerToQuestion(question); + Console.WriteLine("8-Ball says: {0}", answer); + } + Console.ReadLine(); + } + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Properties/AssemblyInfo.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..107a828 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MagicEightBallServiceClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MagicEightBallServiceClient")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("79daeb9f-f554-41e4-ac7a-5fe2b11b1006")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Proxy Files/app.config b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Proxy Files/app.config new file mode 100644 index 0000000..dbbca43 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Proxy Files/app.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Proxy Files/myproxy.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Proxy Files/myproxy.cs new file mode 100644 index 0000000..e7f9d26 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceClient/Proxy Files/myproxy.cs @@ -0,0 +1,68 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + + +[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] +[System.ServiceModel.ServiceContractAttribute(Namespace="http://MyCompany.com", ConfigurationName="IEightBall")] +public interface IEightBall +{ + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IEightBall/ObtainAnswerToQuestion", ReplyAction="http://MyCompany.com/IEightBall/ObtainAnswerToQuestionResponse")] + string ObtainAnswerToQuestion(string userQuestion); + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IEightBall/ObtainAnswerToQuestion", ReplyAction="http://MyCompany.com/IEightBall/ObtainAnswerToQuestionResponse")] + System.Threading.Tasks.Task ObtainAnswerToQuestionAsync(string userQuestion); +} + +[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] +public interface IEightBallChannel : IEightBall, System.ServiceModel.IClientChannel +{ +} + +[System.Diagnostics.DebuggerStepThroughAttribute()] +[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] +public partial class EightBallClient : System.ServiceModel.ClientBase, IEightBall +{ + + public EightBallClient() + { + } + + public EightBallClient(string endpointConfigurationName) : + base(endpointConfigurationName) + { + } + + public EightBallClient(string endpointConfigurationName, string remoteAddress) : + base(endpointConfigurationName, remoteAddress) + { + } + + public EightBallClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : + base(endpointConfigurationName, remoteAddress) + { + } + + public EightBallClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : + base(binding, remoteAddress) + { + } + + public string ObtainAnswerToQuestion(string userQuestion) + { + return base.Channel.ObtainAnswerToQuestion(userQuestion); + } + + public System.Threading.Tasks.Task ObtainAnswerToQuestionAsync(string userQuestion) + { + return base.Channel.ObtainAnswerToQuestionAsync(userQuestion); + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHTTP.sln b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHTTP.sln new file mode 100644 index 0000000..310c360 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHTTP.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicEightBallServiceLib", "MagicEightBallServiceLib\MagicEightBallServiceLib.csproj", "{BD249056-565D-46FF-87B6-51E41AB6FFEE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicEightBallServiceHost", "MagicEightBallServiceHost\MagicEightBallServiceHost.csproj", "{9AEE7261-2B46-4776-8899-AB66B1B667D0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicEightBallServiceClient", "MagicEightBallServiceClient\MagicEightBallServiceClient.csproj", "{79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BD249056-565D-46FF-87B6-51E41AB6FFEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BD249056-565D-46FF-87B6-51E41AB6FFEE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BD249056-565D-46FF-87B6-51E41AB6FFEE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BD249056-565D-46FF-87B6-51E41AB6FFEE}.Release|Any CPU.Build.0 = Release|Any CPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0}.Release|Any CPU.Build.0 = Release|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Debug|Any CPU.Build.0 = Debug|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Release|Any CPU.ActiveCfg = Release|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/App.config b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/App.config new file mode 100644 index 0000000..0ea3bfc --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/App.config @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/MagicEightBallServiceHost.csproj b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/MagicEightBallServiceHost.csproj new file mode 100644 index 0000000..1ce9225 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/MagicEightBallServiceHost.csproj @@ -0,0 +1,61 @@ + + + + + Debug + AnyCPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0} + Exe + MagicEightBallServiceHost + MagicEightBallServiceHost + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + Designer + + + + + {bd249056-565d-46ff-87b6-51e41ab6ffee} + MagicEightBallServiceLib + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/Program.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/Program.cs new file mode 100644 index 0000000..53def70 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/Program.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using System.ServiceModel; +using MagicEightBallServiceLib; + +namespace MagicEightBallServiceHost +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Console Based WCF Host *****"); + + //using (ServiceHost serviceHost = new ServiceHost(typeof(MagicEightBallService), + // new Uri[]{new Uri("http://localhost:8080/MagicEightBallServer")})) + using (ServiceHost serviceHost = new ServiceHost(typeof(MagicEightBallService))) + { + // Open the host and start listening for incoming messages. + serviceHost.Open(); + DisplayHostInfo(serviceHost); + // Keep the service running until Enter key is pressed. + Console.WriteLine("The service is ready."); + Console.WriteLine("Press the Enter key to terminate service."); + Console.ReadLine(); + } + } + + #region Show all the ABCs exposed from the host. + static void DisplayHostInfo(ServiceHost host) + { + Console.WriteLine(); + Console.WriteLine("***** Host Info *****"); + + foreach (System.ServiceModel.Description.ServiceEndpoint se in host.Description.Endpoints) + { + Console.WriteLine("Address: {0}", se.Address); + Console.WriteLine("Binding: {0}", se.Binding.Name); + Console.WriteLine("Contract: {0}", se.Contract.Name); + } + Console.WriteLine("**********************"); + } + #endregion + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/Properties/AssemblyInfo.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..348e234 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceHost/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MagicEightBallServiceHost")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MagicEightBallServiceHost")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9aee7261-2b46-4776-8899-ab66b1b667d0")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/IEightBall.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/IEightBall.cs new file mode 100644 index 0000000..1327f69 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/IEightBall.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.ServiceModel; + +namespace MagicEightBallServiceLib +{ + [ServiceContract(Namespace = "http://MyCompany.com")] + public interface IEightBall + { + // Ask a question, receive an answer! + [OperationContract] + string ObtainAnswerToQuestion(string userQuestion); + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/MagicEightBallService.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/MagicEightBallService.cs new file mode 100644 index 0000000..da37e6c --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/MagicEightBallService.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +// The key WCF namespace. +using System.ServiceModel; + +namespace MagicEightBallServiceLib +{ + public class MagicEightBallService : IEightBall + { + public MagicEightBallService() + { + Console.WriteLine("The 8-Ball awaits your question..."); + } + public string ObtainAnswerToQuestion(string userQuestion) + { + string[] answers = { "Future Uncertain", "Yes", "No", + "Hazy", "Ask again later", "Definitely" }; + + // Return a random response. + Random r = new Random(); + return answers[r.Next(answers.Length)]; + } + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/MagicEightBallServiceLib.csproj b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/MagicEightBallServiceLib.csproj new file mode 100644 index 0000000..1aa131f --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/MagicEightBallServiceLib.csproj @@ -0,0 +1,49 @@ + + + + + Debug + AnyCPU + {BD249056-565D-46FF-87B6-51E41AB6FFEE} + Library + Properties + MagicEightBallServiceLib + MagicEightBallServiceLib + v4.7 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/Properties/AssemblyInfo.cs b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1890393 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTP/MagicEightBallServiceLib/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MagicEightBallServiceLib")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MagicEightBallServiceLib")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("bd249056-565d-46ff-87b6-51e41ab6ffee")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/App.config b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/App.config new file mode 100644 index 0000000..448b91b --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/App.config @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.disco b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.disco new file mode 100644 index 0000000..1f46fc9 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.disco @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.wsdl b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.wsdl new file mode 100644 index 0000000..08714f3 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.wsdl @@ -0,0 +1,73 @@ + + + + + + + + + + + + EncryptAndSign + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + net.tcp://localhost:8099/MagicEightBallService + + PHILSURFACEBOOK\Skimedic + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.xsd b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.xsd new file mode 100644 index 0000000..1db1379 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService.xsd @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.wsdl b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.wsdl new file mode 100644 index 0000000..53841a6 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.wsdl @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.xsd b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.xsd new file mode 100644 index 0000000..d58e7f3 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/MagicEightBallService1.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.cs new file mode 100644 index 0000000..3a547f0 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.cs @@ -0,0 +1,60 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace MagicEightBallServiceClient.ServiceReference1 { + + + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + [System.ServiceModel.ServiceContractAttribute(Namespace="http://MyCompany.com", ConfigurationName="ServiceReference1.IEightBall")] + public interface IEightBall { + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IEightBall/ObtainAnswerToQuestion", ReplyAction="http://MyCompany.com/IEightBall/ObtainAnswerToQuestionResponse")] + string ObtainAnswerToQuestion(string userQuestion); + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IEightBall/ObtainAnswerToQuestion", ReplyAction="http://MyCompany.com/IEightBall/ObtainAnswerToQuestionResponse")] + System.Threading.Tasks.Task ObtainAnswerToQuestionAsync(string userQuestion); + } + + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public interface IEightBallChannel : MagicEightBallServiceClient.ServiceReference1.IEightBall, System.ServiceModel.IClientChannel { + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public partial class EightBallClient : System.ServiceModel.ClientBase, MagicEightBallServiceClient.ServiceReference1.IEightBall { + + public EightBallClient() { + } + + public EightBallClient(string endpointConfigurationName) : + base(endpointConfigurationName) { + } + + public EightBallClient(string endpointConfigurationName, string remoteAddress) : + base(endpointConfigurationName, remoteAddress) { + } + + public EightBallClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : + base(endpointConfigurationName, remoteAddress) { + } + + public EightBallClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : + base(binding, remoteAddress) { + } + + public string ObtainAnswerToQuestion(string userQuestion) { + return base.Channel.ObtainAnswerToQuestion(userQuestion); + } + + public System.Threading.Tasks.Task ObtainAnswerToQuestionAsync(string userQuestion) { + return base.Channel.ObtainAnswerToQuestionAsync(userQuestion); + } + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.svcmap b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.svcmap new file mode 100644 index 0000000..54fdf23 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/Reference.svcmap @@ -0,0 +1,35 @@ + + + + false + true + true + + false + false + false + + + true + Auto + true + true + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration.svcinfo b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration.svcinfo new file mode 100644 index 0000000..cebe87c --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration.svcinfo @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration91.svcinfo b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration91.svcinfo new file mode 100644 index 0000000..47c35bc --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Connected Services/ServiceReference1/configuration91.svcinfo @@ -0,0 +1,404 @@ + + + + + + + BasicHttpBinding_IEightBall + + + + + + + + + + + + + + + + + + + + + StrongWildcard + + + + + + 65536 + + + + + + + + + System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + System.Text.UTF8Encoding + + + Buffered + + + + + + Text + + + System.ServiceModel.Configuration.BasicHttpSecurityElement + + + None + + + System.ServiceModel.Configuration.HttpTransportSecurityElement + + + None + + + None + + + System.Security.Authentication.ExtendedProtection.Configuration.ExtendedProtectionPolicyElement + + + Never + + + TransportSelected + + + (Collection) + + + + + + System.ServiceModel.Configuration.BasicHttpMessageSecurityElement + + + UserName + + + Default + + + + + + + NetTcpBinding_IEightBall + + + + + + + + + + + + + + + False + + + Buffered + + + OleTransactions + + + StrongWildcard + + + 0 + + + + + + 65536 + + + 0 + + + + + + False + + + System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + System.ServiceModel.Configuration.StandardBindingOptionalReliableSessionElement + + + True + + + 00:10:00 + + + False + + + System.ServiceModel.Configuration.NetTcpSecurityElement + + + Transport + + + System.ServiceModel.Configuration.TcpTransportSecurityElement + + + Windows + + + EncryptAndSign + + + System.Security.Authentication.ExtendedProtection.Configuration.ExtendedProtectionPolicyElement + + + Never + + + TransportSelected + + + (Collection) + + + Tls, Tls11, Tls12 + + + System.ServiceModel.Configuration.MessageSecurityOverTcpElement + + + Windows + + + Default + + + + + + + + + http://localhost:8080/MagicEightBallService + + + + + + basicHttpBinding + + + BasicHttpBinding_IEightBall + + + ServiceReference1.IEightBall + + + System.ServiceModel.Configuration.AddressHeaderCollectionElement + + + <Header /> + + + System.ServiceModel.Configuration.IdentityElement + + + System.ServiceModel.Configuration.UserPrincipalNameElement + + + + + + System.ServiceModel.Configuration.ServicePrincipalNameElement + + + + + + System.ServiceModel.Configuration.DnsElement + + + + + + System.ServiceModel.Configuration.RsaElement + + + + + + System.ServiceModel.Configuration.CertificateElement + + + + + + System.ServiceModel.Configuration.CertificateReferenceElement + + + My + + + LocalMachine + + + FindBySubjectDistinguishedName + + + + + + False + + + BasicHttpBinding_IEightBall + + + + + + + + + + + + + net.tcp://localhost:8099/MagicEightBallService + + + + + + netTcpBinding + + + NetTcpBinding_IEightBall + + + ServiceReference1.IEightBall + + + System.ServiceModel.Configuration.AddressHeaderCollectionElement + + + <Header /> + + + System.ServiceModel.Configuration.IdentityElement + + + System.ServiceModel.Configuration.UserPrincipalNameElement + + + PHILSURFACEBOOK\Skimedic + + + System.ServiceModel.Configuration.ServicePrincipalNameElement + + + + + + System.ServiceModel.Configuration.DnsElement + + + + + + System.ServiceModel.Configuration.RsaElement + + + + + + System.ServiceModel.Configuration.CertificateElement + + + + + + System.ServiceModel.Configuration.CertificateReferenceElement + + + My + + + LocalMachine + + + FindBySubjectDistinguishedName + + + + + + False + + + NetTcpBinding_IEightBall + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/MagicEightBallServiceClient.csproj b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/MagicEightBallServiceClient.csproj new file mode 100644 index 0000000..53fa7cd --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/MagicEightBallServiceClient.csproj @@ -0,0 +1,88 @@ + + + + + Debug + AnyCPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006} + Exe + MagicEightBallServiceClient + MagicEightBallServiceClient + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + True + True + Reference.svcmap + + + + + + + + + Designer + + + + Designer + + + + + + + + + + + + + + + + + + + + WCF Proxy Generator + Reference.cs + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/MagicEightBallServiceClient.sln b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/MagicEightBallServiceClient.sln new file mode 100644 index 0000000..454434f --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/MagicEightBallServiceClient.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicEightBallServiceClient", "MagicEightBallServiceClient\MagicEightBallServiceClient.csproj", "{79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Debug|Any CPU.Build.0 = Debug|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Release|Any CPU.ActiveCfg = Release|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Program.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Program.cs new file mode 100644 index 0000000..bb78cb4 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Program.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MagicEightBallServiceClient.ServiceReference1; + +namespace MagicEightBallServiceClient +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Ask the Magic 8 Ball *****\n"); + + using (EightBallClient ball = new EightBallClient("BasicHttpBinding_IEightBall")) + { + Console.Write("Your question: "); + string question = Console.ReadLine(); + string answer = + ball.ObtainAnswerToQuestion(question); + Console.WriteLine("8-Ball says: {0}", answer); + } + using (EightBallClient ball = new EightBallClient("NetTcpBinding_IEightBall")) + { + Console.Write("Your question: "); + string question = Console.ReadLine(); + string answer = + ball.ObtainAnswerToQuestion(question); + Console.WriteLine("8-Ball says: {0}", answer); + } + Console.ReadLine(); + } + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Properties/AssemblyInfo.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..107a828 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MagicEightBallServiceClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MagicEightBallServiceClient")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("79daeb9f-f554-41e4-ac7a-5fe2b11b1006")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Proxy Files/app.config b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Proxy Files/app.config new file mode 100644 index 0000000..dbbca43 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Proxy Files/app.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Proxy Files/myproxy.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Proxy Files/myproxy.cs new file mode 100644 index 0000000..e7f9d26 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceClient/Proxy Files/myproxy.cs @@ -0,0 +1,68 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + + +[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] +[System.ServiceModel.ServiceContractAttribute(Namespace="http://MyCompany.com", ConfigurationName="IEightBall")] +public interface IEightBall +{ + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IEightBall/ObtainAnswerToQuestion", ReplyAction="http://MyCompany.com/IEightBall/ObtainAnswerToQuestionResponse")] + string ObtainAnswerToQuestion(string userQuestion); + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IEightBall/ObtainAnswerToQuestion", ReplyAction="http://MyCompany.com/IEightBall/ObtainAnswerToQuestionResponse")] + System.Threading.Tasks.Task ObtainAnswerToQuestionAsync(string userQuestion); +} + +[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] +public interface IEightBallChannel : IEightBall, System.ServiceModel.IClientChannel +{ +} + +[System.Diagnostics.DebuggerStepThroughAttribute()] +[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] +public partial class EightBallClient : System.ServiceModel.ClientBase, IEightBall +{ + + public EightBallClient() + { + } + + public EightBallClient(string endpointConfigurationName) : + base(endpointConfigurationName) + { + } + + public EightBallClient(string endpointConfigurationName, string remoteAddress) : + base(endpointConfigurationName, remoteAddress) + { + } + + public EightBallClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : + base(endpointConfigurationName, remoteAddress) + { + } + + public EightBallClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : + base(binding, remoteAddress) + { + } + + public string ObtainAnswerToQuestion(string userQuestion) + { + return base.Channel.ObtainAnswerToQuestion(userQuestion); + } + + public System.Threading.Tasks.Task ObtainAnswerToQuestionAsync(string userQuestion) + { + return base.Channel.ObtainAnswerToQuestionAsync(userQuestion); + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHTTP.sln b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHTTP.sln new file mode 100644 index 0000000..310c360 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHTTP.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicEightBallServiceLib", "MagicEightBallServiceLib\MagicEightBallServiceLib.csproj", "{BD249056-565D-46FF-87B6-51E41AB6FFEE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicEightBallServiceHost", "MagicEightBallServiceHost\MagicEightBallServiceHost.csproj", "{9AEE7261-2B46-4776-8899-AB66B1B667D0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicEightBallServiceClient", "MagicEightBallServiceClient\MagicEightBallServiceClient.csproj", "{79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BD249056-565D-46FF-87B6-51E41AB6FFEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BD249056-565D-46FF-87B6-51E41AB6FFEE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BD249056-565D-46FF-87B6-51E41AB6FFEE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BD249056-565D-46FF-87B6-51E41AB6FFEE}.Release|Any CPU.Build.0 = Release|Any CPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0}.Release|Any CPU.Build.0 = Release|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Debug|Any CPU.Build.0 = Debug|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Release|Any CPU.ActiveCfg = Release|Any CPU + {79DAEB9F-F554-41E4-AC7A-5FE2B11B1006}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/App.config b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/App.config new file mode 100644 index 0000000..3221ed5 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/App.config @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/MagicEightBallServiceHost.csproj b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/MagicEightBallServiceHost.csproj new file mode 100644 index 0000000..1ce9225 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/MagicEightBallServiceHost.csproj @@ -0,0 +1,61 @@ + + + + + Debug + AnyCPU + {9AEE7261-2B46-4776-8899-AB66B1B667D0} + Exe + MagicEightBallServiceHost + MagicEightBallServiceHost + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + Designer + + + + + {bd249056-565d-46ff-87b6-51e41ab6ffee} + MagicEightBallServiceLib + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/Program.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/Program.cs new file mode 100644 index 0000000..53def70 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/Program.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using System.ServiceModel; +using MagicEightBallServiceLib; + +namespace MagicEightBallServiceHost +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** Console Based WCF Host *****"); + + //using (ServiceHost serviceHost = new ServiceHost(typeof(MagicEightBallService), + // new Uri[]{new Uri("http://localhost:8080/MagicEightBallServer")})) + using (ServiceHost serviceHost = new ServiceHost(typeof(MagicEightBallService))) + { + // Open the host and start listening for incoming messages. + serviceHost.Open(); + DisplayHostInfo(serviceHost); + // Keep the service running until Enter key is pressed. + Console.WriteLine("The service is ready."); + Console.WriteLine("Press the Enter key to terminate service."); + Console.ReadLine(); + } + } + + #region Show all the ABCs exposed from the host. + static void DisplayHostInfo(ServiceHost host) + { + Console.WriteLine(); + Console.WriteLine("***** Host Info *****"); + + foreach (System.ServiceModel.Description.ServiceEndpoint se in host.Description.Endpoints) + { + Console.WriteLine("Address: {0}", se.Address); + Console.WriteLine("Binding: {0}", se.Binding.Name); + Console.WriteLine("Contract: {0}", se.Contract.Name); + } + Console.WriteLine("**********************"); + } + #endregion + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/Properties/AssemblyInfo.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..348e234 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceHost/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MagicEightBallServiceHost")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MagicEightBallServiceHost")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9aee7261-2b46-4776-8899-ab66b1b667d0")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/IEightBall.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/IEightBall.cs new file mode 100644 index 0000000..1327f69 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/IEightBall.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.ServiceModel; + +namespace MagicEightBallServiceLib +{ + [ServiceContract(Namespace = "http://MyCompany.com")] + public interface IEightBall + { + // Ask a question, receive an answer! + [OperationContract] + string ObtainAnswerToQuestion(string userQuestion); + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/MagicEightBallService.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/MagicEightBallService.cs new file mode 100644 index 0000000..da37e6c --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/MagicEightBallService.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +// The key WCF namespace. +using System.ServiceModel; + +namespace MagicEightBallServiceLib +{ + public class MagicEightBallService : IEightBall + { + public MagicEightBallService() + { + Console.WriteLine("The 8-Ball awaits your question..."); + } + public string ObtainAnswerToQuestion(string userQuestion) + { + string[] answers = { "Future Uncertain", "Yes", "No", + "Hazy", "Ask again later", "Definitely" }; + + // Return a random response. + Random r = new Random(); + return answers[r.Next(answers.Length)]; + } + } +} diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/MagicEightBallServiceLib.csproj b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/MagicEightBallServiceLib.csproj new file mode 100644 index 0000000..1aa131f --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/MagicEightBallServiceLib.csproj @@ -0,0 +1,49 @@ + + + + + Debug + AnyCPU + {BD249056-565D-46FF-87B6-51E41AB6FFEE} + Library + Properties + MagicEightBallServiceLib + MagicEightBallServiceLib + v4.7 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/Properties/AssemblyInfo.cs b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1890393 --- /dev/null +++ b/Chapter_23/MagicEightBallServiceHTTPDefaultBindings/MagicEightBallServiceLib/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MagicEightBallServiceLib")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MagicEightBallServiceLib")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("bd249056-565d-46ff-87b6-51e41ab6ffee")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/MagicEightBallTCP/Client/MagicEightBallServiceClient.exe.config b/Chapter_23/MagicEightBallTCP/Client/MagicEightBallServiceClient.exe.config new file mode 100644 index 0000000..05f4799 --- /dev/null +++ b/Chapter_23/MagicEightBallTCP/Client/MagicEightBallServiceClient.exe.config @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/Chapter_23/MagicEightBallTCP/Host/MagicEightBallServiceHost.exe.config b/Chapter_23/MagicEightBallTCP/Host/MagicEightBallServiceHost.exe.config new file mode 100644 index 0000000..7a4cc37 --- /dev/null +++ b/Chapter_23/MagicEightBallTCP/Host/MagicEightBallServiceHost.exe.config @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/App.config b/Chapter_23/MathServiceLibrary/MathClient/App.config new file mode 100644 index 0000000..0ea2501 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/App.config @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathService.wsdl b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathService.wsdl new file mode 100644 index 0000000..4adcc1c --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathService.wsdl @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.disco b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.disco new file mode 100644 index 0000000..ace78b8 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.disco @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.wsdl b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.wsdl new file mode 100644 index 0000000..5206b75 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.wsdl @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.xsd b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.xsd new file mode 100644 index 0000000..eeabd58 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary1.xsd b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary1.xsd new file mode 100644 index 0000000..d58e7f3 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/MathServiceLibrary1.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/Reference.cs b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/Reference.cs new file mode 100644 index 0000000..2896fdc --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/Reference.cs @@ -0,0 +1,133 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace MathClient.ServiceReference1 { + + + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + [System.ServiceModel.ServiceContractAttribute(Namespace="http://MyCompany.com", ConfigurationName="ServiceReference1.IBasicMath")] + public interface IBasicMath { + + [System.ServiceModel.OperationContractAttribute(Action="http://MyCompany.com/IBasicMath/Add", ReplyAction="http://MyCompany.com/IBasicMath/AddResponse")] + int Add(int x, int y); + + [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://MyCompany.com/IBasicMath/Add", ReplyAction="http://MyCompany.com/IBasicMath/AddResponse")] + System.IAsyncResult BeginAdd(int x, int y, System.AsyncCallback callback, object asyncState); + + int EndAdd(System.IAsyncResult result); + } + + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public interface IBasicMathChannel : MathClient.ServiceReference1.IBasicMath, System.ServiceModel.IClientChannel { + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public partial class AddCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + public AddCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + public int Result { + get { + base.RaiseExceptionIfNecessary(); + return ((int)(this.results[0])); + } + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public partial class BasicMathClient : System.ServiceModel.ClientBase, MathClient.ServiceReference1.IBasicMath { + + private BeginOperationDelegate onBeginAddDelegate; + + private EndOperationDelegate onEndAddDelegate; + + private System.Threading.SendOrPostCallback onAddCompletedDelegate; + + public BasicMathClient() { + } + + public BasicMathClient(string endpointConfigurationName) : + base(endpointConfigurationName) { + } + + public BasicMathClient(string endpointConfigurationName, string remoteAddress) : + base(endpointConfigurationName, remoteAddress) { + } + + public BasicMathClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : + base(endpointConfigurationName, remoteAddress) { + } + + public BasicMathClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : + base(binding, remoteAddress) { + } + + public event System.EventHandler AddCompleted; + + public int Add(int x, int y) { + return base.Channel.Add(x, y); + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public System.IAsyncResult BeginAdd(int x, int y, System.AsyncCallback callback, object asyncState) { + return base.Channel.BeginAdd(x, y, callback, asyncState); + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public int EndAdd(System.IAsyncResult result) { + return base.Channel.EndAdd(result); + } + + private System.IAsyncResult OnBeginAdd(object[] inValues, System.AsyncCallback callback, object asyncState) { + int x = ((int)(inValues[0])); + int y = ((int)(inValues[1])); + return this.BeginAdd(x, y, callback, asyncState); + } + + private object[] OnEndAdd(System.IAsyncResult result) { + int retVal = this.EndAdd(result); + return new object[] { + retVal}; + } + + private void OnAddCompleted(object state) { + if ((this.AddCompleted != null)) { + InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state)); + this.AddCompleted(this, new AddCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState)); + } + } + + public void AddAsync(int x, int y) { + this.AddAsync(x, y, null); + } + + public void AddAsync(int x, int y, object userState) { + if ((this.onBeginAddDelegate == null)) { + this.onBeginAddDelegate = new BeginOperationDelegate(this.OnBeginAdd); + } + if ((this.onEndAddDelegate == null)) { + this.onEndAddDelegate = new EndOperationDelegate(this.OnEndAdd); + } + if ((this.onAddCompletedDelegate == null)) { + this.onAddCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnAddCompleted); + } + base.InvokeAsync(this.onBeginAddDelegate, new object[] { + x, + y}, this.onEndAddDelegate, this.onAddCompletedDelegate, userState); + } + } +} diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/Reference.svcmap b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/Reference.svcmap new file mode 100644 index 0000000..c5662fd --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/Reference.svcmap @@ -0,0 +1,34 @@ + + + + true + true + + false + false + false + + + true + Auto + true + true + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/configuration.svcinfo b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/configuration.svcinfo new file mode 100644 index 0000000..c785f93 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/configuration.svcinfo @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/configuration91.svcinfo b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/configuration91.svcinfo new file mode 100644 index 0000000..0fb6f28 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Connected Services/ServiceReference1/configuration91.svcinfo @@ -0,0 +1,201 @@ + + + + + + + BasicHttpBinding_IBasicMath + + + + + + + + + + + + + + + + + + + + + StrongWildcard + + + + + + 65536 + + + + + + + + + System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + System.Text.UTF8Encoding + + + Buffered + + + + + + Text + + + System.ServiceModel.Configuration.BasicHttpSecurityElement + + + None + + + System.ServiceModel.Configuration.HttpTransportSecurityElement + + + None + + + None + + + System.Security.Authentication.ExtendedProtection.Configuration.ExtendedProtectionPolicyElement + + + Never + + + TransportSelected + + + (Collection) + + + + + + System.ServiceModel.Configuration.BasicHttpMessageSecurityElement + + + UserName + + + Default + + + + + + + + + http://localhost:8080/MathServiceLibrary + + + + + + basicHttpBinding + + + BasicHttpBinding_IBasicMath + + + ServiceReference1.IBasicMath + + + System.ServiceModel.Configuration.AddressHeaderCollectionElement + + + <Header /> + + + System.ServiceModel.Configuration.IdentityElement + + + System.ServiceModel.Configuration.UserPrincipalNameElement + + + + + + System.ServiceModel.Configuration.ServicePrincipalNameElement + + + + + + System.ServiceModel.Configuration.DnsElement + + + + + + System.ServiceModel.Configuration.RsaElement + + + + + + System.ServiceModel.Configuration.CertificateElement + + + + + + System.ServiceModel.Configuration.CertificateReferenceElement + + + My + + + LocalMachine + + + FindBySubjectDistinguishedName + + + + + + False + + + BasicHttpBinding_IBasicMath + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/MathClient.csproj b/Chapter_23/MathServiceLibrary/MathClient/MathClient.csproj new file mode 100644 index 0000000..7ba91c3 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/MathClient.csproj @@ -0,0 +1,88 @@ + + + + + Debug + AnyCPU + {3DB37783-E0A6-44EB-ACC3-F254C445684A} + Exe + MathClient + MathClient + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + True + True + Reference.svcmap + + + + + + + + + + Designer + + + Designer + + + + + + + + + + + + + + + + + + + + WCF Proxy Generator + Reference.cs + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Program.cs b/Chapter_23/MathServiceLibrary/MathClient/Program.cs new file mode 100644 index 0000000..996679b --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Program.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MathClient.ServiceReference1; + +namespace MathClient +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("***** The Async Math Client *****\n"); + + using (BasicMathClient proxy = new BasicMathClient()) + { + proxy.Open(); + + // Add numbers in an async manner, using a lambda expression. + IAsyncResult result = proxy.BeginAdd(2, 3, + ar => + { + Console.WriteLine("2 + 3 = {0}", proxy.EndAdd(ar)); + }, + null); + + while (!result.IsCompleted) + { + Thread.Sleep(200); + Console.WriteLine("Client working..."); + } + } + Console.ReadLine(); + } + } +} \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathClient/Properties/AssemblyInfo.cs b/Chapter_23/MathServiceLibrary/MathClient/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c3a21d2 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathClient/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MathClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MathClient")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3db37783-e0a6-44eb-acc3-f254c445684a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/MathServiceLibrary/MathServiceLibrary.sln b/Chapter_23/MathServiceLibrary/MathServiceLibrary.sln new file mode 100644 index 0000000..6b1ef28 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathServiceLibrary.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathServiceLibrary", "MathServiceLibrary\MathServiceLibrary.csproj", "{52B28FA3-1021-41A0-BC07-D7ADF0495B7E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathWindowsServiceHost", "MathWindowsServiceHost\MathWindowsServiceHost.csproj", "{0919B28B-5E7B-44E9-B192-476B218608A1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathClient", "MathClient\MathClient.csproj", "{3DB37783-E0A6-44EB-ACC3-F254C445684A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {52B28FA3-1021-41A0-BC07-D7ADF0495B7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {52B28FA3-1021-41A0-BC07-D7ADF0495B7E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {52B28FA3-1021-41A0-BC07-D7ADF0495B7E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {52B28FA3-1021-41A0-BC07-D7ADF0495B7E}.Release|Any CPU.Build.0 = Release|Any CPU + {0919B28B-5E7B-44E9-B192-476B218608A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0919B28B-5E7B-44E9-B192-476B218608A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0919B28B-5E7B-44E9-B192-476B218608A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0919B28B-5E7B-44E9-B192-476B218608A1}.Release|Any CPU.Build.0 = Release|Any CPU + {3DB37783-E0A6-44EB-ACC3-F254C445684A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3DB37783-E0A6-44EB-ACC3-F254C445684A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3DB37783-E0A6-44EB-ACC3-F254C445684A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3DB37783-E0A6-44EB-ACC3-F254C445684A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_23/MathServiceLibrary/MathServiceLibrary/App.config b/Chapter_23/MathServiceLibrary/MathServiceLibrary/App.config new file mode 100644 index 0000000..e282ff2 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathServiceLibrary/App.config @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Chapter_23/MathServiceLibrary/MathServiceLibrary/IBasicMath.cs b/Chapter_23/MathServiceLibrary/MathServiceLibrary/IBasicMath.cs new file mode 100644 index 0000000..53184de --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathServiceLibrary/IBasicMath.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.ServiceModel; +using System.Text; + +namespace MathServiceLibrary +{ + [ServiceContract(Namespace = "http://MyCompany.com")] + public interface IBasicMath + { + [OperationContract] + int Add(int x, int y); + } + +} diff --git a/Chapter_23/MathServiceLibrary/MathServiceLibrary/MathService.cs b/Chapter_23/MathServiceLibrary/MathServiceLibrary/MathService.cs new file mode 100644 index 0000000..b52024b --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathServiceLibrary/MathService.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.ServiceModel; +using System.Text; + +namespace MathServiceLibrary +{ + // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together. + public class MathService : IBasicMath + { + public int Add(int x, int y) + { + // To simulate a lengthy request + System.Threading.Thread.Sleep(5000); + return x + y; + } + } +} diff --git a/Chapter_23/MathServiceLibrary/MathServiceLibrary/MathServiceLibrary.csproj b/Chapter_23/MathServiceLibrary/MathServiceLibrary/MathServiceLibrary.csproj new file mode 100644 index 0000000..bb7540b --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathServiceLibrary/MathServiceLibrary.csproj @@ -0,0 +1,77 @@ + + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {52B28FA3-1021-41A0-BC07-D7ADF0495B7E} + Library + Properties + MathServiceLibrary + MathServiceLibrary + {3D9AD99F-2412-4246-B90B-4EAA41C64699};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + /client:"WcfTestClient.exe" + v4.7 + True + True + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio + $(VSToolsPath)\WCF + + + + + + + True + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathServiceLibrary/Properties/AssemblyInfo.cs b/Chapter_23/MathServiceLibrary/MathServiceLibrary/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..85ea20f --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathServiceLibrary/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MathServiceLibrary")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MathServiceLibrary")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("52b28fa3-1021-41a0-bc07-d7adf0495b7e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/App.config b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/App.config new file mode 100644 index 0000000..cdb60db --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/App.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWinService.Designer.cs b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWinService.Designer.cs new file mode 100644 index 0000000..98c1ec5 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWinService.Designer.cs @@ -0,0 +1,37 @@ +namespace MathWindowsServiceHost +{ + partial class MathWinService + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.ServiceName = "Service1"; + } + + #endregion + } +} diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWinService.cs b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWinService.cs new file mode 100644 index 0000000..df709d5 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWinService.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.ServiceModel; +using System.ServiceProcess; +using System.Text; +using System.Threading.Tasks; +using MathServiceLibrary; + +namespace MathWindowsServiceHost +{ + public partial class MathWinService : ServiceBase + { + //A member variable of type ServiceHost + private ServiceHost myHost; + public MathWinService() + { + InitializeComponent(); + } + + protected override void OnStart(string[] args) + { + ////Just to be safe + //myHost?.Close(); + ////Create the service + //myHost = new ServiceHost(typeof(MathService)); + ////The ABCs in Code! + //Uri address = new Uri("http://localhost:8080/MathServiceLibrary"); + //WSHttpBinding binding = new WSHttpBinding(); + //Type contract = typeof(IBasicMath); + + ////Add the endpoint + //myHost.AddServiceEndpoint(contract, binding, address); + + ////Open the host + //myHost.Open(); + + //Using the defaults + myHost?.Close(); + // Create the host and specify a URL for an HTTP binding. + myHost = new ServiceHost(typeof(MathService), + new Uri("http://localhost:8080/MathServiceLibrary")); + myHost.AddDefaultEndpoints(); + + // Open the host. + myHost.Open(); + } + + protected override void OnStop() + { + //Shut down the service + myHost?.Close(); + } + } +} diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWindowsServiceHost.csproj b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWindowsServiceHost.csproj new file mode 100644 index 0000000..a0331f0 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/MathWindowsServiceHost.csproj @@ -0,0 +1,79 @@ + + + + + Debug + AnyCPU + {0919B28B-5E7B-44E9-B192-476B218608A1} + WinExe + MathWindowsServiceHost + MathWindowsServiceHost + v4.7 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + Component + + + MathWinService.cs + + + + Component + + + ProjectInstaller.cs + + + + + + + + + {52b28fa3-1021-41a0-bc07-d7adf0495b7e} + MathServiceLibrary + + + + + ProjectInstaller.cs + + + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/Program.cs b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/Program.cs new file mode 100644 index 0000000..48750c2 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/Program.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.ServiceProcess; +using System.Text; +using System.Threading.Tasks; + +namespace MathWindowsServiceHost +{ + static class Program + { + /// + /// The main entry point for the application. + /// + static void Main() + { + ServiceBase[] ServicesToRun; + ServicesToRun = new ServiceBase[] + { + new MathWinService() + }; + ServiceBase.Run(ServicesToRun); + } + } +} \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.Designer.cs b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.Designer.cs new file mode 100644 index 0000000..b1fd6b4 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.Designer.cs @@ -0,0 +1,60 @@ +namespace MathWindowsServiceHost +{ + partial class ProjectInstaller + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); + this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); + // + // serviceProcessInstaller1 + // + this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; + this.serviceProcessInstaller1.Password = null; + this.serviceProcessInstaller1.Username = null; + this.serviceProcessInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall); + // + // serviceInstaller1 + // + this.serviceInstaller1.Description = "This is the math service"; + this.serviceInstaller1.ServiceName = "MathService"; + this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; + // + // ProjectInstaller + // + this.Installers.AddRange(new System.Configuration.Install.Installer[] { + this.serviceProcessInstaller1, + this.serviceInstaller1}); + + } + + #endregion + + private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; + private System.ServiceProcess.ServiceInstaller serviceInstaller1; + } +} \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.cs b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.cs new file mode 100644 index 0000000..acebeed --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration.Install; +using System.Linq; +using System.Threading.Tasks; + +namespace MathWindowsServiceHost +{ + [RunInstaller(true)] + public partial class ProjectInstaller : System.Configuration.Install.Installer + { + public ProjectInstaller() + { + InitializeComponent(); + } + + private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e) + { + + } + } +} diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.resx b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.resx new file mode 100644 index 0000000..53840a9 --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/ProjectInstaller.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 328, 17 + + + False + + \ No newline at end of file diff --git a/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/Properties/AssemblyInfo.cs b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..793059b --- /dev/null +++ b/Chapter_23/MathServiceLibrary/MathWindowsServiceHost/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MathWindowsServiceHost")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MathWindowsServiceHost")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0919b28b-5e7b-44e9-b192-476b218608a1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp.sln b/Chapter_24/WpfTesterApp/WpfTesterApp.sln new file mode 100644 index 0000000..aa0d922 --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfTesterApp", "WpfTesterApp\WpfTesterApp.csproj", "{D2A45B76-20BA-4E54-9D31-A86D54447428}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D2A45B76-20BA-4E54-9D31-A86D54447428}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D2A45B76-20BA-4E54-9D31-A86D54447428}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D2A45B76-20BA-4E54-9D31-A86D54447428}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D2A45B76-20BA-4E54-9D31-A86D54447428}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/App.config b/Chapter_24/WpfTesterApp/WpfTesterApp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/App.xaml b/Chapter_24/WpfTesterApp/WpfTesterApp/App.xaml new file mode 100644 index 0000000..2806277 --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/App.xaml.cs b/Chapter_24/WpfTesterApp/WpfTesterApp/App.xaml.cs new file mode 100644 index 0000000..ee94a4f --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/App.xaml.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace WpfTesterApp +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { +private void App_OnStartup(object sender, StartupEventArgs e) +{ + Application.Current.Properties["GodMode"] = false; + // Check the incoming command-line arguments and see if they + // specified a flag for /GODMODE. + foreach (string arg in e.Args) + { + if (arg.Equals("/godmode",StringComparison.OrdinalIgnoreCase)) + { + Application.Current.Properties["GodMode"] = true; + break; + } + } + +} + + private void App_OnExit(object sender, ExitEventArgs e) + { + } + } +} diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/MainWindow.xaml b/Chapter_24/WpfTesterApp/WpfTesterApp/MainWindow.xaml new file mode 100644 index 0000000..6af69f9 --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/MainWindow.xaml @@ -0,0 +1,23 @@ + + + + + + + diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/MainWindow.xaml.cs b/Chapter_24/WpfTesterApp/WpfTesterApp/MainWindow.xaml.cs new file mode 100644 index 0000000..e8e0c22 --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/MainWindow.xaml.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace WpfTesterApp +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : Window + { + public MainWindow() + { + InitializeComponent(); + this.Closed+=MainWindow_OnClosed; + this.Closing += MainWindow_Closing; + this.MouseMove += MainWindow_MouseMove; + this.KeyDown += MainWindow_KeyDown; + } + + private void MainWindow_KeyDown(object sender, KeyEventArgs e) + { + ClickMe.Content = e.Key.ToString(); + } + + private void MainWindow_MouseMove(object sender, MouseEventArgs e) + { + // Set the title of the window to the current (x,y) of the mouse. + this.Title = e.GetPosition(this).ToString(); + } + + private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) + { + // See if the user really wants to shut down this window. + string msg = "Do you want to close without saving?"; + MessageBoxResult result = MessageBox.Show(msg, + "My App", MessageBoxButton.YesNo, MessageBoxImage.Warning); + + if (result == MessageBoxResult.No) + { + // If user doesn't want to close, cancel closure. + e.Cancel = true; + } + } + + private void MainWindow_OnClosed(object sender, EventArgs eventArgs) + { + MessageBox.Show("See ya!"); + } + + private void Button_Click(object sender, RoutedEventArgs e) + { + // Did user enable /godmode? + if ((bool) Application.Current.Properties["GodMode"]) + { + MessageBox.Show("Cheater!"); + } + } + + private void MyCalendar_OnSelectedDatesChanged(object sender, SelectionChangedEventArgs e) + { + } + } +} \ No newline at end of file diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/AssemblyInfo.cs b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4cb26a1 --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/AssemblyInfo.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("WpfTesterApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WpfTesterApp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +//In order to begin building localizable applications, set +//CultureYouAreCodingWith in your .csproj file +//inside a . For example, if you are using US english +//in your source files, set the to en-US. Then uncomment +//the NeutralResourceLanguage attribute below. Update the "en-US" in +//the line below to match the UICulture setting in the project file. + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] + + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Resources.Designer.cs b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Resources.Designer.cs new file mode 100644 index 0000000..5426f4b --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WpfTesterApp.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfTesterApp.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Resources.resx b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Settings.Designer.cs b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Settings.Designer.cs new file mode 100644 index 0000000..f44b1e6 --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WpfTesterApp.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Settings.settings b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Chapter_24/WpfTesterApp/WpfTesterApp/WpfTesterApp.csproj b/Chapter_24/WpfTesterApp/WpfTesterApp/WpfTesterApp.csproj new file mode 100644 index 0000000..2d90112 --- /dev/null +++ b/Chapter_24/WpfTesterApp/WpfTesterApp/WpfTesterApp.csproj @@ -0,0 +1,97 @@ + + + + + Debug + AnyCPU + {D2A45B76-20BA-4E54-9D31-A86D54447428} + WinExe + WpfTesterApp + WpfTesterApp + v4.7 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + \ No newline at end of file diff --git a/Chapter_25/CustomDepProp/CustomDepProp.sln b/Chapter_25/CustomDepProp/CustomDepProp.sln new file mode 100644 index 0000000..f3f3a43 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomDepProp", "CustomDepProp\CustomDepProp.csproj", "{7FABA4C3-F927-4CED-98A1-FC80C5F11414}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7FABA4C3-F927-4CED-98A1-FC80C5F11414}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7FABA4C3-F927-4CED-98A1-FC80C5F11414}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7FABA4C3-F927-4CED-98A1-FC80C5F11414}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7FABA4C3-F927-4CED-98A1-FC80C5F11414}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_25/CustomDepProp/CustomDepProp/App.config b/Chapter_25/CustomDepProp/CustomDepProp/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_25/CustomDepProp/CustomDepProp/App.xaml b/Chapter_25/CustomDepProp/CustomDepProp/App.xaml new file mode 100644 index 0000000..ea47deb --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/Chapter_25/CustomDepProp/CustomDepProp/App.xaml.cs b/Chapter_25/CustomDepProp/CustomDepProp/App.xaml.cs new file mode 100644 index 0000000..dc74f49 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace CustomDepProp +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/Chapter_25/CustomDepProp/CustomDepProp/CustomDepProp.csproj b/Chapter_25/CustomDepProp/CustomDepProp/CustomDepProp.csproj new file mode 100644 index 0000000..95980e6 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/CustomDepProp.csproj @@ -0,0 +1,104 @@ + + + + + Debug + AnyCPU + {7FABA4C3-F927-4CED-98A1-FC80C5F11414} + WinExe + CustomDepProp + CustomDepProp + v4.7 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + ShowNumberControl.xaml + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + Designer + MSBuild:Compile + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + \ No newline at end of file diff --git a/Chapter_25/CustomDepProp/CustomDepProp/MainWindow.xaml b/Chapter_25/CustomDepProp/CustomDepProp/MainWindow.xaml new file mode 100644 index 0000000..418fe36 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/MainWindow.xaml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + diff --git a/Chapter_25/CustomDepProp/CustomDepProp/MainWindow.xaml.cs b/Chapter_25/CustomDepProp/CustomDepProp/MainWindow.xaml.cs new file mode 100644 index 0000000..ae16eb8 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/MainWindow.xaml.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace CustomDepProp +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : Window + { + public MainWindow() + { + InitializeComponent(); + } + + } +} diff --git a/Chapter_25/CustomDepProp/CustomDepProp/Properties/AssemblyInfo.cs b/Chapter_25/CustomDepProp/CustomDepProp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..56e39a7 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/Properties/AssemblyInfo.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CustomDepProp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CustomDepProp")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +//In order to begin building localizable applications, set +//CultureYouAreCodingWith in your .csproj file +//inside a . For example, if you are using US english +//in your source files, set the to en-US. Then uncomment +//the NeutralResourceLanguage attribute below. Update the "en-US" in +//the line below to match the UICulture setting in the project file. + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] + + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_25/CustomDepProp/CustomDepProp/Properties/Resources.Designer.cs b/Chapter_25/CustomDepProp/CustomDepProp/Properties/Resources.Designer.cs new file mode 100644 index 0000000..f13628f --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace CustomDepProp.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CustomDepProp.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Chapter_25/CustomDepProp/CustomDepProp/Properties/Resources.resx b/Chapter_25/CustomDepProp/CustomDepProp/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Chapter_25/CustomDepProp/CustomDepProp/Properties/Settings.Designer.cs b/Chapter_25/CustomDepProp/CustomDepProp/Properties/Settings.Designer.cs new file mode 100644 index 0000000..215f9cf --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace CustomDepProp.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Chapter_25/CustomDepProp/CustomDepProp/Properties/Settings.settings b/Chapter_25/CustomDepProp/CustomDepProp/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Chapter_25/CustomDepProp/CustomDepProp/ShowNumberControl.xaml b/Chapter_25/CustomDepProp/CustomDepProp/ShowNumberControl.xaml new file mode 100644 index 0000000..f5e7400 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/ShowNumberControl.xaml @@ -0,0 +1,12 @@ + + + + diff --git a/Chapter_25/CustomDepProp/CustomDepProp/ShowNumberControl.xaml.cs b/Chapter_25/CustomDepProp/CustomDepProp/ShowNumberControl.xaml.cs new file mode 100644 index 0000000..cd925e2 --- /dev/null +++ b/Chapter_25/CustomDepProp/CustomDepProp/ShowNumberControl.xaml.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace CustomDepProp +{ + /// + /// Interaction logic for ShowNumberControl.xaml + /// + public partial class ShowNumberControl : UserControl + { + public ShowNumberControl() + { + InitializeComponent(); + } + // A normal, everyday .NET property. + //private int _currNumber = 0; + //public int CurrentNumber + //{ + // get => _currNumber; + // set + // { + // _currNumber = value; + // numberDisplay.Content = _currNumber.ToString(); + // } + //} + + + public int CurrentNumber + { + get => (int)GetValue(CurrentNumberProperty); + set => SetValue(CurrentNumberProperty, value); + } + + // Using a DependencyProperty as the backing store for CurrentNumber. This enables animation, styling, binding, etc... + public static readonly DependencyProperty CurrentNumberProperty = + DependencyProperty.Register("CurrentNumber", + typeof(int), + typeof(ShowNumberControl), + new UIPropertyMetadata(100, new PropertyChangedCallback(CurrentNumberChanged)), + new ValidateValueCallback(ValidateCurrentNumber)); + + public static bool ValidateCurrentNumber(object value) + { + // Just a simple business rule. Value must be between 0 and 500. + return Convert.ToInt32(value) >= 0 && Convert.ToInt32(value) <= 500; + } + private static void CurrentNumberChanged( + DependencyObject depObj, DependencyPropertyChangedEventArgs args) + { + // Cast the DependencyObject into ShowNumberControl. + ShowNumberControl c = (ShowNumberControl)depObj; + + // Get the Label control in the ShowNumberControl. + Label theLabel = c.numberDisplay; + + // Set the Label with the new value. + theLabel.Content = args.NewValue.ToString(); + } + + } +} diff --git a/Chapter_25/MyWordPad/MyWordPad.sln b/Chapter_25/MyWordPad/MyWordPad.sln new file mode 100644 index 0000000..5c65309 --- /dev/null +++ b/Chapter_25/MyWordPad/MyWordPad.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyWordPad", "MyWordPad\MyWordPad.csproj", "{5E226946-A591-463B-A5E3-43F93A951D92}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5E226946-A591-463B-A5E3-43F93A951D92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5E226946-A591-463B-A5E3-43F93A951D92}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5E226946-A591-463B-A5E3-43F93A951D92}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5E226946-A591-463B-A5E3-43F93A951D92}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_25/MyWordPad/MyWordPad/App.config b/Chapter_25/MyWordPad/MyWordPad/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_25/MyWordPad/MyWordPad/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_25/MyWordPad/MyWordPad/App.xaml b/Chapter_25/MyWordPad/MyWordPad/App.xaml new file mode 100644 index 0000000..35df025 --- /dev/null +++ b/Chapter_25/MyWordPad/MyWordPad/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/Chapter_25/MyWordPad/MyWordPad/App.xaml.cs b/Chapter_25/MyWordPad/MyWordPad/App.xaml.cs new file mode 100644 index 0000000..2f98fbe --- /dev/null +++ b/Chapter_25/MyWordPad/MyWordPad/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace MyWordPad +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/Chapter_25/MyWordPad/MyWordPad/MainWindow.xaml b/Chapter_25/MyWordPad/MyWordPad/MainWindow.xaml new file mode 100644 index 0000000..66cd558 --- /dev/null +++ b/Chapter_25/MyWordPad/MyWordPad/MainWindow.xaml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Chapter_25/PanelMarkup/SimpleScrollViewer.xaml b/Chapter_25/PanelMarkup/SimpleScrollViewer.xaml new file mode 100644 index 0000000..49b8847 --- /dev/null +++ b/Chapter_25/PanelMarkup/SimpleScrollViewer.xaml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + + diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/MainWindow.xaml.cs b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/MainWindow.xaml.cs new file mode 100644 index 0000000..470ee99 --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/MainWindow.xaml.cs @@ -0,0 +1,111 @@ +using System.IO; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Ink; +using System.Windows.Media; +using AutoLotDAL.Repos; + +namespace WpfControlsAndAPIs +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : Window + { + public MainWindow() + { + InitializeComponent(); + this.MyInkCanvas.EditingMode = InkCanvasEditingMode.Ink; + this.inkRadio.IsChecked = true; + this.comboColors.SelectedIndex = 0; + SetBindings(); + ConfigureGrid(); + } + + private void RadioButtonClicked(object sender, RoutedEventArgs e) + { + switch ((sender as RadioButton)?.Content.ToString()) + { + // These strings must be the same as the Content values for each + // RadioButton. + case "Ink Mode!": + this.MyInkCanvas.EditingMode = InkCanvasEditingMode.Ink; + break; + + case "Erase Mode!": + this.MyInkCanvas.EditingMode = InkCanvasEditingMode.EraseByStroke; + break; + + case "Select Mode!": + this.MyInkCanvas.EditingMode = InkCanvasEditingMode.Select; + break; + } + } + + private void ColorChanged(object sender, SelectionChangedEventArgs e) + { + // Get the selected value in the combo box. + //string colorToUse = (comboColors.SelectedItem as ComboBoxItem)?.Content.ToString(); + string colorToUse = + (comboColors.SelectedItem as StackPanel)?.Tag.ToString(); + + // Change the color used to render the strokes. + this.MyInkCanvas.DefaultDrawingAttributes.Color = + (Color)ColorConverter.ConvertFromString(colorToUse); + + } + + private void SaveData(object sender, System.Windows.RoutedEventArgs e) + { + // Save all data on the InkCanvas to a local file. + using (FileStream fs = new FileStream("StrokeData.bin", FileMode.Create)) + { + this.MyInkCanvas.Strokes.Save(fs); + fs.Close(); + } + } + + private void LoadData(object sender, System.Windows.RoutedEventArgs e) + { + // Fill StrokeCollection from file. + using (FileStream fs = new FileStream("StrokeData.bin", + FileMode.Open, FileAccess.Read)) + { + StrokeCollection strokes = new StrokeCollection(fs); + this.MyInkCanvas.Strokes = strokes; + } + } + + private void Clear(object sender, System.Windows.RoutedEventArgs e) + { + // Clear all strokes. + this.MyInkCanvas.Strokes.Clear(); + } + + private void SetBindings() + { + // Create a Binding object. + Binding b = new Binding(); + + // Register the converter, source, and path. + b.Converter = new MyDoubleConverter(); + b.Source = this.mySB; + b.Path = new PropertyPath("Value"); + + // Call the SetBinding method on the Label. + this.labelSBThumb.SetBinding(Label.ContentProperty, b); + } + private void ConfigureGrid() + { + using (var repo = new InventoryRepo()) + { + // Build a LINQ query that gets back some data from the Inventory table. + gridInventory.ItemsSource = + repo.GetAll().Select(x => new { x.Id, x.Make, x.Color, x.PetName }); + } + } + + } +} diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/MyDoubleConverter.cs b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/MyDoubleConverter.cs new file mode 100644 index 0000000..8f6a1c1 --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/MyDoubleConverter.cs @@ -0,0 +1,24 @@ +using System; +using System.Windows.Data; + +namespace WpfControlsAndAPIs +{ + public class MyDoubleConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, + System.Globalization.CultureInfo culture) + { + // Convert the double to an int. + double v = (double)value; + return (int)v; + } + + public object ConvertBack(object value, Type targetType, object parameter, + System.Globalization.CultureInfo culture) + { + // You won't worry about "two-way" bindings + // here, so just return the value. + return value; + } + } +} diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/AssemblyInfo.cs b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a69db35 --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/AssemblyInfo.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("WpfControlsAndAPIs")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WpfControlsAndAPIs")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +//In order to begin building localizable applications, set +//CultureYouAreCodingWith in your .csproj file +//inside a . For example, if you are using US english +//in your source files, set the to en-US. Then uncomment +//the NeutralResourceLanguage attribute below. Update the "en-US" in +//the line below to match the UICulture setting in the project file. + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] + + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Resources.Designer.cs b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Resources.Designer.cs new file mode 100644 index 0000000..9d8c6f7 --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WpfControlsAndAPIs.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfControlsAndAPIs.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Resources.resx b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Settings.Designer.cs b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Settings.Designer.cs new file mode 100644 index 0000000..a897889 --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WpfControlsAndAPIs.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Settings.settings b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/WpfControlsAndAPIs.csproj b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/WpfControlsAndAPIs.csproj new file mode 100644 index 0000000..835c803 --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/WpfControlsAndAPIs.csproj @@ -0,0 +1,112 @@ + + + + + Debug + AnyCPU + {333345D3-2142-462E-A886-9FAE9B993CAB} + WinExe + WpfControlsAndAPIs + WpfControlsAndAPIs + v4.7 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + {7e5a8812-c303-4ae0-a6e7-4ac96ec11624} + AutoLotDAL + + + + \ No newline at end of file diff --git a/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/packages.config b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/packages.config new file mode 100644 index 0000000..bb66824 --- /dev/null +++ b/Chapter_25/WpfControlsAndAPIs/WpfControlsAndAPIs/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents.sln b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents.sln new file mode 100644 index 0000000..dbf564a --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfRoutedEvents", "WpfRoutedEvents\WpfRoutedEvents.csproj", "{2F662A28-F3E7-4995-91F9-CD4F7693DB5A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2F662A28-F3E7-4995-91F9-CD4F7693DB5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2F662A28-F3E7-4995-91F9-CD4F7693DB5A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2F662A28-F3E7-4995-91F9-CD4F7693DB5A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2F662A28-F3E7-4995-91F9-CD4F7693DB5A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.config b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.xaml b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.xaml new file mode 100644 index 0000000..9ecc7af --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.xaml.cs b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.xaml.cs new file mode 100644 index 0000000..05c7352 --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace WpfRoutedEvents +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/MainWindow.xaml b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/MainWindow.xaml new file mode 100644 index 0000000..61e9fef --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/MainWindow.xaml @@ -0,0 +1,26 @@ + + + + + + diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/MainWindow.xaml.cs b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/MainWindow.xaml.cs new file mode 100644 index 0000000..8508220 --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/MainWindow.xaml.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace WpfRoutedEvents +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : Window + { + string _mouseActivity = string.Empty; + public MainWindow() + { + InitializeComponent(); + } + public void btnClickMe_Clicked(object sender, RoutedEventArgs e) + { + AddEventInfo(sender, e); + MessageBox.Show(_mouseActivity, "Your Event Info"); + // Clear string for next round. + _mouseActivity = ""; + } + + private void AddEventInfo(object sender, RoutedEventArgs e) + { + _mouseActivity += string.Format( + "{0} sent a {1} event named {2}.\n", sender, + e.RoutedEvent.RoutingStrategy, + e.RoutedEvent.Name); + } + + private void outerEllipse_MouseDown(object sender, MouseButtonEventArgs e) + { + AddEventInfo(sender, e); + } + + private void outerEllipse_PreviewMouseDown(object sender, MouseButtonEventArgs e) + { + AddEventInfo(sender, e); + } + } +} diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/AssemblyInfo.cs b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f4639ac --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/AssemblyInfo.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("WpfRoutedEvents")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WpfRoutedEvents")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +//In order to begin building localizable applications, set +//CultureYouAreCodingWith in your .csproj file +//inside a . For example, if you are using US english +//in your source files, set the to en-US. Then uncomment +//the NeutralResourceLanguage attribute below. Update the "en-US" in +//the line below to match the UICulture setting in the project file. + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] + + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Resources.Designer.cs b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Resources.Designer.cs new file mode 100644 index 0000000..3ace233 --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WpfRoutedEvents.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfRoutedEvents.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Resources.resx b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Settings.Designer.cs b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Settings.Designer.cs new file mode 100644 index 0000000..9b6b61b --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WpfRoutedEvents.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Settings.settings b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/WpfRoutedEvents.csproj b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/WpfRoutedEvents.csproj new file mode 100644 index 0000000..7d0ebdd --- /dev/null +++ b/Chapter_25/WpfRoutedEvents/WpfRoutedEvents/WpfRoutedEvents.csproj @@ -0,0 +1,97 @@ + + + + + Debug + AnyCPU + {2F662A28-F3E7-4995-91F9-CD4F7693DB5A} + WinExe + WpfRoutedEvents + WpfRoutedEvents + v4.7 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + \ No newline at end of file diff --git a/Chapter_26/1.fpage b/Chapter_26/1.fpage new file mode 100644 index 0000000..f9c5478 --- /dev/null +++ b/Chapter_26/1.fpage @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Chapter_26/FunWithTransforms/FunWithTransforms.sln b/Chapter_26/FunWithTransforms/FunWithTransforms.sln new file mode 100644 index 0000000..42bf9a3 --- /dev/null +++ b/Chapter_26/FunWithTransforms/FunWithTransforms.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FunWithTransforms", "FunWithTransforms\FunWithTransforms.csproj", "{84705E6C-E82F-42DA-BEFA-9C006C898289}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {84705E6C-E82F-42DA-BEFA-9C006C898289}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {84705E6C-E82F-42DA-BEFA-9C006C898289}.Debug|Any CPU.Build.0 = Debug|Any CPU + {84705E6C-E82F-42DA-BEFA-9C006C898289}.Release|Any CPU.ActiveCfg = Release|Any CPU + {84705E6C-E82F-42DA-BEFA-9C006C898289}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_26/FunWithTransforms/FunWithTransforms/App.config b/Chapter_26/FunWithTransforms/FunWithTransforms/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_26/FunWithTransforms/FunWithTransforms/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_26/FunWithTransforms/FunWithTransforms/App.xaml b/Chapter_26/FunWithTransforms/FunWithTransforms/App.xaml new file mode 100644 index 0000000..801a5fe --- /dev/null +++ b/Chapter_26/FunWithTransforms/FunWithTransforms/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/Chapter_26/FunWithTransforms/FunWithTransforms/App.xaml.cs b/Chapter_26/FunWithTransforms/FunWithTransforms/App.xaml.cs new file mode 100644 index 0000000..8b9a86a --- /dev/null +++ b/Chapter_26/FunWithTransforms/FunWithTransforms/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace FunWithTransforms +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/Chapter_26/FunWithTransforms/FunWithTransforms/FunWithTransforms.csproj b/Chapter_26/FunWithTransforms/FunWithTransforms/FunWithTransforms.csproj new file mode 100644 index 0000000..828a372 --- /dev/null +++ b/Chapter_26/FunWithTransforms/FunWithTransforms/FunWithTransforms.csproj @@ -0,0 +1,97 @@ + + + + + Debug + AnyCPU + {84705E6C-E82F-42DA-BEFA-9C006C898289} + WinExe + FunWithTransforms + FunWithTransforms + v4.7 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + \ No newline at end of file diff --git a/Chapter_26/FunWithTransforms/FunWithTransforms/MainWindow.xaml b/Chapter_26/FunWithTransforms/FunWithTransforms/MainWindow.xaml new file mode 100644 index 0000000..1519a6b --- /dev/null +++ b/Chapter_26/FunWithTransforms/FunWithTransforms/MainWindow.xaml @@ -0,0 +1,43 @@ + + + + + + + + + + diff --git a/Chapter_27/XamlAnimations/AnimateString.xaml b/Chapter_27/XamlAnimations/AnimateString.xaml new file mode 100644 index 0000000..d495bb1 --- /dev/null +++ b/Chapter_27/XamlAnimations/AnimateString.xaml @@ -0,0 +1,26 @@ + + + + + diff --git a/Chapter_27/XamlAnimations/AnimationStyle.backup b/Chapter_27/XamlAnimations/AnimationStyle.backup new file mode 100644 index 0000000..9a5417b --- /dev/null +++ b/Chapter_27/XamlAnimations/AnimationStyle.backup @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_27/XamlAnimations/AnimationStyle.xaml b/Chapter_27/XamlAnimations/AnimationStyle.xaml new file mode 100644 index 0000000..9a5417b --- /dev/null +++ b/Chapter_27/XamlAnimations/AnimationStyle.xaml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter_27/XamlAnimations/GrowLabelFont.backup b/Chapter_27/XamlAnimations/GrowLabelFont.backup new file mode 100644 index 0000000..db661a5 --- /dev/null +++ b/Chapter_27/XamlAnimations/GrowLabelFont.backup @@ -0,0 +1,21 @@ + + + + + \ No newline at end of file diff --git a/Chapter_27/XamlAnimations/GrowLabelFont.xaml b/Chapter_27/XamlAnimations/GrowLabelFont.xaml new file mode 100644 index 0000000..db661a5 --- /dev/null +++ b/Chapter_27/XamlAnimations/GrowLabelFont.xaml @@ -0,0 +1,21 @@ + + + + + \ No newline at end of file diff --git a/Chapter_28/WpfCommands/WpfCommands.sln b/Chapter_28/WpfCommands/WpfCommands.sln new file mode 100644 index 0000000..066dab2 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfCommands", "WpfCommands\WpfCommands.csproj", "{66137FA7-9862-4AA7-B794-58030A9F59B4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {66137FA7-9862-4AA7-B794-58030A9F59B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {66137FA7-9862-4AA7-B794-58030A9F59B4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {66137FA7-9862-4AA7-B794-58030A9F59B4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {66137FA7-9862-4AA7-B794-58030A9F59B4}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Chapter_28/WpfCommands/WpfCommands/App.config b/Chapter_28/WpfCommands/WpfCommands/App.config new file mode 100644 index 0000000..016d28f --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Chapter_28/WpfCommands/WpfCommands/App.xaml b/Chapter_28/WpfCommands/WpfCommands/App.xaml new file mode 100644 index 0000000..b57df81 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/Chapter_28/WpfCommands/WpfCommands/App.xaml.cs b/Chapter_28/WpfCommands/WpfCommands/App.xaml.cs new file mode 100644 index 0000000..d2e7b25 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace WpfCommands +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/Chapter_28/WpfCommands/WpfCommands/Cmds/AddCarCommand.cs b/Chapter_28/WpfCommands/WpfCommands/Cmds/AddCarCommand.cs new file mode 100644 index 0000000..446dd30 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/Cmds/AddCarCommand.cs @@ -0,0 +1,23 @@ +using System.Collections.ObjectModel; +using System.Linq; +using WpfCommands.Models; + +namespace WpfCommands.Cmds +{ + public class AddCarCommand : CommandBase + { + public override bool CanExecute(object parameter) + { + return parameter != null && parameter is ObservableCollection; + } + + public override void Execute(object parameter) + { + if (parameter is ObservableCollection cars) + { + var maxCount = cars?.Max(x => x.CarId) ?? 0; + cars?.Add(new Inventory { CarId = ++maxCount, Color = "Yellow", Make = "VW", PetName = "Birdie" }); + } + } + } +} \ No newline at end of file diff --git a/Chapter_28/WpfCommands/WpfCommands/Cmds/ChangeColorCommand.cs b/Chapter_28/WpfCommands/WpfCommands/Cmds/ChangeColorCommand.cs new file mode 100644 index 0000000..2b6ac2f --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/Cmds/ChangeColorCommand.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Input; +using WpfCommands.Models; + +namespace WpfCommands.Cmds +{ + public class ChangeColorCommand : CommandBase + { + //public bool CanExecute(object parameter) => (parameter as Inventory) != null; + + //public void Execute(object parameter) + //{ + // ((Inventory)parameter).Color = "Pink"; + //} + + //public event EventHandler CanExecuteChanged + //{ + // add => CommandManager.RequerySuggested += value; + // remove => CommandManager.RequerySuggested -= value; + //} + public override bool CanExecute(object parameter) => (parameter as Inventory) != null; + + public override void Execute(object parameter) + { + ((Inventory)parameter).Color = "Pink"; + } + + + } +} diff --git a/Chapter_28/WpfCommands/WpfCommands/Cmds/CommandBase.cs b/Chapter_28/WpfCommands/WpfCommands/Cmds/CommandBase.cs new file mode 100644 index 0000000..de5b753 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/Cmds/CommandBase.cs @@ -0,0 +1,18 @@ +using System; +using System.Windows.Input; + +namespace WpfCommands.Cmds +{ + public abstract class CommandBase : ICommand + { + public abstract bool CanExecute(object parameter); + + public abstract void Execute(object parameter); + + public event EventHandler CanExecuteChanged + { + add => CommandManager.RequerySuggested += value; + remove => CommandManager.RequerySuggested -= value; + } + } +} diff --git a/Chapter_28/WpfCommands/WpfCommands/Cmds/RelayCommand.cs b/Chapter_28/WpfCommands/WpfCommands/Cmds/RelayCommand.cs new file mode 100644 index 0000000..d29fb05 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/Cmds/RelayCommand.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WpfCommands.Cmds +{ + public class RelayCommand : CommandBase + { + private readonly Action _execute; + private readonly Func _canExecute; + + public RelayCommand() + { + } + + public RelayCommand(Action execute) : this(execute, null) { } + public RelayCommand(Action execute, Func canExecute) + { + _execute = execute ?? throw new ArgumentNullException(nameof(execute)); + _canExecute = canExecute; + } + + public override bool CanExecute(object parameter) + => _canExecute == null || _canExecute(); + public override void Execute(object parameter) { _execute(); } + + } +} diff --git a/Chapter_28/WpfCommands/WpfCommands/Cmds/RelayCommandT.cs b/Chapter_28/WpfCommands/WpfCommands/Cmds/RelayCommandT.cs new file mode 100644 index 0000000..f35ff81 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/Cmds/RelayCommandT.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WpfCommands.Cmds +{ + public class RelayCommand : RelayCommand + { + private readonly Action _execute; + private readonly Func _canExecute; + public RelayCommand(Action execute) : this(execute, null) { } + + public RelayCommand(Action execute, Func canExecute) + { + _execute = execute ?? throw new ArgumentNullException(nameof(execute)); + _canExecute = canExecute; + } + public override bool CanExecute(object parameter) => _canExecute == null || _canExecute((T)parameter); + public override void Execute(object parameter) { _execute((T)parameter); } + + } +} diff --git a/Chapter_28/WpfCommands/WpfCommands/FodyWeavers.xml b/Chapter_28/WpfCommands/WpfCommands/FodyWeavers.xml new file mode 100644 index 0000000..87ff356 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/FodyWeavers.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Chapter_28/WpfCommands/WpfCommands/MainWindow.xaml b/Chapter_28/WpfCommands/WpfCommands/MainWindow.xaml new file mode 100644 index 0000000..5d55c00 --- /dev/null +++ b/Chapter_28/WpfCommands/WpfCommands/MainWindow.xaml @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +