Dynamically populate HTML tables / web controls with different SQL select queries. PHP Vs ASP.NET

Last post 04-07-2009 1:14 AM by Danny117. 5 replies.

Sort Posts:

  • Dynamically populate HTML tables / web controls with different SQL select queries. PHP Vs ASP.NET

    04-03-2009, 6:31 PM
    • Member
      point Member
    • noone9
    • Member since 04-03-2009, 6:39 PM
    • Posts 2

    Hi to all, I'm new to this forum. I am a PHP programmer and recently I decided to give .NET 3.5 a try (ASP.NET/C# and ADO.NET), so far it has been intriguing to know how ASP.NET takes the leap towards a whole new programmatic methodology. I am accustomed to handling every HTTP request, every session, every cryptographic data handler, Apache modules, etc. It truly intrigued me how some things seem so much easier to develop in ASP.NET; i.e. login forms and session authentication, session handling, POSTBACKS (now this is truly superb) that wrap/integrate all the JavaScript code as part of the ASP.NET framework and allow web controls to be designed graphically. All of these quirks and plays make ASP.NET a very solid platform and it allows you to do things in seconds that would take hours to do on any other language (i.e. input validation).

    HOWEVER,  it would seem that with all the efforts in .NET, the programmatic dynamic development was left a little bit ashore. For instance if I am not mistaken it would seem that the only equivalent to associative arrays in PHP would be hashtables, and this is good, but developing something like this:

    $arrName = array("Key0" => array("01", "02", "03"), "Key1" => array("x", "y"));

    would be tedious in C#'s hashtables as strongly

    typed languages do not allow this kind of assignment during instantiation.

     

     Anyhow, on to the real topic...

    I developed this code in PHP to dynamically generate a table (actually its purpose is to dynamically generate an XML file that would be syncronized through AJAX to update a table of values real-time, but ignore the AJAX functionality and assume the XML is an HTML table for our purposes here). I haven't found yet how to do the equivalent in ASP.NET in a 'design' manner, I'm not sure if you can actually generate a GridView dynamically or if I can assign values to predefined controls dynamically (since I can't get the control ID's dynamically). It is quite obvious that I should do the PHP equivalent in ASP.NET.

     i.e. in PHP you could go like:

    <table ...>
    <tr><td>...</td></tr>
    fetch_row(...))
    {
    echo "<tr>";
    foreach($row as $value)
    {
    echo "<td>" . $value . "</td>";
    }
    echo "</tr>" . PHP_EOL;
    }
    ?>
    </table>

      However on ASP.NET it wouldn't make sense to use Response.Write(...) to generate a table, besides you won't be able to output it where you want unless you used some CSS hacks which is just not the way of doing things.

     

    OK, so the PHP equivalent to my code which is considerably more complex than the aforementioned, as I require a few different queries to run, would be to dynamically generate DataTables and generate some dynamic controls (i.e. labels, textboxes, or the like) with the correspondent values. This approach works perfectly and I generated the equivalent PHP code in ASP.NET, see below the code for the actual question...

     

    /*********************
    PHP CODE
    **********************/

    if(isset($_POST['submit']) && ($_POST['action'] === "[encrypted_value_here]"))
    {
    /******************
    * QUOTA: SEL / NSE
    *******************/
    //labels that represent the SEL, the associate array was used for retrieving this as XML data through AJAX.

    $arrSEL_Legend = array("01" => "5", "04" => "4", "06" => "3", "08" => "2", "10" => "1");
    //the quotas for each value
    $arrSELTotal = array("1" => 26, "2" => 60, "3" => 200, "4" => 140, "5" => 74); //1 = A, 2 = B, 3 = C, 4 = D, 5 = E
    //the values that correspond to the "IN (...) OPERATOR", these represent the codes 1 to 5 (A to E)

    $arrSELSQL = array("01" => "'01','02','03'", "04" => "'04','05'", "06" => "'06','07'", "08" => "'08','09'",
    "10" => "'10','11','12','13'");

    $mysqli = new mysqli("localhost", "user_name", "password", "db_name");
    if (mysqli_connect_errno())
    {
    die("Connection failed: Server is down, please try again later.<br />");
    }

    $arrNSE = array();
    foreach($arrSELSQL as $v)
    {
    $query = "SELECT * FROM `tableName` WHERE `F3` IN (" . $v . ") AND (`date` >= '" . $_POST['dateFrom'] . "' AND `date` <= '" . $_POST['dateTo'] . "')";
    $result = $mysqli->query($query);
    if($result)
    {
    array_push($arrNSE, $mysqli->affected_rows);
    $result->close();
    }
    }
    $v = NULL;

    $mysqli->close();

    echo "&lt;?xml version='1.0' encoding='ISO-8859-1'?>";
    echo "&lt;dynamic>";
    echo "&lt;total>" . $totalSurveys . "&lt;/total>";
    echo "&lt;missing_total>" . (500 - $totalSurveys) . "&lt;/missing_total>";

    $i = 0;
    foreach($arrSEL_Legend as $idx)
    {
    echo "&lt;nse_$i>" . $idx . "&lt;/nse_$i>";
    echo "&lt;total_nse_$i>" . $arrNSE[$i] . "&lt;/total_nse_$i>";
    echo "&lt;missing_nse_$i>" . ($arrSELTotal[$idx] - $arrNSE[$i]) . "&lt;/missing_nse_$i>";
    $i++;
    }
    $i = NULL;
    echo "&lt;/dynamic>";
    }

    /*********************
    ASP.NET CODE
    **********************/

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

    //manually added:
    using MySql.Data.MySqlClient;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.Configuration;
    using System.Collections; //for hash table

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    //
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
    lblSqlLog.Enabled = true;
    lblSqlLog.Visible = true;

    //Verify: Is there another way to check for unselected calendar date?
    if ( (CalendarFrom.SelectedDate.ToString() == "1/1/0001 12:00:00 AM") ||
    (CalendarTo.SelectedDate.ToString() == "1/1/0001 12:00:00 AM") )
    {
    //analogous to heredoc syntax in PHP
    lblSqlLog.Text =
    @"
    Log:<br />
    Error: You must choose a correct date.<br />
    Select a date and press submit.
    "
    ;
    return;
    }

    //Convert date from Calendar (SQL-like) format to MySQL format
    string strDateFrom = CalendarFrom.SelectedDate.ToString("yyyy-MM-dd 00:00:00", System.Globalization.DateTimeFormatInfo.InvariantInfo);
    string strDateTo = CalendarTo.SelectedDate.ToString("yyyy-MM-dd 23:59:59", System.Globalization.DateTimeFormatInfo.InvariantInfo);

    DateTime dtFrom = Convert.ToDateTime(strDateFrom);
    DateTime dtTo = Convert.ToDateTime(strDateTo);
    if (dtTo >= dtFrom) //verify that the final date is larger or equal to the first date
    {
    string strConn = WebConfigurationManager.ConnectionStrings["connStrNameHere"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(strConn);
    try
    {
    conn.Open();

    #region QUOTA = Socio-economic Level (SEL / NSE = Nivel Socio-economico)
    /******************
    * QUOTA: SEL / NSE
    *******************/
    //labels that represent the SEL

    string[] selLabels = new string[] { "A = 1", "B = 2", "C = 3", "D = 4", "E = 5" };
    //the quota for each value
    int[] selQuota = new int[] { 26, 60, 200, 140, 74 };
    //the values that correspond to the "IN (...) OPERATOR", these represent the codes 1 to 5 (A to E)
    string[] selSQL = new string[] { "'10','11','12','13'", "'08','09'", "'06','07'", "'04','05'", "'01','02','03'" };

    phSEL.Controls.Clear();
    Table selTbl = new Table();
    TableRow tr = new TableRow();
    TableCell tc = new TableCell();
    TextBox tb = new TextBox();
    Label lbl = new Label();

    lbl.Text = "Socio-economic Level";
    tc.Controls.Add(lbl);
    tr.Cells.Add(tc);
    tc = new TableCell();
    lbl = new Label();
    lbl.Text = "Total";
    tc.Controls.Add(lbl);
    tr.Cells.Add(tc);
    tc = new TableCell();
    lbl = new Label();
    lbl.Text = "Missing";
    tc.Controls.Add(lbl);
    tr.Cells.Add(tc);
    selTbl.Rows.Add(tr);

    int idx = 0;
    foreach (string str in selSQL) //string version
    {
    string query = "SELECT COUNT(`F3`) FROM `tableName` WHERE `F3` IN (" + str + ") AND (`date` >= '" + strDateFrom + "' AND `date` <= '" + strDateTo + "')";

    MySqlCommand cmd = new MySqlCommand(query, conn);
    MySqlDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows)
    {
    dr.Read();

    phSEL.Controls.Add(selTbl);
    tr = new TableRow();
    tc = new TableCell();
    tb = new TextBox();
    tb.Text = selLabels[idx];
    tb.ReadOnly = true;
    tc.Controls.Add(tb);
    tr.Cells.Add(tc);

    tc = new TableCell();
    tb = new TextBox();
    tb.Text = dr[0].ToString();
    tb.ReadOnly = true;
    tc.Controls.Add(tb);
    tr.Cells.Add(tc);

    tc = new TableCell();
    tb = new TextBox();
    int nVal = (selQuota[idx] - Convert.ToInt32(dr[0]));
    tb.Text = nVal.ToString();
    tb.ReadOnly = true;
    tc.Controls.Add(tb);
    tr.Cells.Add(tc);

    selTbl.Rows.Add(tr);
    }
    dr.Close();
    idx++;
    }
    #endregion
    }
    catch (Exception err)
    {
    lblSqlLog.Text = "Error Log: Could not connect or retrieve from the database.<br />";
    lblSqlLog.Text += err.Message;
    }
    finally
    {
    conn.Close();
    }
    }
    else
    {
    //analogous to heredoc syntax in PHP
    lblSqlLog.Text =
    @"
    Log:<br />
    Error: Choose correct dates, 'date to' must be larger or equal to 'date from'.<br />
    Make appropriate selection and press submit.
    "
    ;
    }
    }
    }

     

    OK, so all that is the actual code. The samples are given in MySQL but they can easily work the exact same in SQL Server 2000/2005/2008, the SQL code is irrelevant. So my question is, is this the only way of doing this, or is there a more 'simpler' design-like approach I could take. I am obviously not proficient in ASP.NET or .NET, I just hardcoded this by reading MSDN references and since C# is almost identical to C/C++ and PHP I have no problem translating code to C#, however as you can see from the sample above the PHP code is about 50 lines of code whereas the ASP.NET code (the MySQL specific code, not the rest) is about 102 lines, so that means it is about 2X larger than the PHP code.

     I just want some impressions from all of you guys on what would be the appropriate ASP.NET approach for this.

    Filed under:
  • Re: Dynamically populate HTML tables / web controls with different SQL select queries. PHP Vs ASP.NET

    04-03-2009, 9:01 PM
    • Star
      10,558 point Star
    • Danny117
    • Member since 12-16-2008, 9:30 AM
    • Royal Oak Michigan USA
    • Posts 1,837

    noone9:
    <table ...>
    <tr><td>...</td></tr>
    fetch_row(...))
    {
    echo "<tr>";
    foreach($row as $value)
    {
    echo "<td>" . $value . "</td>";
    }
    echo "</tr>" . PHP_EOL;
    }
    ?>
    </table>

    You can do that in asp.net almost line for line.

    echo "<td>" . $value . "</td>";
    translates to

    <td><%= eval("mydatacolumn") %></td>

    you should watch the sample video How to Create a Data Driven Website how to Video.  Or jump up to the newest craze for dotnet MVC http://www.asp.net/learn/mvc/

    Good Luck



  • Re: Dynamically populate HTML tables / web controls with different SQL select queries. PHP Vs ASP.NET

    04-05-2009, 11:09 AM
    • All-Star
      62,543 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 8:34 AM
    • England
    • Posts 12,210
    • TrustedFriends-MVPs

     Whilst most of the time the ASP.NET controls do a superb job, sometimes the HTML needs to be generated directly. In this case a tool like Html textWriter 2 is very useful. It is a free download from http://www.codeplex.com/HtmlTextWriter2

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: Dynamically populate HTML tables / web controls with different SQL select queries. PHP Vs ASP.NET

    04-06-2009, 12:31 PM
    • Member
      point Member
    • noone9
    • Member since 04-03-2009, 6:39 PM
    • Posts 2

    Hi guys,

    Indeed, I know I can dynamically data bind as an alternative approach which could also be 'equivalent' to how things are done in PHP, still I would prefer to follow the guidelines of .NET development rather than literarily translate from PHP.

    I did see a few of the 'tutorial videos' on this site to get an objective overview of some basic things that could be done with ASP.NET, but they are all novice videos rather than a computer science approach, I must confess I come from the C/C++, Assembly school so I would prefer to read books a la K&R or Petzold Win32 API rather than reading or watching tutorials.

    The "how to create data-driven sites" video is cool but all it does is teach the user how to bind a gridview and a webcontrol to a dataset generated through a downgraded copy of the pubs/adventureworks Authors table, so it is mostly a 'technology preview' video rather than a scientific approach at how to do things. Of course, it is good for a 13 minute video, obviously it was not going to teach the user how to code in ADO.NET.

    As for MVC, it is truly interesting that MS went for that pattern, specially useful for the Java developers. However, I want to be an expert C# ASP.NET developer (Web Forms pattern) before I delve into different architectural patterns (MVC).

    What books would you recommend for learning ASP.NET and ADO.NET (in C#) that are 'Computer Science / Enteprise Development' quality? I don't mind the level of complexity or the length of the book.

    I did come across a few books from which most of them I discarded, but these two seem like a good approach: Apress - Pro ASP.NET 3.5 in C# 2008 (I skimmed through some of the chapters and speed read a few key items and it seems rather good and complete) and Sams - ASP.NET 3.5 Unleashed (seems also complete, though less elaborated than the Apress one).

    What do you think about these books or what books would you recommend?

  • Re: Dynamically populate HTML tables / web controls with different SQL select queries. PHP Vs ASP.NET

    04-06-2009, 1:34 PM
    • All-Star
      62,543 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 8:34 AM
    • England
    • Posts 12,210
    • TrustedFriends-MVPs

     Have a look at Murach's ASP.NET 3.5 Web Programming with C# 2008 at http://www.murach.com/books/acs8/index.htm

    There are some sample chapters for download.

    For Videos, look at www.learnvisualstudio.net - there are some excellent tutorial videos there.

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: Dynamically populate HTML tables / web controls with different SQL select queries. PHP Vs ASP.NET

    04-07-2009, 1:14 AM
    • Star
      10,558 point Star
    • Danny117
    • Member since 12-16-2008, 9:30 AM
    • Royal Oak Michigan USA
    • Posts 1,837

    http://blogs.msdn.com/saraford/  Sara Ford just wrote a new book.  It will help more with Visual Studio than programming.

     

    Good Luck



Page 1 of 1 (6 items)