-1

I have this C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;

public partial class UpdateArticle : System.Web.UI.Page
{
    public string ArticleTitle, ArticleBody, PostDate;

    protected void Page_Load(object sender, EventArgs e)
    {
        string ArticleId;
        try
        { ArticleId = Request.QueryString["ArticleId"].ToString();
            string dpath = Server.MapPath(@"App_Data") + "/MySite.mdb";
            string connectionstring = @"Data source='" + dpath + "';Provider='Microsoft.Jet.OLEDB.4.0';";
            string q = string.Format("select *  from tblArticles where ArticleId={0}", ArticleId);
            OleDbConnection con = new OleDbConnection(connectionstring);
            OleDbCommand cmd = new OleDbCommand(q, con);
            con.Open();
            cmd.ExecuteNonQuery();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "tbl");
            con.Close();
            ArticleTitle = ds.Tables[0].Rows[0]["ArticleTitle"].ToString();
            ArticleBody = ds.Tables[0].Rows[0]["ArticleBody"].ToString();
            PostDate = ds.Tables[0].Rows[0]["PostDate"].ToString();


        }
        catch
        { }
        string NewArticleTitle, NewArticleDate, NewArticleBody, ArticleId1;  
        try
        {

                NewArticleTitle = Request.Form["ArticleTitle"].ToString();
                NewArticleDate = Request.Form["ArticleDate"].ToString();
                NewArticleBody = Request.Form["ArticleBody"].ToString();
                ArticleId1 = Request.QueryString["ArticleId"].ToString();
                string dpath = Server.MapPath(@"App_Data") + "/MySite.mdb";
                string connectionstring = @"Data source='" + dpath + "';Provider='Microsoft.Jet.OLEDB.4.0';";
                OleDbConnection con = new OleDbConnection(connectionstring);
                string QuaryString = string.Format("insert into tblArticles(ArticleTitle, ArticleBody, PostDate) values ('{0}','{1}','{2}') where ArticleId='{3}'", NewArticleTitle, NewArticleBody, NewArticleDate, ArticleId1);
                OleDbCommand cmd = new OleDbCommand(QuaryString, con);
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds, "tbl");
                con.Close();
            }
            catch { }
       // Response.Redirect("ArticlesTable.aspx");

}}

The problem in my code is that when it comes to this line :

ArticleId1 = Request.QueryString["ArticleId"].ToString();

It exits from the try block. A few lines above I wrote this code :

ArticleId = Request.QueryString["ArticleId"].ToString();

And it works just fine. So why is the lower line not working? When I debug it in the first time: 1: https://i.stack.imgur.com/CfKXL.png after submiting the form in the ASPX page: this is the aspx code:

<b>
כותרת המאמר :<br /></b><input id="Text1" type="text" name="ArticleTitle" value="<%=ArticleTitle %>"/><p></p>
<b>

תאריך פרסום: <br /></b><input id="Text2" type="text" name="ArticleDate" value="<%=PostDate %>"/><p></p>

<b>

תוכן המאמר: <br /></b> <textarea rows="10" cols="60"  name="ArticleBody"><%=ArticleBody %></textarea>
<br />
<input id="Reset1" type="reset" value="נקה" />
<input id="Submit1" type="submit" value="שלח כתבה!" />
</form>
<p></p><p></p>

<a href="Default.aspx">חזור לדף הבית</a>

And after the submit (The var not getting the Id value!) enter image description here

Nave Tseva
  • 868
  • 8
  • 24
  • 47
  • 8
    Catch the exception and display the exception information. – RBarryYoung Jan 10 '13 at 21:15
  • 2
    [MSDN using Statement](http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.110).aspx) -- `OleDbCommand` and `OleDbConnection` both implement `IDisposable`. – Austin Salonen Jan 10 '13 at 21:16
  • 1
    You need to step through your code and see what is happening – codingbiz Jan 10 '13 at 21:17
  • 1
    What is the reason of double accessing to `Request.QueryString["ArticleId"]`? Why dont you use `ArticleId` to assign `ArticleId1`, if `ArticleId` is successfully initialized? – Alexander Balte Jan 10 '13 at 21:17
  • Try catching the exception like this: `catch (Exception exc) { throw(exc); } – Brian Jan 10 '13 at 21:17
  • Are you sure that the first part completed successfully? How do you know that that exact line is the problem? – SWeko Jan 10 '13 at 21:18
  • @MichaelBerkowski When someone suggests a bad edit and your "improve" of that edit is just undoing everything they did, you shouldn't mark it as helpful, you should mark it as not helpful... – Servy Jan 10 '13 at 21:19
  • May be the Server.MapPath... ? – codingbiz Jan 10 '13 at 21:20
  • 2
    Wow I hope that code is not going into a company's application. You should use using or at least close the connections on finally. Also, catching exceptions without handling them is a great way to miss errors. Are you sure that is the line that is generating the error? – Nick Bray Jan 10 '13 at 21:20
  • 3
    Oh, and since nobody's mentioned it, you shouldn't be concatenating strings to create SQL queries; it leaves you open to SQL injection. You should use parameterized queries. – Servy Jan 10 '13 at 21:23
  • Although in this case it can be prevented by an int.parse... Not recommending it though! – RobH Jan 10 '13 at 21:26
  • , @Nick Bray This is not something big, it is work that I got from school, can you explain what wrong with this connection to the DB code? Thanks you every one! – Nave Tseva Jan 10 '13 at 21:39
  • Read the link posted by Austin Salonen. You should use the using statement when you use a dbconnection. – Nick Bray Jan 10 '13 at 21:43
  • @RBarryYoung run that code with an article title of `'); DROP TABLE tblArticles; --` and see what happens ;). Using `string.Format`, under the hood, will just concat the strings together. It will not sanitize the input strings to ensure they contain entirely literal SQL text with no embedded queries. – Servy Jan 10 '13 at 21:49
  • 1
    @RobH For the first query, sure, for the second, no, not a chance. – Servy Jan 10 '13 at 21:51
  • @RBarryYoung I don't see how you could ever think that it was. Both of the locations that define the SQL queries use `string.Format` to create the queries. Do you actually think that using `string.Format` is a safe way to create a query that can't be injected into? There is no reference to parameters, with respect to the database object, where I could see you possibly thinking that this is using a parameterized query. The relevant lines are the definitions of `q` and `QueryString`. – Servy Jan 10 '13 at 21:53
  • @Servy: OK, I see, he's using String.Format() substitution. My eyes fooled me because explicit parametization in SqlClient can also use the "..{0}.." format, but its perfectly safe there (because its a sql parameter in that case). Sorry, my bad. – RBarryYoung Jan 10 '13 at 21:56
  • @Servy Didn't see that query :S – RobH Jan 11 '13 at 09:41

2 Answers2

0

If your code is suddenly exiting from a try block unexpectedly, it's catching an exception.

If your catch statement throws away that exception as catch { } does, then you'll never see it.

You should either remove the try/catch altogether and let the error bubble up naturally, or you should catch it and do something with it:

catch (Exception ex)
{
   // However you want to handle things going wrong.
}
Bobson
  • 13,498
  • 5
  • 55
  • 80
0

Your code is throwing an exception, most likely because Request.QueryString["ArticleId"] has gone out of scope. I'm not sure why this would happen, but it's the most likely explanation. Change catch {} to catch (Exception e) {} and set a break point there so you can inspect the exception. Assuming this is what's happening, declare a ArticleId1 outside of the first try and then set it the line after you set ArticleId (in the first try).

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • 1
    If the query string isn't there it will just return `null`. My guess is he's just getting a null pointer exception when he tries to `ToString` it. – Servy Jan 10 '13 at 21:35