420 likes | 436 Views
Learn C# coding for building a shopping cart system in ASP.NET, explore classes, methods, and code-behind model. Understand how C# classes interact and manage data sets, enhancing user experience.
E N D
COMP3241E-Business Technologies Richard Henson University of Worcester November2014
Week 6: Coding a C# Shopping Cart (!) • By the end of this session you will be able to: • explain the structure of a .net environment application including controls, assemblies, code-behind file(s), design file(s), web.config • apply asp.net principles to the creation of a shopping system • Explain how the shopping cart dataset interfaces with the products table and update smoothly when user changes their mind
C# and “classes” • “C” has been around since 1972 • C++ is the object-orientated (OO) version, invented in 1983… • C# is even more OO • All versions of C are compiled • i.e. code runs as machine code or assembly language; source code must be compiled beforehand…
Classes • A bit like entities in systems analysis… • can have “properties” • equivalent to attributes… • Have to be carefully coded… • could be “public” or “private” • properties are variables • should really be “private” • code snippets (methods) – public
Properties & Objects • Need to “instantiate” a newly-defined class by giving it “objects” (hence OBJECT-ORIENTATED)… • e.g. if a class is defined with colour as a property • then a single value “red” would be enough to create an “object” of that class
C# Constructors & Methods • Sounds terrible… • actually just the different [public] code segments associated with a class • A constructor uses property(ies) to define or “construct” a member/object of that class • Methods can include any programming structures and do stuff using property values
“Partial” Classes and Methods • Partial Classes • used to describe a situation where different parts of a class are defined in different places • Partial Methods • within a partial class • must return a “void” value • implicitly “private”
C# classes & Code Behind When .aspx page is requested and it renders its markup code to a browser… ASP.NET generates & compiles the “classes” that perform the tasks required to run the page
“Classes” and the code behind model the .net framework also: sets up the JIT run-time environment converts source code to “intermediate language” (IL)
“Classes” and the code behind model Combination of different code What runs is not just the code that was created for the .aspx page plus its associated “code behind” (!)
Generating a class, as Code Behind When a .aspx page runs, it has already combined: the server-side elements in the page e.g. toolbox controls the event-handling code written as “code behind” The class or classes that the compiler creates depends on whether the page uses the single-file model or the code-behind model no need to pre-compile such pages into assemblies!
Generating and Running the Page’s “class” Code .NET framework dynamically compiles & runs .aspx pages the first time user requests them: IF…any changes are subsequently made either to the page or resources the page depends on THEN… the page is automatically recompiled .NET also supports precompilation of a Web site: to enhance performance to perform error checking to support site deployment
Single-File Pages When the page is compiled: the compilergenerates then compiles… EITHER a new class that derives from the base Page class OR a custom base class defined with the Inherits attribute of the @ Page directive.
Single-File Pages Example: IF… a new ASP.NET Web page named SamplePage1.aspx is created in application root directory THEN… a new class named ASP.SamplePage1_aspx will be derived from the Page class
Single-File Pages IF that single-file is inside an application subfolder subfolder name is used as part of the generated class & contains: declarations for the controls in the .aspx page the event handlers and other custom code
After Page generation… Generated class… compiled into an assembly assembly loaded into the application domain Page class… instantiated executed renders output to the browser…
Effect of Page modifications IF a page changes & this would affect the generated class… e.g. adding controls modifying code THEN compiled class code is invalidated a new class is generated
Using C# classes with “event-driven” controls EXAMPLE (an “add to cart” button): protected void DataList1_ItemCommand (objectsource, DataListCommandEventArgs e) { if (e.CommandName == "AddToCart") { // Add code here to add the item to the shopping cart. // Use the value of e.Item.ItemIndex to retrieve the data // item in the control. } }
Use of Multiple Scripting languages in a Page General rule… DON’T! use of multiple compilers wastes system resources If you must: HTML <SCRIPT> tag and its LANGUAGE added within the .aspx code usually placed after the <HEAD></HEAD> tags RUNAT attributes (where code is executed) optional Syntax: <SCRIPT LANGUAGE=ScriptingLanguage RUNAT=Server> script… </SCRIPT> similar to embedded client code
Keep it simple! Multiple languages not even recommended for different pages in the same application!!! makes the ASP.net engine load multiple scripting engines needs more processing which piece of script should be sent to which scripting engine! reduces the responsiveness and scalability of the application
Potential Scripting Problems in a RAD Environment like Vis Studio… Correct scripting language always needs to be defined at the start of the page dynamic “new” pages provide a range of options Inserted controls: can be inserted in the wrong place… can themselves become muddled (start again?) may already contain HTML code or (if database) SQL code
Potential Problems of Scripting in the VSt Environment… (cont.) Embedded server script code may depend on a link to a database link needs to be functioning correctly… database field types must correspond with script equivalents If the database tables/fields change significantly, the script must accommodate the field changes… roll out changes carefully may be easier to recreate control or whole page…
Use of Comments in aspx files Apostrophe for VBScript ‘This is a VBScript comment Three slashes for C# /// <summary> /// The “myClass” class represents an arbitrary class /// </summary> An excellent C# resource: http://www.softsteel.co.uk/tutorials/cSharp/contents.html
More about Objects In general terms… chunks of server script code that will together provide web functionality using RAD tools, added to a dynamic HTML page “at the click of a mouse button” available in a number of languages asp, asp.net php, cold fusion Several objects usually used together to create a useful web application e.g. data capture form and sending data to database presentation of data from a database
“Components” and “Objects” Very similar and easily confused… Object part of the library of files available to the whole application Component a number of objects a mini-application in its own right any instance of a component must be explicitly created before it can be used
Using COM in aspx files COM (later COM+) components… popular with developers… provided consistent, reusable functionality easy to maintain and share could be modified or enhanced without affecting the rest of the application Microsoft therefore reluctant to give up a good thing and encouraged using COM+ with .net http://msdn2.microsoft.com/en-us/library/bb735856.aspx
ASP.net and directing user input The “HttpRequest” class includes… event handling controls web controls Web controls can also be pre-written and pre-compiled as assembles… Really useful in designing pages to handle user input
How a click on the product can update the cart • Essential that the cart dataset is available with each product page • otherwise, product and quantity data can’t be added to the cart! • Advice: use “split screen” to see the code as well as the screen design • then able to check the code that corresponds with the cart, and its appropriateness for page display • if there is a mismatch, you can’t expect the shopping cart to be updated…
Web Controls and ASP.net Shopping Carts • Web controls…object classes used by asp.net to render parts of a page • similar to HTML “forms” • extra advantage of being reusable • An .aspx web page may use a hierarchical structure of defined web controls • making a combination of code behind and assembly-based controls easily manageable
Some Typical Web Controls that used with a HTML form • button listbox • checkbox radiobutton • checkboxlistradiobuttonlist • dropdownlist textbox • imagebutton label
Web Control syntax (1) • Textbox & contents must be held within a HTML form • i.e. between <form> and </form> • Opening tag: <asp:textbox> • various properties of the control follow… • e.g. display of text box • displayed text contents • runat=“server” • Closing tag: /> or </asp:textbox>
Dropdown box control & “nesting” syntax • Drop Down List box & contents • again within a HTML form • Opening tag: <asp:dropdownlist>… • properties of the control individually defined e.g. properties of drop down list box, and displayed text contents runat=“server” (essential) Controlname ID = “unique name” (also essential) • further nested control needed for each item in the drop down list…
Dropdown box control & “nesting” syntax (cont…) 3. Each item defined as: <asp:listitem> …. properties of listitem…. </asp:listitem> properties should include: text = “” (what is displayed) value = “” (what is passed on) 4. Closing tag: </asp:dropdownlist> or />
Dropdown box control & “nesting” syntax (3) • Typical code for whole structure: • Note the embedding of one control, listitem within another, dropdownbox <form> <asp:dropdownlist ID = “selected” runat = “server”> <listitem> text = “true” value = “1”/> <listitem> text = “false” value = “0”/> /> </form>
Summary of cart logic • Up to three different labels for product ID: • product table value • parameter value • cart value • This can be very confusing, but the cart won’t work without the right associations • all cart control parameters must be correctly entered… otherwise… • no data or the wrong data will be added • incorrect parameters will be invoked causing .net errors
WebXelCart Assembly • Collection of compiled versions of many coded web controls: • Cart • AddFromDB • WriteToDB • etc.. • Visual Studio can “open” an assembly to reveal defined properties of each control
WebXelCart:Cart control • Like any other asp.net web control… • stored as executable code • Visual Studio makes it available to any .net pages in the project… • assuming parent assembly is… • held in the relevant /App_Data folder • and added to “References” • Can be called as <control name>… < /> • like any other web control • parameters have to be set accordingly
Passing the Product ID Parameter Product Page Product ID value sent as e.g. “ProdID” Remote DB Add from DB scripts Shopping Cart fields extracted from remote database
Updating Cart Values • When the customer clicks on a hyperlink/button associated with a product: • a “line record” is created on the cart for that product (based on the parameter passed) • quantity is set at the default value of 1 • Cart Totals are then automatically calculated • If customer clicks on a second product… • further cart record is created • all cart totals recalculated
Cart Display Page • Cart.aspx consists of a HTML table with scripts added to insert cart values in the right places on the table • Pages should be designed so cart.aspx is available at all times, so the customer can readily remind themselves what they have clicked on… • Cart.aspx should also include: • update product quantity (e.g. buy 2 instead of 1) • remove a cart line altogether (erase cart record)
Rest of Shopping System • Registration for new customer/Login for existing customer (personal data) • Online Invoice • Payment Page (sensitive personal data) • Thank you page • Goodbye and come again page • Email updates on order progress