?? votingcontrol.cs
字號:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ASPNET.StarterKit.Communities;
namespace ASPNET.StarterKit.Communities {
/// <summary>
/// The Vote control is allows for users to vote on topics. The results are stored in
/// a SQL Server table and a HTML graph is used to display the selections/percentages.
///
/// Adopted from Rob Howard's (rhoward@microsoft.com) Voting Control.
/// </summary>
public class VotingControl : WebControl, System.Web.UI.INamingContainer {
// Internal members
//
RadioButtonList radioButtonList;
PollDetails polldetails;
System.Drawing.Color barBackColor = System.Drawing.Color.LightGray;
System.Drawing.Color barForeColor = System.Drawing.Color.Blue;
Style questionStyle;
Style itemStyle;
Style buttonStyle;
string itemClass = "VoteItemClass";
string questionClass = "VoteQuestionClass";
string buttonClass = "VoteButtonClass";
string tableClass = "VoteTableClass";
string resultClass = "VoteResultClass";
string buttonText = "Vote";
int section_ID;
string userName;
protected override void OnLoad(EventArgs e) {
//InitializeControl();
}
private void InitializeControl() {
// Try to get user and page information if available
if (HttpContext.Current.Items["UserInfo"]!=null) {
UserInfo userInfo = (UserInfo)HttpContext.Current.Items["UserInfo"];
userName=userInfo.Username;
} else {
userName=String.Empty;
}
if (HttpContext.Current.Items["SectionInfo"]!=null) {
SectionInfo objSectionInfo =(SectionInfo)HttpContext.Current.Items["SectionInfo"];
section_ID = objSectionInfo.ID;
} else {
section_ID=0;
}
// Get Poll Details
//
polldetails = GetPollDetails();
}
/// <summary>
/// Used to indicate whether multiple votes are allowed per user. Default is false.
/// </summary>
public bool AllowMultipleVote=false;
public string ItemClass
{
get
{
return itemClass;
}
set
{
itemClass = value;
}
}
public string QuestionClass
{
get
{
return questionClass;
}
set
{
questionClass = value;
}
}
public string ButtonClass
{
get
{
return buttonClass;
}
set
{
buttonClass = value;
}
}
public string TableClass
{
get
{
return tableClass;
}
set
{
tableClass = value;
}
}
public string ResultClass
{
get
{
return resultClass;
}
set
{
resultClass = value;
}
}
/// <summary>
/// Controls the height of the control
/// </summary>
public override Unit Height
{
get {
return base.Height;
}
set {
base.Height = value;
}
}
/// <summary>
/// Controls the width of the control
/// </summary>
public override Unit Width {
get {
return base.Width;
}
set {
base.Width = value;
}
}
/// <summary>
/// Used to control the text on the button. Default is 'Vote'
/// </summary>
public String ButtonText {
get {
return buttonText;
}
set {
buttonText = value;
}
}
/// <summary>
/// Sets the style for the question
/// </summary>
public Style QuestionStyle {
get {
if (questionStyle == null)
questionStyle = new Style();
return questionStyle;
}
}
/// <summary>
/// Sets the general style for displayed items
/// </summary>
public Style ItemStyle {
get {
if (itemStyle == null)
itemStyle = new Style();
return itemStyle;
}
}
/// <summary>
/// Sets the style for the button used in voting
/// </summary>
public Style ButtonStyle {
get {
if (buttonStyle == null)
buttonStyle = new Style();
return buttonStyle;
}
}
/// <summary>
/// Override control collection and return base collection
/// </summary>
public override ControlCollection Controls {
get {
EnsureChildControls();
return base.Controls;
}
}
/// <summary>
/// Controls the back ground color of the rendered bar(s).
/// </summary>
public System.Drawing.Color BarBackColor {
get {
return barBackColor;
}
set {
barBackColor = value;
}
}
/// <summary>
/// Controls the foreground color of the rendered bar(s).
/// </summary>
public System.Drawing.Color BarForeColor {
get {
return barForeColor;
}
set {
barForeColor = value;
}
}
protected override void CreateChildControls() {
InitializeControl();
// There may not be a poll available for this page
if (polldetails!=null) {
if (CheckHasVoted())
HasVoted();
else
HasNotVoted();
}
}
protected void HasNotVoted() {
// Member variables
//
Table t = new Table();
t.CssClass = tableClass;
t.Width = System.Web.UI.WebControls.Unit.Percentage(100);
TableRow questionRow = new TableRow();
TableRow choicesRow = new TableRow();
TableRow buttonRow = new TableRow();
TableCell questionCell = new TableCell();
TableCell choicesCell = new TableCell();
TableCell buttonCell = new TableCell();
Button button = new Button();
radioButtonList = new RadioButtonList();
// Wire up the button click event
//
button.Click += new EventHandler(VoteButtonClick);
// Format Question
//
questionCell.Text = polldetails.Question;
questionRow.ControlStyle.CopyFrom(questionStyle);
questionCell.CssClass = questionClass;
// Insert question cell and row into table
//
questionRow.Cells.Add(questionCell);
t.Rows.Add(questionRow);
// Format Radio Button
//
radioButtonList.ControlStyle.CopyFrom(itemStyle);
radioButtonList.CssClass = itemClass;
// Populate the radioButtonList
//
foreach (ChoiceInfo choice in polldetails.Choices.OrderedChoices)
radioButtonList.Items.Add(new ListItem(choice.Choice,choice.PollChoice_ID.ToString()));
// Insert the radio button into the cell
//
choicesCell.Controls.Add(radioButtonList);
// Add row/cell to table
//
choicesRow.Cells.Add(choicesCell);
t.Rows.Add(choicesRow);
// Format Button
//
button.Text = buttonText;
button.ControlStyle.CopyFrom(buttonStyle);
button.CssClass = buttonClass;
// Insert button into cell
//
buttonCell.Controls.Add(button);
// Add button cell/row to table
//
buttonRow.Cells.Add(buttonCell);
t.Rows.Add(buttonRow);
// Add table to the controls collection
//
this.Controls.Add(t);
this.Controls.Add(new LiteralControl("<p>"));
}
protected void VoteButtonClick(Object sender, EventArgs e) {
HttpContext.Current.Trace.Write("VoteButtonClick");
if (radioButtonList.SelectedIndex!=-1) {
int pollChoice_ID=Int32.Parse(radioButtonList.SelectedItem.Value);
// Cast vote and save in DB
VotingUtility.CreatePollResult(userName,pollChoice_ID);
// Make cookie aware that this user has voted for this poll.
AddPollToCookie();
this.Controls.Clear();
HasVoted();
}
}
protected void HasVoted() {
// Member Variables
//
Table t = new Table();
TableRow questionRow = new TableRow();
TableRow resultsRow = new TableRow();
TableRow footerRow = new TableRow();
TableCell questionCell = new TableCell();
TableCell resultsCell = new TableCell();
TableCell footer = new TableCell();
// Format the table
//
//t.BorderWidth = 0;
t.CssClass = tableClass;
t.Width = System.Web.UI.WebControls.Unit.Percentage(100);
// Question
//
questionCell.Text = polldetails.Question;
questionCell.ColumnSpan = 3;
questionCell.ControlStyle.CopyFrom(questionStyle);
questionCell.CssClass = questionClass;
// Add the question cell/row to the table
//
questionRow.Cells.Add(questionCell);
t.Rows.Add(questionRow);
if (polldetails.DisplayResultsToPublic) {
Hashtable pollresults = VotingUtility.GetPollResults(polldetails.Poll_ID);
// Calculate the sum
//
int sum=0;
foreach (int key in pollresults.Keys)
sum = sum + (int)pollresults[key];
// Calculate percentage
//
foreach (int key in pollresults.Keys) {
// Internal variables/instances
//
double d = 0;
TableRow row = new TableRow();
TableCell progressCell = new TableCell();
TableCell percentageCell = new TableCell();
TableCell choiceCell = new TableCell();
ProgressBar bar = new ProgressBar();
// Percentage for this poll value
//
d = ((double)((int)pollresults[key]) / (double)sum) * 100;
// Display the choice in cell and format
//
choiceCell.Text = ((ChoiceInfo)polldetails.Choices[key]).Choice + ": ";
choiceCell.VerticalAlign = VerticalAlign.Top;
choiceCell.HorizontalAlign = HorizontalAlign.Right;
choiceCell.ControlStyle.CopyFrom(itemStyle);
choiceCell.CssClass = itemClass;
choiceCell.Wrap = false;
// Set properties for each bar
//
bar.PercentageOfProgress = (int)d;
bar.BackColor = this.BarBackColor;
bar.ForeColor = this.BarForeColor;
// Add the bar and set properties of the cell
//
progressCell.Controls.Add(bar);
progressCell.HorizontalAlign = HorizontalAlign.Right;
progressCell.VerticalAlign = VerticalAlign.Top;
progressCell.Width = 100;
// Special case 0
//
if ((double.IsNaN(d)) || (0 == d))
percentageCell.Text = "(0%)";
else
percentageCell.Text = "(" + d.ToString("##.#") + "%)";
// Format percentage cell
//
percentageCell.HorizontalAlign = HorizontalAlign.Left;
percentageCell.VerticalAlign = VerticalAlign.Top;
percentageCell.ControlStyle.CopyFrom(itemStyle);
percentageCell.CssClass = itemClass;
// Add the cells to the row
//
row.Cells.Add(choiceCell);
row.Cells.Add(progressCell);
row.Cells.Add(percentageCell);
// Add the row to the table
//
t.Rows.Add(row);
}
}
// What you voted for
//
resultsCell.ColumnSpan = 3;
resultsCell.HorizontalAlign = HorizontalAlign.Right;
resultsCell.ControlStyle.CopyFrom(itemStyle);
resultsCell.CssClass = resultClass;
// Get Users data from the database
// TODO: Rethink cookie design to store Anonymous user's values.
if (userName!=String.Empty && userName!="Anonymous") {
resultsCell.Text = "Your vote: " + VotingUtility.GetUsersChoice(polldetails.Poll_ID,userName).Choice;
} else {
resultsCell.Text = "You have already voted for this poll.";
}
// Add results cell/row to table
//
resultsRow.Cells.Add(resultsCell);
t.Rows.Add(resultsRow);
this.Controls.Add(t);
this.Controls.Add(new LiteralControl("<p>"));
}
// Cache poll details in the ViewState.
private PollDetails GetPollDetails() {
PollDetails pollDetails;
// Maintain the same Poll_ID accross postbacks
if (ViewState["Poll_ID"]==null) {
pollDetails = VotingUtility.GetPollForWebBox(CommunityGlobals.CommunityID,section_ID,userName);
if (pollDetails!=null)
ViewState["Poll_ID"]=pollDetails.Poll_ID;
} else {
pollDetails = VotingUtility.GetPollForWebBox((int)ViewState["Poll_ID"]);
}
return pollDetails;
}
// Checks if the user has already voted.
private bool CheckHasVoted() {
HttpCookie cookie = GetCookie();
bool hasVoted=false;
// First, check cookie
if (cookie.Value.Length>0) {
string[] polls=cookie.Value.Split('|');
foreach (string poll in polls) {
if (poll==polldetails.Poll_ID.ToString()) {
hasVoted=true;
break;
}
}
}
// Check DB
if (!hasVoted && userName.Length>0) {
ChoiceInfo choice = VotingUtility.GetUsersChoice(polldetails.Poll_ID,userName);
if (choice.PollChoice_ID!=0) {
hasVoted=true;
}
}
return hasVoted;
}
// Adds this poll to the "voted" cookie.
private void AddPollToCookie() {
HttpCookie cookie = GetCookie();
if (cookie.Value.Length==0)
cookie.Value=polldetails.Poll_ID.ToString();
else
cookie.Value=cookie.Value+"|" + polldetails.Poll_ID.ToString();
HttpContext.Current.Response.Cookies.Add(cookie);
}
// Retrieves the cookie and creates a new one if it doesn't exist.
private HttpCookie GetCookie() {
string cookieName="AspNetCommunityVoting_" + userName;
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
if (cookie==null) {
HttpContext.Current.Response.Cookies.Add(new HttpCookie(cookieName,String.Empty));
cookie = HttpContext.Current.Response.Cookies[cookieName];
cookie.Expires=DateTime.MaxValue;
}
return cookie;
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -