Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 4 > BOOK: Beginning ASP.NET 4 : in C# and VB
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
BOOK: Beginning ASP.NET 4 : in C# and VB
This is the forum to discuss the Wrox book Beginning ASP.NET 4: in C# and VB by Imar Spaanjaars; ISBN: 9780470502211
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning ASP.NET 4 : in C# and VB section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old May 14th, 2013, 04:34 AM
Registered User
Points: 30, Level: 1
Points: 30, Level: 1 Points: 30, Level: 1 Points: 30, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: May 2013
Posts: 7
Thanks: 0
Thanked 0 Times in 0 Posts
Default Ch. 17, Exercise 1, p. 652

Hello,

I have tried re-doing the Theme selection accoording to the suggestion of ex. 1 on p. 652, but the Profile object is not available in App_Code/BasePage.cs. The word "Profile" in line "string preferredTheme = Profile.FavoriteTheme;" is underlined in red and an error of The name 'Profile' does not exist in the current context.

All other Profile values work correctly for me.

My App_Code/BasePage.cs:
Code:
using System;
using System.Web;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;
using System.Web.Profile;

/// <summary>
/// This class is used to check the titles of the pages before they are rendered
/// </summary>
public class BasePage:System.Web.UI.Page
{
    private void Page_PreRender(object sender, EventArgs e)
    {
        if (this.Title == "Untitled Page" || string.IsNullOrEmpty(this.Title) || this.Title == "\n" || this.Title == "\r\n")
        {
            throw new Exception("Page title cannot be \"Untitled Page\" or an empty string.");
        }
    }

    private void Page_PreInit(object sender, EventArgs e)
    {
        //HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
        string preferredTheme = Profile.FavoriteTheme;
        if (preferredTheme!=null) {
            // Page.Theme = preferredTheme.Value;
            Page.Theme = preferredTheme;
        }
    }

    /// <summary>
    /// Adds event handler to the event: check if a page has the TITLE tag set or not, throw an exception if necessary
    /// </summary>
	public BasePage()
	{
        this.PreRender += new EventHandler(Page_PreRender);
        this.PreInit += new EventHandler(Page_PreInit);
	}
}
My MyProfile.aspx.cs:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _MyProfile : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!Page.IsPostBack) {
            FirstName.Text = Profile.FirstName;
            LastName.Text = Profile.LastName;
            DateOfBirth.Text = Profile.DateOfBirth.ToShortDateString();
            Bio.Text = Profile.Bio;
        }
    }
    protected void SaveButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid) {
            
            Profile.FirstName = FirstName.Text;
            Profile.LastName = LastName.Text;
            Profile.DateOfBirth = DateTime.Parse(DateOfBirth.Text);
            Profile.Bio = Bio.Text;
            
            // clear the list of favourite genres and re-save again
            Profile.FavoriteGenres.Clear();
            foreach (ListItem myItem in PreferenceList.Items) {
                if (myItem.Selected) {
                    Profile.FavoriteGenres.Add(Convert.ToInt32(myItem.Value));
                }
            }
        }
    }
    protected void PreferenceList_DataBound(object sender, EventArgs e)
    {
        foreach(ListItem myItem in PreferenceList.Items) {
            int currentValue = Convert.ToInt32(myItem.Value);
            if (Profile.FavoriteGenres.Contains(currentValue)) {
                myItem.Selected = true;
            }
        }
    }
}

My MasterPages/Frontend.master.cs:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MasterPages_Frontend : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) {
            string selectedTheme = Page.Theme;
            //HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
            string preferredTheme = Profile.FavoriteTheme;
            if (preferredTheme!=null) {
                //selectedTheme = preferredTheme.Value;
                selectedTheme = preferredTheme;
            }
            if (!string.IsNullOrEmpty(selectedTheme) && ThemeList.Items.FindByValue(selectedTheme)!=null) {
                ThemeList.Items.FindByValue(selectedTheme).Selected = true;
            }
        }

        switch (Page.Theme.ToLower()) {
            case "darkgrey":
                Menu1.Visible = false;
                TreeView1.Visible = true;
                break;
            default:
                Menu1.Visible = true;
                TreeView1.Visible = false;
                break;
        }
    }
    protected void ThemeList_SelectedIndexChanged1(object sender, EventArgs e)
    {
        //HttpCookie preferredTheme = new HttpCookie("PreferredTheme");
        //preferredTheme.Expires = DateTime.Now.AddMonths(3);
        //preferredTheme.Value = ThemeList.SelectedValue;
        //Response.Cookies.Add(preferredTheme);
        Profile.FavoriteTheme = ThemeList.SelectedValue;
        Response.Redirect(Request.Url.ToString());
    }
    
}
I have the following in web.config / <system.web>:

Code:
 
<!-- Enable anonymous identification -->
    <anonymousIdentification enabled="true" cookieName="PlanetWorxAnonymous"/>
    <!-- Define properties to be kept in a user profile (also stored for anonymous users) -->
    <profile defaultProvider="SqlProvider">
      <properties>
        <add name="FirstName" allowAnonymous="true" />
        <add name="LastName" allowAnonymous="true" />
        <add name="DateOfBirth" type="System.DateTime" allowAnonymous="true" />
        <add name="Bio" allowAnonymous="true" />
        <add name="FavoriteGenres" type="System.Collections.Generic.List`1[System.Int32]" allowAnonymous="true" />
        <add name="FavoriteTheme" allowAnonymous="true" defaultValue="Monochrome" />
      </properties>
    </profile>
My MasterPages/Frontend.master

Code:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Frontend.master.cs" Inherits="MasterPages_Frontend" %>
<!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 runat="server">
    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
    <link href="../Styles/Styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/jquery-1.4.1.min.js" />
        </Scripts>
    </asp:ScriptManager>
        <div id="PageWrapper">
        <div id="Header"><a href="~/" runat="server"></a></div>
        <div id="MenuWrapper">
            <asp:Menu ID="Menu1" runat="server" CssClass="MainMenu" 
                DataSourceID="SiteMapDataSource1" Orientation="Horizontal" 
                StaticEnableDefaultPopOutImage="False">
            </asp:Menu>
            <asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" 
                ShowExpandCollapse="False">
                <LevelStyles>
                    <asp:TreeNodeStyle CssClass="FirstLevelMenuItems" />
                </LevelStyles>
            </asp:TreeView>
            <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" 
                ShowStartingNode="False" />
        </div>
        <div id="MainContent">
            <asp:SiteMapPath ID="SiteMapPath1" runat="server">
            </asp:SiteMapPath><br /><br />
            <asp:ContentPlaceHolder id="cpMainContent" runat="server">
            </asp:ContentPlaceHolder>
        </div>
        <div id="Sidebar">Select a theme<br />
            <asp:DropDownList ID="ThemeList" runat="server" AutoPostBack="true" 
                onselectedindexchanged="ThemeList_SelectedIndexChanged1">
                <asp:ListItem>Monochrome</asp:ListItem>
                <asp:ListItem>DarkGrey</asp:ListItem>
            </asp:DropDownList>
            <br />
            <br />
            <br />
            <Wrox:Banner ID="Banner1" runat="server" DisplayDirection="Vertical" /><br />
            <asp:Label ID="HideBanner" runat="server" Text=""></asp:Label>
        </div>
        <div id="Footer">
            <asp:LoginName ID="LoginName1" runat="server" FormatString="Logged in as {0}" />
            <asp:LoginView ID="LoginView1" runat="server">
                <LoggedInTemplate>
                    (<asp:LoginStatus ID="LoginStatus1" runat="server" />)
                </LoggedInTemplate>
                <RoleGroups>
                    <asp:RoleGroup Roles="Managers">
                        <ContentTemplate>
                            <asp:HyperLink ID="HyperLink1" runat="server" 
                                NavigateUrl="~/Management/Default.aspx">Manage Site</asp:HyperLink> or 
                            <asp:LoginStatus ID="LoginStatus2" runat="server" />
                        </ContentTemplate>
                    </asp:RoleGroup>
                </RoleGroups>
            </asp:LoginView>
        </div>
    </div>
    <asp:ContentPlaceHolder ID="cpClientScript" runat="server">
    </asp:ContentPlaceHolder>
    </form>
</body>
</html>
My MyProfile.aspx:
Code:
<%@ Page Title="My Profile" Language="C#" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="true" CodeFile="MyProfile.aspx.cs" Inherits="_MyProfile" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">

<h1>My Profile</h1>
<p>Ths page allows you to make changes to your personal profile.</p>
    <p>&nbsp;</p>
    
    <table class="style1">
        <tr>
            <td>
                <asp:Label ID="Label1" runat="server" Text="Favorite genres:"></asp:Label>
            </td>
            <td>
                <asp:CheckBoxList ID="PreferenceList" runat="server" 
                    DataSourceID="EntityDataSource1" DataTextField="Name" DataValueField="Id" 
                    ondatabound="PreferenceList_DataBound">
                </asp:CheckBoxList></td>
            <td>
                <asp:EntityDataSource ID="EntityDataSource1" runat="server" 
                    ConnectionString="name=PlanetWroxEntities" 
                    DefaultContainerName="PlanetWroxEntities" EnableFlattening="False" 
                    EntitySetName="Genres" OrderBy="it.Name" Select="it.[Id], it.[Name]">
                </asp:EntityDataSource>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="FirstNameLabel" runat="server" AssociatedControlID="FirstName" 
                    Text="First name:"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                    ControlToValidate="FirstName" Display="Dynamic" 
                    ErrorMessage="Please enter first name."></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="LastNameLabel" runat="server" AssociatedControlID="LastName" 
                    Text="Last name:"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="LastName" runat="server"></asp:TextBox>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                    ControlToValidate="LastName" Display="Dynamic" 
                    ErrorMessage="Please enter last name."></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="DateOfBirthLabel" runat="server" 
                    AssociatedControlID="DateOfBirth" Text="Date of birth:"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="DateOfBirth" runat="server"></asp:TextBox>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
                    ControlToValidate="DateOfBirth" Display="Dynamic" 
                    ErrorMessage="Please enter date of birth. "></asp:RequiredFieldValidator>
                <asp:CompareValidator ID="CompareValidator1" runat="server" 
                    ControlToValidate="DateOfBirth" Display="Dynamic" 
                    ErrorMessage="Please enter a valid date." Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="BioLabel" runat="server" AssociatedControlID="Bio" 
                    Text="Biography:"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="Bio" runat="server" Height="75px" TextMode="MultiLine" 
                    Width="300px"></asp:TextBox>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                <asp:Button ID="SaveButton" runat="server" onclick="SaveButton_Click" 
                    Text="Save profile" />
            </td>
            <td>
                &nbsp;</td>
        </tr>
    </table>

    <br />

    <asp:ChangePassword ID="ChangePassword1" runat="server">
    </asp:ChangePassword>
</asp:Content>
Reply With Quote
  #2 (permalink)  
Old May 14th, 2013, 08:49 AM
Imar's Avatar
Wrox Author
Points: 72,073, Level: 100
Points: 72,073, Level: 100 Points: 72,073, Level: 100 Points: 72,073, Level: 100
Activity: 100%
Activity: 100% Activity: 100% Activity: 100%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,089
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

Hi there,

You may want to cheat a bit and look up the answer for this exercise in Appendix A. Because of the way Profile works (the Profile property is added dynamically to your Web Form classes), it's not directly available in the BasePage. Instead you need to use ProfileCommon like this:

Code:
ProfileCommon myProfile = (ProfileCommon) HttpContext.Current.Profile;
if (!string.IsNullOrEmpty(myProfile.FavoriteTheme))
{
Page.Theme = myProfile.FavoriteTheme;
}
It looks like you mistook Exercise 1 for the full implementation. Exercise 2 explains the ProfileCommon as well, but it looks like you tried to create the full implementation from exercise 1 only.

Hope this helps,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
Reply With Quote
  #3 (permalink)  
Old May 15th, 2013, 05:12 AM
Registered User
Points: 30, Level: 1
Points: 30, Level: 1 Points: 30, Level: 1 Points: 30, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: May 2013
Posts: 7
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Thank you !

I must admit I didn't read the next exercise
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Ch 17 LINQ to SQL sirmilt BOOK: Beginning Microsoft Visual Basic 2008 ISBN: 978-0-470-19134-7 0 May 29th, 2011 05:37 PM
CH 17 - Assemblies equintana71 BOOK: Professional C# 2008 ISBN: 978-0-470-19137-8 1 May 17th, 2011 09:20 PM
Exercise 4, P76 - solution on p. 652 Jim.Clauson BOOK: Beginning PHP 6, Apache, MySQL 6 Web Development ISBN: 9780470391143 5 March 4th, 2011 01:06 PM
Exercise 4, P76 - solution on p. 652 Jim.Clauson BOOK: Beginning PHP 6, Apache, MySQL 6 Web Development ISBN: 9780470391143 0 October 15th, 2009 08:30 PM



All times are GMT -4. The time now is 07:34 AM.


Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.