Hiding pos comments from anonymous
I am trying to hide the Post your comments section on the ShowArticleNews.aspx page from Anonymous, not logged in viewers.
I tried putting this section in a loginView control but had problems with the codebehind file not being able to find various controls
e.g.
panComments.Visible = article.CommentsEnabled;
so I tried adding a line above this:
Panel panComments = (Panel)LoginView2.FindControl("panComments");
I did this for all the controls that had this problem but I now get the error:
Object reference not set to an instance of an object.
Line 88: panComments.Visible = article.CommentsEnabled;
I've included the code for the page and behind file
Any advice or change of approach would be greatly appriciated.
Thanks in advance
Jez
ShowArticleNews page:
<asp:loginview ID="LoginView2" runat="server">
<rolegroups>
<asp:rolegroup Roles="Administrators">
</asp:rolegroup>
</rolegroups>
<anonymoustemplate>
To post a comment please sign in or sign up to HealthInvestor
</anonymoustemplate>
<loggedintemplate>
<div class="sectiontitle">
<asp:loginname ID="LoginName1" runat="server" />
How would you rate this article?</div>
<asp:DropDownList runat="server" ID="ddlRatings">
<asp:ListItem Value="1" Text="1 point" />
<asp:ListItem Value="2" Text="2 Points" />
<asp:ListItem Value="3" Text="3 Points" />
<asp:ListItem Value="4" Text="4 Points" />
<asp:ListItem Value="5" Text="5 Points" Selected="true" />
</asp:DropDownList>
<asp:Button runat="server" ID="btnRate" Text="Rate" OnClick="btnRate_Click" CausesValidation="false" />
<asp:Literal runat="server" ID="lblUserRating" Visible="False"
Text="Your rated this article {0} points(s). HealthInvestor appriciates your feedback for your feedback." />
<p></p>
<asp:Panel runat="server" ID="panComments">
<p></p>
<div class="sectionsubtitle">Post your comment</div>
<asp:DetailsView id="dvwComment" runat="server" AutoGenerateInsertButton="True" AutoGenerateEditButton="true" AutoGenerateRows="False" DataSourceID="objCurrComment" DefaultMode="Insert" OnItemInserted="dvwComment_ItemInserted" OnItemCommand="dvwComment_ItemCommand" DataKeyNames="ID" OnItemUpdated="dvwComment_ItemUpdated" OnItemCreated="dvwComment_ItemCreated">
<FieldHeaderStyle Width="80px" />
<Fields>
<asp:BoundField DataField="ID" HeaderText="ID:" ReadOnly="True" InsertVisible="False" />
<asp:BoundField DataField="AddedDate" HeaderText="AddedDate:" InsertVisible="False" ReadOnly="True"/>
<asp:BoundField DataField="AddedByIP" HeaderText="UserIP:" ReadOnly="True" InsertVisible="False" />
<asp:TemplateField HeaderText="Name:">
<ItemTemplate>
<asp:Label SkinID="midYellow" ID="lblAddedBy" runat="server" Text='<%# Eval("AddedBy") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtAddedBy" runat="server" Text='<%# Bind("AddedBy") %>' MaxLength="256" Width="100%"></asp:TextBox>
<asp:RequiredFieldValidator ID="valRequireAddedBy" runat="server" ControlToValidate="txtAddedBy" SetFocusOnError="true"
Text="Your name is required." ToolTip="Your name is required." Display="Dynamic"></asp:RequiredFieldValidator>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="E-mail:">
<ItemTemplate>
<asp:HyperLink ID="lnkAddedByEmail" runat="server" Text='<%# Eval("AddedByEmail") %>'
NavigateUrl='<%# "mailto:" + Eval("AddedByEmail") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtAddedByEmail" runat="server" Text='<%# Bind("AddedByEmail") %>' MaxLength="256" Width="100%"></asp:TextBox>
<asp:RequiredFieldValidator ID="valRequireAddedByEmail" runat="server" ControlToValidate="txtAddedByEmail" SetFocusOnError="true"
Text="Your e-mail is required." ToolTip="Your e-name is required." Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" ID="valEmailPattern" Display="Dynamic" SetFocusOnError="true"
ControlToValidate="txtAddedByEmail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
Text="The e-mail is not well-formed." ToolTip="The e-mail is not well-formed." />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment:">
<ItemTemplate>
<asp:Label ID="lblBody" runat="server" Text='<%# Eval("Body") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBody" runat="server" Text='<%# Bind("Body") %>' TextMode="MultiLine" Rows="5" Width="100%"></asp:TextBox>
<asp:RequiredFieldValidator ID="valRequireBody" runat="server" ControlToValidate="txtBody" SetFocusOnError="true"
Text="The comment text is required." ToolTip="The comment text is required." Display="Dynamic"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
<asp:ObjectDataSource ID="objCurrComment" runat="server" InsertMethod="InsertComment"
SelectMethod="GetCommentByID" TypeName="MB.HealthInvestor.BLL.Articles.Comment"
UpdateMethod="UpdateComment">
<UpdateParameters>
<asp:Parameter Name="id" Type="Int32" />
<asp:Parameter Name="body" Type="String" />
</UpdateParameters>
<SelectParameters>
<asp:ControlParameter ControlID="dlstComments" Name="commentID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="addedBy" Type="String" />
<asp:Parameter Name="addedByEmail" Type="String" />
<asp:QueryStringParameter Name="articleID" QueryStringField="ID" Type="Int32" />
<asp:Parameter Name="body" Type="String" />
</InsertParameters>
</asp:ObjectDataSource>
</asp:Panel>
</loggedintemplate>
</asp:loginview>
Code behind:
public partial class ShowArticleNews : BasePage
{
private bool _userCanEdit = false;
protected bool UserCanEdit
{
get { return _userCanEdit; }
set { _userCanEdit = value; }
}
int _articleID = 0;
protected void Page_Init(object sender, EventArgs e)
{
UserCanEdit = (this.User.Identity.IsAuthenticated &&
(this.User.IsInRole("Administrators") || this.User.IsInRole("Editors")));
}
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.Request.QueryString["ID"]))
throw new ApplicationException("Missing parameter on the querystring.");
else
_articleID = int.Parse(this.Request.QueryString["ID"]);
if (!this.IsPostBack)
{
// try to load the article with the specified ID, and raise an exception
// if it doesn't exist
Article article = Article.GetArticleByID(_articleID);
if (article == null)
throw new ApplicationException("No article was found for the specified ID.");
// Check whether the article is published (approved, released and not yet expired).
// If not, continue only if the current user is an Administrator or an Editor
if (!article.Published)
{
if (!this.UserCanEdit)
{
throw new SecurityException(@"What are you trying to do???
You're not allowed to do view this article!");
}
}
// if the article has the OnlyForMembers = true, and the current user is anonymous,
// redirect to the login page
if (article.OnlyForMembers && !this.User.Identity.IsAuthenticated)
this.RequestLogin();
article.IncrementViewCount();
// if we get here, display all article's data on the page
this.Title = string.Format(this.Title, article.Title);
lblTitle.Text = article.Title;
lblNotApproved.Visible = !article.Approved;
lblAddedBy.Text = article.AddedBy;
lblReleaseDate.Text = article.ReleaseDate.ToShortDateString();
lblCategory.Text = article.CategoryTitle;
lblLocation.Visible = (article.Location.Length > 0);
if (lblLocation.Visible)
lblLocation.Text = string.Format(lblLocation.Text, article.Location);
lblRating.Text = string.Format(lblRating.Text, article.Votes);
ratDisplay.Value = article.AverageRating;
ratDisplay.Visible = (article.Votes > 0);
lblViews.Text = string.Format(lblViews.Text, article.ViewCount);
lblAbstract.Text = article.Abstract;
lblBody.Text = article.Body;
Panel panComments = (Panel)LoginView2.FindControl("panComments");
panComments.Visible = article.CommentsEnabled;
panEditArticle.Visible = this.UserCanEdit;
btnApprove.Visible = !article.Approved;
lnkEditArticle.NavigateUrl = string.Format(lnkEditArticle.NavigateUrl, _articleID);
// hide the rating box controls if the current user has already voted for this article
int userRating = GetUserRating();
if (userRating > 0)
ShowUserRating(userRating);
}
}
protected void btnRate_Click(object sender, EventArgs e)
{
// check whether the user has already rated this article
int userRating = GetUserRating();
if (userRating > 0)
{
ShowUserRating(userRating);
}
else
{
// rate the article, then create a cookie to remember this user's rating
// For findcontrol due to loginView placement
DropDownList ddlRatings = (DropDownList)LoginView2.FindControl("ddlRatings") ;
userRating = ddlRatings.SelectedIndex + 1;
Article.RateArticle(_articleID, userRating);
ShowUserRating(userRating);
HttpCookie cookie = new HttpCookie(
"Rating_Article" + _articleID.ToString(), userRating.ToString());
cookie.Expires = DateTime.Now.AddDays(Globals.Settings.Articles.Rat ingLockInterval);
this.Response.Cookies.Add(cookie);
}
}
protected void ShowUserRating(int rating)
{
// For findcontrol due to loginView placement
DropDownList ddlRatings = (DropDownList)LoginView2.FindControl("ddlRatings") ;
Literal lblUserRating = (Literal)LoginView2.FindControl("lblUserRating");
Button btnRate = (Button)LoginView2.FindControl("btnRate");
lblUserRating.Text = string.Format(lblUserRating.Text, rating);
ddlRatings.Visible = false;
btnRate.Visible = false;
lblUserRating.Visible = true;
}
protected int GetUserRating()
{
int rating = 0;
HttpCookie cookie = this.Request.Cookies["Rating_Article" + _articleID.ToString()];
if (cookie != null)
rating = int.Parse(cookie.Value);
return rating;
}
protected void dlstComments_SelectedIndexChanged(object sender, EventArgs e)
{
// For findcontrol due to loginView placement
DetailsView dvwComment = (DetailsView)LoginView2.FindControl("dvwComment");
dvwComment.ChangeMode(DetailsViewMode.Edit);
}
protected void dvwComment_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Cancel")
{
dlstComments.SelectedIndex = -1;
dlstComments.DataBind();
}
}
protected void dvwComment_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
dlstComments.SelectedIndex = -1;
dlstComments.DataBind();
}
protected void dvwComment_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
dlstComments.SelectedIndex = -1;
dlstComments.DataBind();
}
protected void btnApprove_Click(object sender, ImageClickEventArgs e)
{
Article.ApproveArticle(_articleID);
btnApprove.Visible = false;
}
protected void btnDelete_Click(object sender, ImageClickEventArgs e)
{
Article.DeleteArticle(_articleID);
this.Response.Redirect("BrowseArticles.aspx", false);
}
protected void dlstComments_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int commentID = int.Parse(e.CommandArgument.ToString());
Comment.DeleteComment(commentID);
// For findcontrol due to loginView placement
DetailsView dvwComment = (DetailsView)LoginView2.FindControl("dvwComment");
dvwComment.ChangeMode(DetailsViewMode.Insert);
dlstComments.SelectedIndex = -1;
dlstComments.DataBind();
}
}
protected void dvwComment_ItemCreated(object sender, EventArgs e)
{
// when in Insert Mode, pre-fill the username and e-mail fields with the
// current user's information, if she is authenticated
// For findcontrol due to loginView placement
DetailsView dvwComment = (DetailsView)LoginView2.FindControl("dvwComment");
if (dvwComment.CurrentMode == DetailsViewMode.Insert &&
this.User.Identity.IsAuthenticated)
{
MembershipUser user = Membership.GetUser();
(dvwComment.FindControl("txtAddedBy") as TextBox).Text = user.UserName;
(dvwComment.FindControl("txtAddedByEmail") as TextBox).Text = user.Email;
}
}
}
}
End of code
|