Работа №2. ASP.NET страницы, темы, таблицы

Факультет компьютерных систем и сетей

Кафедра информатики

Отчет

по лабораторным работам

по предмету Избранные Главы Информатики

Выполнил:

ст. гр. 052004

Зезюлькин Д. Ю.

Преподаватель:

Тычко Д.Н.

Минск 2012

Работа №1: Разработка архитектуры проекта и дизайна сайта

Цель работы.

Планирование архитектуры веб-проекта, изучение основ HTML и CSS.

Постановка задачи.

Необходимо выбрать для реализации один из предлагаемых веб-проектов. Для выбранного проекта продумать и реализовать:

1. Общую архитектуру.

2. Компоненты бизнес-логики и слоя доступа к данным (50%).

3. Общую схему сайта (какие страницы планируются и как будет осуществляться навигация между страницами).

4. Макет сайта (макет подразумевает выбор раскладки (Layout) страниц, цветовых решений, шрифтов и т.п.). Необходимо предъявить 2-3 страницы (HTML+CSS), иллюстрирующие макет.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="e_Shop.Site"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>e-Shop</title>

<asp:ContentPlaceHolder ID="HeadTagContentPlaceHolder" runat="server">

</asp:ContentPlaceHolder>

</head>

<body>

<form id="MainForm" runat="server">

<div id="header">

<div class="user">

<asp:MultiView ID="UserView" runat="server" ActiveViewIndex="0">

<asp:View runat="server">

<asp:TextBox ID="LoginTextBox" runat="server"></asp:TextBox>

<asp:TextBox ID="PasswordTextBox" runat="server" TextMode="Password" AutoPostBack="true"></asp:TextBox>

</asp:View>

<asp:View runat="server">

Добро пожаловать, <asp:Label ID="UserNameLabel" runat="server"></asp:Label>.

<asp:LinkButton runat="server" Text="Выйти" OnClick="LogoutButtonClick"/>

</asp:View>

</asp:MultiView>

</div>

<ul class="menu">

<li class="home"><a href="./default.aspx" title="Главная">Главная</a></li>

<li class="catalog"><a href="./catalog.aspx" title="Каталог">Каталог</a></li>

<li class="about"><a href="./about.aspx" title="О нас">О нас</a></li>

</ul>

<asp:ContentPlaceHolder ID="SearchContentPlaceHolder" runat="server">

</asp:ContentPlaceHolder>

</div>

<div id="content">

<div id="leftPan">

<asp:ContentPlaceHolder ID="leftPanelContentPlaceHolder" runat="server">

</asp:ContentPlaceHolder>

</div>

<div id="middlePan">

<asp:ContentPlaceHolder ID="middlePanelContentPlaceHolder" runat="server">

</asp:ContentPlaceHolder>

</div>

<div id="rightPan">

<asp:ContentPlaceHolder ID="rightPanelContentPlaceHolder" runat="server">

</asp:ContentPlaceHolder>

</div>

<div class="clear"></div>

</div>

<div id="footer">

<p>Copyright &copy; Untitled Company.</p>

</div>

</form>

</body>

</html>

Работа №2. ASP.NET страницы, темы, таблицы

Цель работы.

Ознакомление с основными элементами управления ASP.NET.

Постановка задачи.

Необходимо создать набор ASP.NET страниц сайта и связать компоненты страниц со слоем бизнес-логики веб-проекта (на момент защиты лабораторной работы должно быть готово не менее 70% от общего числа планируемых страниц). При создании страниц обязательным является использование эталонных страниц, тем, проверочных элементов управления, табличных элементов управления. Страницы должны демонстрировать возможности сохранения состояния и кэширования.

Catalog.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Catalog.aspx.cs" Inherits="e_Shop.Catalog" StylesheetTheme="DefaulTheme" %>

<%@ Register TagPrefix="ajaxToolkit" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>

<%@ Register TagPrefix="My" TagName="CategoriesMenu" Src="CategoriesMenu.ascx" %>

<asp:Content ContentPlaceHolderID="HeadTagContentPlaceHolder" runat="server">

</asp:Content>

<asp:Content ContentPlaceHolderID="SearchContentPlaceHolder" runat="server">

<div class="SearchContainer">

Поиск: <asp:TextBox ID="SearchTextBox" runat="server" AutoPostBack="true" CssClass="TextBox"></asp:TextBox>

</div>

<div class="BasketWrapper">

<asp:LinkButton ID="HiddenButton" runat="server" CssClass="modal"/>

<asp:ScriptManager ID="asm" runat="server" />

<asp:Panel ID="ModalPanel" runat="server" CssClass="BasketView">

<asp:Button ID="OKButton" runat="server" Text="x"/>

<asp:GridView runat="server" ID="BasketGridView" AutoGenerateColumns="false" EmptyDataText="There is nothing in your shopping cart." GridLines="None" Width="600px" CellPadding="5" ShowFooter="true" DataKeyNames="ID" OnRowDataBound="BasketRowDataBound" OnRowCommand="BasketRowCommand" BorderColor="#535352">

<HeaderStyle HorizontalAlign="Left" ForeColor="#FFFFFF" />

<FooterStyle HorizontalAlign="Right" ForeColor="#FFFFFF" />

<Columns>

<asp:TemplateField HeaderText="Name" ItemStyle-Width="300px">

<ItemTemplate>

<asp:Label runat="server" Text='<%# Eval("Product.Name") %>' />

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Quantity" ItemStyle-Width="100px">

<ItemTemplate>

<asp:Label runat="server" Text='<%# Eval("UnitsQuantitty") %>'></asp:Label><br />

<asp:LinkButton runat="server" Text="+" CommandName="Add" CommandArgument='<%# Eval("ID") %>' Font-Underline="false"></asp:LinkButton>

<asp:LinkButton runat="server" Text="-" CommandName="Remove" CommandArgument='<%# Eval("ID") %>' Font-Underline="false"></asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField="UnitPrice" HeaderText="Price" DataFormatString="{0:F2}" ItemStyle-Width="100px"/>

<asp:TemplateField HeaderText="Total" ItemStyle-Width="100px">

<ItemTemplate>

<asp:Label runat="server" Text='<%# ((decimal)Eval("UnitPrice") * (short)Eval("UnitsQuantitty")).ToString("0.00") + "$" %>'/>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

<br />

<asp:LinkButton runat="server" Text="Оформить заказ" OnClick="RegisterOrderButtonClick" />

</asp:Panel>

<ajaxToolkit:ModalPopupExtender ID="mpe" runat="server"

TargetControlID="HiddenButton" PopupControlID="ModalPanel">

</ajaxToolkit:ModalPopupExtender>

В <asp:LinkButton ID="BasketButton" runat="server" Text="корзине" OnClick="BasketButtonClick"/>:

<asp:Label runat="server" ID="BasketProductsCount" Text="0"/>

</div>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="leftPanelContentPlaceHolder" runat="server">

<asp:RadioButtonList runat="server" ID="CategoriesMenu" OnSelectedIndexChanged="CategoriesMenuItemSelected" AutoPostBack="true" CssClass="CategoriesMenu">

</asp:RadioButtonList>

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="middlePanelContentPlaceHolder" runat="server">

<asp:Repeater runat="server" ID="ProductsView" OnItemCommand="OrderButtonClick">

<ItemTemplate>

<div class="Product">

<div class="ProductImage"><img src="./Images/<%# DataBinder.Eval (Container.DataItem, "ImageURL") %>" alt="<%# DataBinder.Eval (Container.DataItem, "Name") %>" width="119" height="123" border="0" /></div>

<h3><%# DataBinder.Eval (Container.DataItem, "Name") %></h3>

<div class="Description">

<p><span>Страна производства:</span> <%# DataBinder.Eval (Container.DataItem, "Country.Name") %>.<br /></p>

<p><span>Производитель:</span> <%# DataBinder.Eval (Container.DataItem, "Manufacturer.Name") %><br /></p>

<p><span>Описание товара:</span> <br/><%# DataBinder.Eval (Container.DataItem, "Description") %></p>

<p><span>В наличии:</span> <%# DataBinder.Eval (Container.DataItem, "Quantity") %> единиц.</p>

<p><span>Стоимость:</span> <%# DataBinder.Eval (Container.DataItem, "Price") %>$.</p>

<asp:ImageButton ID="ImageButton1" runat="server" SkinID="OrderButtonSkin" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID") %>'> </asp:ImageButton>

</div>

</div>

</ItemTemplate>

</asp:Repeater>

</asp:Content>

<asp:Content ID="Content4" ContentPlaceHolderID="rightPanelContentPlaceHolder" runat="server">

</asp:Content>

Catalog.cs:

public partial class Catalog : System.Web.UI.Page

{

protected List<Product> Basket = new List<Product>();

protected List<OrderInfo> BasketOrderInfo = null;

protected void Page_Load(object sender, EventArgs e)

{

var SavedBasket = Session["Basket"] as List<Product>;

if (SavedBasket != null)

{

Basket = SavedBasket;

UpdateBasketProductsCountView();

}

var SavedBasketOrderInfo = Session["BasketOrderInfo"] as List<OrderInfo>;

if (SavedBasketOrderInfo != null)

BasketOrderInfo = SavedBasketOrderInfo;

CategoriesMenu.DataSource = new BusinessLogicComponent().ReadCategories();

CategoriesMenu.DataTextField = "Name";

CategoriesMenu.DataValueField = "ID";

if (CategoriesMenu.Items.Count != (CategoriesMenu.DataSource as List<Category>).Count)

CategoriesMenu.DataBind();

if (SearchTextBox.Text != "")

{

ProductsView.DataSource = new BusinessLogicComponent().FindBy(new Dictionary<string, string>() { { "Name", SearchTextBox.Text.Trim() } });

ProductsView.DataBind();

}

}

protected void CategoriesMenuItemSelected(object sender, EventArgs e)

{

if (CategoriesMenu.SelectedIndex < 0)

return;

var SelectedCategory = (CategoriesMenu.DataSource as List<Category>)[CategoriesMenu.SelectedIndex];

ProductsView.DataSource = new BusinessLogicComponent().FindBy(new Dictionary<string, string>() { { "Category", SelectedCategory.Name } });

ProductsView.DataBind();

SearchTextBox.Text = "";

}

protected void OrderButtonClick(Object Sender, RepeaterCommandEventArgs e)

{

var NewProduct = new ProductsAcces().Read(new Guid((string)e.CommandArgument));

Basket.Add(NewProduct);

if(BasketOrderInfo != null)

BasketOrderInfo.Add(new BusinessLogicComponent().AddToOrder(NewProduct));

UpdateBasketProductsCountView();

}

private void UpdateBasketProductsCountView()

{

BasketProductsCount.Text = Basket.Count.ToString();

if ((Basket.Count % 10 == 0) || (Basket.Count % 10 >= 5) || (Basket.Count / 10 == 1))

BasketProductsCount.Text += " товаров.";

else if (Basket.Count % 10 == 1)

BasketProductsCount.Text += " товар.";

else

BasketProductsCount.Text += " товара.";

}

protected void BasketButtonClick(object sender, EventArgs e)

{

mpe.Show();

if(BasketOrderInfo == null)

BasketOrderInfo = new BusinessLogicComponent().CreateBasket(Basket, (Guid)Membership.GetUser().ProviderUserKey);

BasketGridView.DataSource = BasketOrderInfo;

BasketGridView.DataBind();

}

protected void RegisterOrderButtonClick(object sender, EventArgs e)

{

new BusinessLogicComponent().RegisterOrder(BasketOrderInfo, (Guid)Membership.GetUser().ProviderUserKey);

}

protected void BasketRowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.Footer)

{

decimal Totally = 0;

foreach (var O in BasketOrderInfo)

Totally += O.UnitPrice * O.UnitsQuantitty;

e.Row.Cells[3].Text = "Total: " + Totally.ToString("0.00$");

}

}

protected void BasketRowCommand(object sender, GridViewCommandEventArgs e)

{

var OrderInfoID = new Guid(e.CommandArgument as string);

var Info = BasketOrderInfo.Find(x => x.ID == OrderInfoID);

if (e.CommandName == "Remove")

{

Info.UnitsQuantitty--;

if (Info.UnitsQuantitty == 0)

{

BasketOrderInfo.Remove(Info);

Basket.Remove(Info.Product);

UpdateBasketProductsCountView();

}

}

else if (e.CommandName == "Add")

{

Info.UnitsQuantitty++;

}

}

protected void Page_Unload(object sender, EventArgs e)

{

Session.Add("Basket", Basket);

Session.Add("BasketOrderInfo", BasketOrderInfo);

}

}

BusinessLogic.cs:

public class BusinessLogicComponent

{

public List<Category> ReadCategories()

{

var Categories = new CategoryAcces();

return Categories.ReadAll();

}

public Product ReadProduct(string ID)

{

return new ProductsAcces().Read(new Guid(ID));

}

public bool CreateProduct(string Name, string CategoryName, string Description, string CountryName, string Price, string Quantity, string ImageURL, string ManufacturerName)

{

var NewCountry = new CountryAcces().ReadByName(CountryName);

if (NewCountry == null)

{

NewCountry = new Country() { Name = CountryName };

new CountryAcces().Create(NewCountry);

}

var NewManufacturer = new ManufacturerAcces().ReadByName(ManufacturerName);

if (NewManufacturer == null)

{

NewManufacturer = new Manufacturer() { ID = Guid.NewGuid(), Name = ManufacturerName };

new ManufacturerAcces().Create(NewManufacturer);

}

var NewProduct = Product.CreateProduct(Guid.NewGuid(),

new CategoryAcces().ReadByName(CategoryName).ID,

NewCountry.ID, NewManufacturer.ID, Name,

Int32.Parse(Quantity), decimal.Parse(Price), ImageURL);

NewProduct.Description = Description;

return new ProductsAcces().Create(NewProduct);

}

public bool UpdateProduct(string ID, string Name, int CategoryID, string Description, short CountryID, string Price, string Quantity, string ImageURL, Guid ManufacturerID)

{

var UpdatedProduct = new ProductsAcces().Read(new Guid(ID));

UpdatedProduct.Name = Name;

UpdatedProduct.CategoryID = (short)CategoryID;

UpdatedProduct.Description = Description;

UpdatedProduct.CountryID = CountryID;

UpdatedProduct.Price = decimal.Parse(Price);

UpdatedProduct.Quantity = Int32.Parse(Quantity);

UpdatedProduct.ImageURL = ImageURL;

UpdatedProduct.ManufacturerID = ManufacturerID;

return new ProductsAcces().Update(UpdatedProduct);

}

public List<Product> FindBy(Dictionary<string, string> SearchParams)

{

string Query = "SELECT VALUE A FROM Product AS A WHERE";

foreach (var Parameter in SearchParams)

{

switch (Parameter.Key)

{

case "Name":

Query += " A.Name LIKE('%" + Parameter.Value + "%') AND";

break;

case "Decription":

Query += " A.Description LIKE('%" + Parameter.Value + "%') AND";

break;

case "Country":

Query += " A.Country LIKE('%" + Parameter.Value + "%') AND";

break;

case "Category":

var CategoryID= new CategoryAcces().ReadByName(Parameter.Value).ID;

Query += " A.CategoryID = " + CategoryID + " AND";

break;

}

}

Query = Query.Substring(0, Query.Count() - 3) + ";";

return new ProductsAcces().ReadByQuery(Query);

}

public List<OrderInfo> CreateBasket(List<Product> Products, Guid ClientID)

{

var Basket = new List<OrderInfo>();

foreach (var P in Products)

{

Basket.Add(new OrderInfo() { ID = Guid.NewGuid(), ProductID = P.ID, UnitPrice = P.Price, UnitsQuantitty = 1, Product = P});

}

return Basket;

}

public OrderInfo AddToOrder(Product NewProduct)

{

return new OrderInfo() { ID = Guid.NewGuid(), ProductID = NewProduct.ID, UnitPrice = NewProduct.Price, UnitsQuantitty = 1, Product = NewProduct };

}

public void RegisterOrder(List<OrderInfo> Basket, Guid ClientID)

{

var NewOrder = Order.CreateOrder(Guid.NewGuid(), DateTime.Now, 0, "Name", "Adress", "Phone", "Mail");

NewOrder.ClientID = ClientID;

new OrderAcces().Create(NewOrder);

foreach (var Good in Basket)

{

Good.Product = null;

Good.OrderID = NewOrder.ID;

new OrderInfoAcces().Create(Good);

}

}

}


Наши рекомендации