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 "<?xml version='1.0' encoding='ISO-8859-1'?>";
echo "<dynamic>";
echo "<total>" . $totalSurveys . "</total>";
echo "<missing_total>" . (500 - $totalSurveys) . "</missing_total>";
$i = 0;
foreach($arrSEL_Legend as $idx)
{
echo "<nse_$i>" . $idx . "</nse_$i>";
echo "<total_nse_$i>" . $arrNSE[$i] . "</total_nse_$i>";
echo "<missing_nse_$i>" . ($arrSELTotal[$idx] - $arrNSE[$i]) . "</missing_nse_$i>";
$i++;
}
$i = NULL;
echo "</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.