Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to C# - trying to write code to do a simple function

Tags:

c#

.net

mysql

I'm new to C# (worked in PHP, Python, and Javascript) and I'm trying to more or less make a duplicate of another page and change some things - to make a form and database submission.

Anyway, here's the code:

public partial class commenter : System.Web.UI.Page
{

    string employee_reviewed;
    //public Commenter();
    public void SaveBtn_Click(object sender, EventArgs e)
    {
        if (CommentTB.Text == "Please enter a comment.")
        {
            String csname = "Email Error";
            Type cstype = this.GetType();
            ClientScriptManager cs = Page.ClientScript;
            if (!cs.IsStartupScriptRegistered(cstype, csname))
            {
                String cstext = "alert('Please submit at least one comment.');";
                cs.RegisterStartupScript(cstype, csname, cstext, true);
            }
            FormMessage.Text = "Please submit at least one comment.";
            return;
        }
        string comment = CommentTB.Text;
        comment = comment.Replace("'", "''");
        comment = comment.Replace("’", "''");
        comment = comment.Replace("`", "''");

        try
        {
            //myCommand.Connection.Open();
            //myCommand.ExecuteNonQuery();
            //myCommand.Connection.Close();

            MySqlCommand myCommand;
            MySqlConnection connection;
            string connStringName = "server=localhost;database=hourtracking;uid=username;password=password";
            connection = new MySqlConnection(connStringName);

            string sql_query;


            sql_query = "insert into peer_review_comment " + " (emp_id,  comment)" + " values(?employeeid, ?comment) ";

            //String csname = "Email Error";
            //Type cstype = this.GetType();
            //ClientScriptManager cs = Page.ClientScript;
            //cs.RegisterStartupScript(cstype, csname, sql_query, true);
            myCommand = new MySqlCommand(sql_query, connection);
            //FormMessage.Text = sql_query;
            //return;

            Trace.Write("comment = ", comment);
            myCommand.Parameters.Add(new MySqlParameter("?employeeid", ViewState["employeeid"].ToString()));
            myCommand.Parameters.Add(new MySqlParameter("?comment", comment));

            try
            {
                myCommand.Connection.Open();
                myCommand.ExecuteNonQuery();
                myCommand.Connection.Close();
            }
            catch (Exception ex)
            {
                FormMessage.Text = "Error:SaveBtn_Click - " + ex.Message;
            }
            //SendNotification(from, to, cc, subject, body, attach);
            FormMessage.Text = "\n Thank you for leaving anonymous feedback for " + employee_reviewed; ;
            ThankyouDiv.Visible = true;
            FormFieldDiv.Visible = false;
            reviewHeader.Visible = false;
        }
        catch (Exception ex)
        {
            FormMessage.Text = "Error:SaveBtn_Click - " + ex.Message;
        }
    }
}

I really have little idea what I'm doing - I'm reading the tutorials, but C# is a significantly different language than I am used to.

I get the Javascript alert when I do not change the text currently, but submission isn't working - I want it to submit to peer_review_comment database table, and fill in employeeid as well as the submitted comment.

Sorry if my understanding is so spotty, I am a TOTAL C# newbie (currently reading http://www.csharp-station.com/Tutorial/CSharp/)

like image 332
Steven Matthews Avatar asked Oct 17 '12 12:10

Steven Matthews


People also ask

What is getch () in C language?

getch() method pauses the Output Console until a key is pressed. It does not use any buffer to store the input character. The entered character is immediately returned without waiting for the enter key. The entered character does not show up on the console.

Can we use new in C?

There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.

What is new () in C?

new() The new operator requests for the memory allocation in heap. If the sufficient memory is available, it initializes the memory to the pointer variable and returns its address.

What does \n do in C?

What is \n exactly? The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.


1 Answers

My guess is the problem is here:

try
{
    myCommand.Connection.Open();
    myCommand.ExecuteNonQuery();
    myCommand.Connection.Close();
}
catch (Exception ex)
{
    FormMessage.Text = "Error:SaveBtn_Click - " + ex.Message;
    // no "return;"  !!
}
//SendNotification(from, to, cc, subject, body, attach);
FormMessage.Text = "\n Thank you for leaving anonymous feedback for " + 
                        employee_reviewed; ;

Your catch block is setting the FormMessage.Text value bot not exiting the method, so the method keeps executing where the catch block finishes off, resetting the Text value and appearing that no exception was thrown.

add a return; at the end of your catch block to see the excpetion message.

Some general guidelines to make these kinds of problems easier to trap:

  • Don't try to do too much in one method. Have one method that validates the message (or do it client-side using Validators, another to do the DB call, etc.
  • Learn to use the debugger. You can step through code and get a better idea of what causes these kinds of errors.
  • Unless you can DO something about an exception, there's no harm in letting them bubble up to a higher level event handler (like Elmah) so exceptions don't get accidentally swallowed like it does here. In general it's preferrable to re-throw exceptions in lower-level methods (maybe adding some context or a user-friendly message) so the higher level exception handling can decide what to do (show a message, log, etc.)
like image 134
D Stanley Avatar answered Nov 14 '22 22:11

D Stanley