Skip to main content
Home  › ... Razor

Data Tutorials

Tutorial HomeData

The top 10 files found in this portal as returned from DB

This example queries the DNN SQL for the files using DataReader objects.


@{
  // load the sql connection name from Web.Config
  // the default connection string for DNN is SiteSqlServer
  var conString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString();

  var con = new SqlConnection(conString);
  con.Open();

  // You should always write parameters using the @-syntaxt,
  // and never write them directly into the SQL using string-concatenation
  // to protect yourself from SQL injection attacks
  var command = new SqlCommand("Select Top 10 * from Files Where PortalId = @PortalId", con);
  command.Parameters.Add("@PortalId", CmsContext.Site.Id);
  var myReader = command.ExecuteReader();
}

  1. image-1.jpg
  2. image-2.jpg
  3. ct basic content.png
  4. ct image.png
  5. ct layout element.png
  6. ct links.png
  7. ct location.png
  8. ct person.png
  9. ct video.png
  10. RazorTutoApp1000x1000.png

<ol>
  @while (myReader.Read())
  {
    <li>@myReader["FileName"]</li>
  }
</ol>
@{
  myReader.Close();
}

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor12
<!-- unimportant stuff, hidden -->
@using System.Configuration
@using System.Data
@using System.Data.SqlClient

The top 10 files found in this portal as... <!-- unimportant stuff, hidden -->

@{
  // load the sql connection name from Web.Config
  // the default connection string for DNN is SiteSqlServer
  var conString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString();

  var con = new SqlConnection(conString);
  con.Open();

  // You should always write parameters using the @-syntaxt,
  // and never write them directly into the SQL using string-concatenation
  // to protect yourself from SQL injection attacks
  var command = new SqlCommand("Select Top 10 * from Files Where PortalId = @PortalId", con);
  command.Parameters.Add("@PortalId", CmsContext.Site.Id);
  var myReader = command.ExecuteReader();
}





<ol>
  @while (myReader.Read())
  {
    <li>@myReader["FileName"]</li>
  }
</ol>
@{
  myReader.Close();
}



<!-- unimportant stuff, hidden -->