0

我看过很多关于这个 ASP.NET 错误的帖子,但我无法弄清楚它如何应用于我的代码。

该页面在我的开发机器上加载没有任何错误。我只在我的生产机器上得到错误。

[Exception: An item with the same key has already been added.]
bli_main.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\bli_main.master.cs:149
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Control.LoadRecursive() +190
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3064

它说错误的根源在第 149 行,这是我的 Page_Load 函数的右括号所在的行。

这是给出错误的页面的完整源代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Net;
using System.Configuration;

public partial class bli_main : System.Web.UI.MasterPage
{

public static string connectionString = ConfigurationSettings.AppSettings["connectionString"];

string sql;

//poll variables
List<string> poll_ids = new List<string>();
List<string> poll_long_descriptions = new List<string>();
List<string> poll_short_descriptions = new List<string>();
List<List<string>> questions = new List<List<string>>();
List<List<int>> questionTypes = new List<List<int>>();
List<List<int>> questionIDs = new List<List<int>>();
List<List<string>> responses = new List<List<string>>();

Dictionary<string, List<string>> d_questions = new Dictionary<string, List<string>>();
Dictionary<string, List<int>> d_questionTypes = new Dictionary<string, List<int>>();
Dictionary<string, List<int>> d_questionIDs = new Dictionary<string, List<int>>();
Dictionary<string, List<string>> d_responses = new Dictionary<string, List<string>>();


protected void Page_Load(object sender, EventArgs e)
{
    MySqlConnection connector = new MySqlConnection(connectionString);
    MySqlCommand command;
    MySqlDataReader reader;

    TableRow columnsRow = new TableRow();
    Table1.Rows.Add(columnsRow);
    columnsRow.VerticalAlign = VerticalAlign.Top;

    connector.Open();

    //pull table columns from database
    sql = "SELECT * FROM column_table WHERE column_page_key = @page";
    command = new MySqlCommand(sql, connector);
    command.Parameters.AddWithValue("@page", pageNumber.Value);
    command.CommandTimeout = 30000;
    reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            TableCell c = new TableCell();
            columnsRow.Cells.Add(c);
            c.BorderWidth = 1;
            c.ID = "column_" + reader["column_id"].ToString();
            if (reader["column_type_key"].ToString().Equals("1"))
                c.Width = 600;
            if (reader["column_type_key"].ToString().Equals("2"))
                c.Width = 250;
        }
    }
    catch (Exception ex)
    {
        reader.Close();
        connector.Close();
        throw new Exception(ex.Message);
    }
    finally
    {
        reader.Close();
        connector.Close();
    }

    //for each column, pull all widgets and load them in, and make an add-widget button
    foreach (TableCell c in columnsRow.Cells)
    {
        string column_id = (c.ID.Split('_'))[1];
        sql = "SELECT * FROM widget_instance_table, widget_instance_content_table "
            + "WHERE widget_instance_column_key=@column AND widget_instance_id=widget_instance_content_widget_instance_key";
        connector.Open();
        command = new MySqlCommand(sql, connector);
        command.Parameters.AddWithValue("@column", column_id);
        reader = command.ExecuteReader();

        try
        {
            //for each widget in the column
            while (reader.Read())
            {
                Table t = new Table();
                t.BorderWidth = 1;
                c.Controls.Add(t);
                TableCell cc;

                string widgetType = reader["widget_instance_content_type_key"].ToString();

                //if it's an article widget
                if (widgetType.Equals("7")) buildArticleWidget(t, reader["widget_instance_content_content_key"].ToString());

                //if it's a tweet widget
                else if (widgetType.Equals("13")) buildTweetWidget(t);

                //if it's a poll widget
                else if (widgetType.Equals("12")) buildPollWidget(t, reader["widget_instance_id"].ToString());

                //if it's a testimonial widget
                else if (widgetType.Equals("4")) buildTestimonialWidget(t, reader["widget_instance_id"].ToString());

                //if it's a standard content widget
                else if (widgetType.Equals("1")) buildStandardContentWidget(t, reader["widget_instance_id"].ToString());

                //otherwise
                else
                {
                    t = new Table();
                    t.BorderWidth = 1;
                    TableRow r = new TableRow();
                    cc = new TableCell();
                    c.Controls.Add(t);
                    t.Rows.Add(r);
                    r.Cells.Add(cc);
                    cc.Text = "Other widget type goes Here";
                }
            }
        }
        catch (Exception ex)
        {
            reader.Close();
            connector.Close();
            throw new Exception(ex.Message);
        }
        finally
        {
            reader.Close();
            connector.Close();
        }
    }

}


protected void buildTestimonialWidget(Table t, string widget_id)
{
    TableRow r;
    TableCell c;

    t.BorderWidth = 1;
    r = new TableRow();
    c = new TableCell();
    t.Rows.Add(r);
    r.Cells.Add(c);
    c.Text = "Testimonial " + widget_id + " goes here.";

    MySqlConnection dataConn = new MySqlConnection(); ;
    dataConn.ConnectionString = connectionString;
    dataConn.Open();

    //get widget configuration info from database
    string sql = "SELECT * from content_table, widget_instance_content_table "
               + "WHERE widget_instance_content_content_key = cont_id "
               + "AND widget_instance_content_widget_instance_key = @widget_id";

    MySqlCommand dataCmd = new MySqlCommand(sql, dataConn);
    dataCmd.Parameters.AddWithValue("@widget_id", widget_id);
    MySqlDataReader dataReader = dataCmd.ExecuteReader();

    string article_title = "";
    string article_content = "";

    try
    {
        if (dataReader.Read())
        {
            article_title = dataReader["cont_desc"].ToString();
            article_content = dataReader["cont_content_1"].ToString();
        }
    }
    catch (Exception ex)
    {
        dataReader.Close();
        dataConn.Close();
        throw new Exception(ex.Message);
    }
    finally
    {
        dataReader.Close();
        dataConn.Close();
    }
    r = new TableRow();
    t.Rows.Add(r);

    c = new TableCell();
    r.Cells.Add(c);

    c.Text = article_title;

    r = new TableRow();
    t.Rows.Add(r);

    c = new TableCell();
    r.Cells.Add(c);

    c.Text = article_content;
    c.Text = HttpUtility.HtmlDecode(c.Text);
    Regex.Replace(c.Text, "<.*?>", string.Empty);


}

protected void buildStandardContentWidget(Table t, string widget_id)
{
    TableRow r;
    TableCell c;

    t.BorderWidth = 1;
    r = new TableRow();
    c = new TableCell();
    t.Rows.Add(r);
    r.Cells.Add(c);
    c.Text = "Standard Content " + widget_id + " goes here.";

    MySqlConnection dataConn = new MySqlConnection(); ;
    dataConn.ConnectionString = connectionString;
    dataConn.Open();

    //get widget configuration info from database
    string sql = "SELECT * from content_table, widget_instance_content_table "
               + "WHERE widget_instance_content_content_key = cont_id "
               + "AND widget_instance_content_widget_instance_key = @widget_id";

    MySqlCommand dataCmd = new MySqlCommand(sql, dataConn);
    dataCmd.Parameters.AddWithValue("@widget_id", widget_id);
    MySqlDataReader dataReader = dataCmd.ExecuteReader();

    string article_title = "";
    string article_content = "";

    try
    {
        if (dataReader.Read())
        {
            article_title = dataReader["cont_desc"].ToString();
            article_content = dataReader["cont_content_1"].ToString();
        }
    }
    catch (Exception ex)
    {
        dataReader.Close();
        dataConn.Close();
        throw new Exception(ex.Message);
    }
    finally
    {
        dataReader.Close();
        dataConn.Close();
    }
    r = new TableRow();
    t.Rows.Add(r);

    c = new TableCell();
    r.Cells.Add(c);

    c.Text = article_title;

    r = new TableRow();
    t.Rows.Add(r);

    c = new TableCell();
    r.Cells.Add(c);

    c.Text = article_content;
    c.Text = HttpUtility.HtmlDecode(c.Text);
    Regex.Replace(c.Text, "<.*?>", string.Empty);


}

protected void buildPollWidget(Table t, string widget_id)
{

    MySqlConnection dataConn;
    MySqlCommand dataCmd;
    MySqlDataReader dataReader;

    //get the poll key of the poll from the widget instance table
    dataConn = new MySqlConnection();
    dataConn.ConnectionString = connectionString;
    dataConn.Open();
    sql = "SELECT widget_instance_content_content_key from widget_instance_content_table where widget_instance_content_widget_instance_key=@widget_id";
    dataCmd = new MySqlCommand(sql, dataConn);
    dataCmd.Parameters.AddWithValue("@widget_id", widget_id);
    dataReader = dataCmd.ExecuteReader();

    string poll;
    try
    {
        dataReader.Read();
        poll = dataReader[0].ToString();
    }
    catch (Exception ex)
    {
        dataReader.Close();
        dataConn.Close();
        throw new Exception(ex.Message);
    }
    finally
    {
        dataReader.Close();
        dataConn.Close();
    }

    //get the long and short descriptions of the poll
    //get the elements of the poll from the element table
    dataConn = new MySqlConnection();
    dataConn.ConnectionString = connectionString;
    dataConn.Open();
    sql = "SELECT * FROM poll_table WHERE poll_id=@poll";
    dataCmd = new MySqlCommand(sql, dataConn);
    dataCmd.Parameters.AddWithValue("@poll", poll);
    dataReader = dataCmd.ExecuteReader();

    string poll_long_desc;
    string poll_short_desc;
    try
    {
        dataReader.Read();
        poll_long_desc = dataReader["poll_long_desc"].ToString();
        poll_short_desc = dataReader["poll_short_desc"].ToString();
    }
    catch (Exception ex)
    {
        dataReader.Close();
        dataConn.Close();
        throw new Exception(ex.Message);
    }
    finally
    {
        dataReader.Close();
        dataConn.Close();
    }

    //get the elements of the poll from the element table
    dataConn = new MySqlConnection(); ;
    dataConn.ConnectionString = connectionString;
    dataConn.Open();
    sql = "SELECT * FROM poll_element_table WHERE poll_table_key=@poll";
    dataCmd = new MySqlCommand(sql, dataConn);
    dataCmd.Parameters.AddWithValue("@poll", poll);
    dataReader = dataCmd.ExecuteReader();

    List<string> qs = new List<string>();
    List<int> qtypes = new List<int>();
    List<int> qids = new List<int>();
    List<string> ans = new List<string>();

    try
    {
        while (dataReader.Read())
        {
            qs.Add(dataReader["poll_element_question"].ToString());
            qtypes.Add(Int32.Parse(dataReader["poll_element_type_key"].ToString()));
            qids.Add(Int32.Parse(dataReader["poll_element_id"].ToString()));
            ans.Add("");
        }
    }
    catch (Exception ex)
    {
        dataReader.Close();
        dataConn.Close();
        throw new Exception(ex.Message);
    }
    finally
    {
        dataReader.Close();
        dataConn.Close();
    }

    questions.Add(qs);
    questionTypes.Add(qtypes);
    questionIDs.Add(qids);
    responses.Add(ans);

    d_questions.Add(widget_id, qs);
    d_questionTypes.Add(widget_id, qtypes);
    d_questionIDs.Add(widget_id, qids);
    d_responses.Add(widget_id, ans);

    TableRow r;
    TableCell c;
    Button b;
    //for each poll

    //display poll descriptions
    r = new TableRow();
    r.CssClass = "bodysan";
    t.Rows.Add(r);
    c = new TableCell();
    c.ColumnSpan = 2;
    c.CssClass = "bodysan";
    r.Cells.Add(c);
    c.Text = poll_short_desc;
    r = new TableRow();
    t.Rows.Add(r);
    c = new TableCell();
    c.CssClass = "bodysan";
    c.ColumnSpan = 2;
    r.Cells.Add(c);
    c.Text = poll_long_desc;

    //display the questions and response fields
    for (int j = 0; j < d_questions[widget_id].Count; j++)
    {
        r = new TableRow();
        r.CssClass = "bodysan";
        t.Rows.Add(r);
        c = new TableCell();
        c.CssClass = "bodysan";
        r.Cells.Add(c);
        c = new TableCell();
        c.CssClass = "bodysan";
        r.Cells.Add(c);
        c.Text = d_questions[widget_id][j];
        //c.Text = questions[0][j];
        r = new TableRow();
        r.CssClass = "bodysan";
        t.Rows.Add(r);
        int type = d_questionTypes[widget_id][j];
        c = new TableCell();
        c.CssClass = "bodysan";
        r.Cells.Add(c);
        r.Cells.Add(makeResponseCell(type, Int32.Parse(widget_id), j));
    }

    r = new TableRow();
    r.CssClass = "bodysan";
    t.Rows.Add(r);
    c = new TableCell();
    c.CssClass = "bodysan";
    r.Cells.Add(c);
    b = new Button();
    b.CssClass = "bodysan";
    c.Controls.Add(b);
    b.Text = "Submit Poll";
    b.ID = "submit_" + widget_id + "_poll";
    b.Click += new EventHandler(this.submit);
}



//stores responses in database.
public void submit(Object sender, EventArgs e)
{
    bool valid = true;

    //get the poll ID.
    Button b = (Button)sender;
    string poll = b.ID.Split('_')[1];
    //for each repsonse in this poll

    for (int i = 0; i < d_responses[poll].Count; i++)
    {
        Table tb = (Table)b.Parent.Parent.Parent;
        TableCell c = tb.Rows[2 * i + 3].Cells[1];
        int type = d_questionTypes[poll][i];
        string text = "";
        if (type == 1)
        {
            //throw new Exception("i=" + i + ", cellControls=" + c.Controls.Count + ", cellText=" + c.Text);
            TextBox t = (TextBox)c.Controls[0];
            text = t.Text;
            t.Text = "";
        }
        if (type == 2)
        {
            RadioButtonList r = (RadioButtonList)c.Controls[0];
            text = r.Text;
            r.ClearSelection();
        }
        if (type == 3)
        {
            RadioButtonList r = (RadioButtonList)c.Controls[0];
            text = r.Text;
            r.ClearSelection();
        }

        int element_id = d_questionIDs[poll][i];
        string response = text;
        //TODO: Update client ID from -1 to real client ID after login is implemented
        int client_id = -1;

        //responses[poll][i] = text;

        MySqlConnection dataConn;
        MySqlCommand dataCmd;

        dataConn = new MySqlConnection();
        dataConn.ConnectionString = connectionString;
        dataConn.Open();

        try
        {
            sql = "INSERT INTO poll_response_table "
                + "(poll_response_client_key, poll_response_poll_element_key, poll_response_response) "
                + "VALUES (@client_id, @element_id, @response)";

            dataCmd = new MySqlCommand(sql, dataConn);
            dataCmd.Parameters.AddWithValue("@client_id", client_id);
            dataCmd.Parameters.AddWithValue("@element_id", element_id);
            dataCmd.Parameters.AddWithValue("@response", response);

            dataCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            dataConn.Close();
            throw new Exception(ex.Message);
        }
        finally
        {
            dataConn.Close();
        }

    }
    /*
    Response.Write("<table><tr><td>");
    foreach (string s in responses[poll])
        Response.Write(s + "<br/>");

    foreach (List<string> l in responses)
    {
        Response.Write("----- <br/>");
        foreach(string s in l)
            Response.Write("- " + s + " <br/>");
    }
    Response.Write("</td></tr></table>");
    */
}

protected TableCell makeResponseCell(int type, int poll, int element)
{
    TableCell c = new TableCell();
    RadioButtonList r;
    TextBox t;
    switch (type)
    {
        //freeform textbox
        case 1:
            t = new TextBox();
            c.Controls.Add(new TextBox());
            break;
        //yes/no
        case 2:
            r = new RadioButtonList();
            r.RepeatDirection = RepeatDirection.Horizontal;
            c.Controls.Add(r);
            r.Items.Add("yes");
            r.Items.Add("no");
            break;
        //1-5
        case 3:
            r = new RadioButtonList();
            r.RepeatDirection = RepeatDirection.Horizontal;
            c.Controls.Add(r);
            r.Items.Add("1");
            r.Items.Add("2");
            r.Items.Add("3");
            r.Items.Add("4");
            r.Items.Add("5");
            break;
        //default = textbox
        default:
            c.Controls.Add(new TextBox());
            break;
    }

    c.ID = poll + "_" + element + "_response";

    return c;
}






protected void buildArticleWidget(Table t, string article_id)
{
    TableRow r;
    TableCell c;

    t.BorderWidth = 1;
    r = new TableRow();
    c = new TableCell();
    t.Rows.Add(r);
    r.Cells.Add(c);
    c.Text = "Article " + article_id + " goes here.";

    MySqlConnection dataConn = new MySqlConnection(); ;
    dataConn.ConnectionString = connectionString;
    dataConn.Open();

    //get widget configuration info from database
    string sql = "SELECT * from content_table WHERE cont_id=@cont_id";

    MySqlCommand dataCmd = new MySqlCommand(sql, dataConn);
    dataCmd.Parameters.AddWithValue("@cont_id", article_id);
    MySqlDataReader dataReader = dataCmd.ExecuteReader();

    string article_title = "";
    string article_content = "";

    try
    {
        if (dataReader.Read())
        {
            article_title = dataReader["cont_desc"].ToString();
            article_content = dataReader["cont_content_1"].ToString();
        }
    }
    catch (Exception ex)
    {
        dataReader.Close();
        dataConn.Close();
        throw new Exception(ex.Message);
    }
    finally
    {
        dataReader.Close();
        dataConn.Close();
    }

    r = new TableRow();
    t.Rows.Add(r);

    c = new TableCell();
    r.Cells.Add(c);

    c.Text = article_title;

    r = new TableRow();
    t.Rows.Add(r);

    c = new TableCell();
    r.Cells.Add(c);

    c.Text = article_content;
    c.Text = HttpUtility.HtmlDecode(c.Text);
    Regex.Replace(c.Text, "<.*?>", string.Empty);

}

protected void buildTweetWidget(Table t)
{
    MySqlConnection dataConn = new MySqlConnection(connectionString);
    dataConn.Open();

    //get widget configuration info from database
    string sql = "SELECT * from widget_config WHERE widgcon_id=2";

    MySqlCommand dataCmd = new MySqlCommand(sql, dataConn);
    MySqlDataReader dataReader = dataCmd.ExecuteReader();

    int num_tweets_displayed;
    string account;
    try
    {
        dataReader.Read();
        num_tweets_displayed = (int)(dataReader["widgcon_num_items_displayed"]);
        account = dataReader["widgcon_currently_displayed"].ToString();
    }
    catch (Exception ex)
    {
        dataReader.Close();
        dataConn.Close();
        throw new Exception(ex.Message);
    }
    finally
    {
        dataReader.Close();
        dataConn.Close();
    }
    string tweets = ("<br/>");

    foreach (var tweet in GetTweets(account).Take(num_tweets_displayed))
    {
        string s = Regex.Replace(HttpUtility.HtmlEncode(tweet), @"[a-z]+://[^\s]+",
            x => "<a href='" + x.Value.Replace("'", "&quot;") + "' style='tweet_link'>" + x.Value + "</a>",
            RegexOptions.Compiled | RegexOptions.IgnoreCase);
        tweets += (s + "<br/><br/>");
    }

    TableRow r = new TableRow();
    TableCell c = new TableCell();
    c.Text = "Tweet Widget";
    t.Rows.Add(r);
    r.Cells.Add(c);

    r = new TableRow();
    c = new TableCell();
    t.Rows.Add(r);
    r.Cells.Add(c);
    c.Text = tweets;

}

// called by buildTweetWidget
public List<string> GetTweets(string account)
{
    var ls = new List<string>();
    var jss = new JavaScriptSerializer();
    try
    {
        var d = jss.Deserialize<List<Dictionary<string, object>>>(
            new WebClient()
            .DownloadString("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" + account));

        foreach (var x in d)
            ls.Add((string)x["text"]);
    }
    catch
    {
        ls.Add("Unauthorized.");
    }

    return ls;
}

}

我一直在寻找重复的变量名,但没有找到。如果之前已经回答过这个问题,我深表歉意。提前致谢!

4

1 回答 1

0

如果你检查这个查询,它可能不止一次返回 widget_id 并且它必须是唯一的,因为你正在将它添加到字典中。

SELECT * FROM widget_instance_table, widget_instance_content_table "
            + "WHERE widget_instance_column_key=@column AND widget_instance_id=widget_instance_content_widget_instance_key
于 2012-04-27T21:12:48.573 回答