Tuesday, December 9, 2014

ASP.NET Web Pages - Files


This chapter is about working with text files.

Working with Text Files

In a previous chapter, we looked at web data stored in a database.
Your web site may also have data stored in text files.
Text files used to store data is often called flat files. Common text file formats are .txt, .xml, and .csv (comma-delimited values).
In this chapter you will learn:
  • How to read and display data from a text file

Add a Text File Manually

In the example to follow, you will need a text file to work with.
On your web site, if you don't have an App_Data folder, create one. In the App_Data folder, create a new file named Persons.txt.
Add the following content to the file:

Persons.txt

George,Lucas
Steven,Spielberg
Alfred,Hitchcock


Displaying Data from a Text File

The example below shows how to display data from a text file:  

Example

@{
var dataFile = Server.MapPath("~/App_Data/Persons.txt");
Array userData = File.ReadAllLines(dataFile);
}
<!DOCTYPE html>
<html>
<body>

<h1>Reading Data from a File</h1>
@foreach (string dataLine in userData)
{
  foreach (string dataItem in dataLine.Split(','))
  {@dataItem <text>&nbsp;</text>}

  <br />
}
</body>
</html>

Run example »

Example explained

Server.MapPath finds the exact text file path.
File.ReadAllLines opens the text file and reads all lines from the file into an array.
For each dataItem in each dataline of the array the data is displayed.

ASP.NET Web Pages - PHP


Attention PHP Developers. Web Pages can be written in PHP.

WebMatrix Supports PHP

At first look, WebMatrix only supports Microsoft technologies. This is not true. In WebMatrix you can write full PHP applications with MySQL and all.

Create a PHP Site

In WebMatrix, create an empty site named "Demo_PHP", enable PHP (see picture below), create a new empty page of the type PHP, name it "index.php", and you have created your first PHP site.  
Screenshoot

Create a PHP Page

Put the following code inside the "index.php" file:

index.php

<!DOCTYPE html>
<html>
<body>

<?php
phpinfo();
?>


</body>
</html>
Run the file and see PHP at work.

ASP.NET Web Pages - The Chart Helper


The Chart Helper - One of many useful ASP.NET Web Helpers.

The Chart Helper

In the previous chapters, you learned how to use an ASP.NET "Helper".
You learned how to display data in a grid using the "WebGrid Helper".
This chapter explains how to display data in graphical form, using the "Chart Helper".
The "Chart Helper" can create chart images of different types with many formatting options and labels. It can create standard charts like area charts, bar charts, column charts, line charts, and pie charts, along with more specialized charts like stock charts.
chart chart
The data you display in a chart can be from an array, from a database, or from data in a file.

Chart From an Array

The example below shows the code needed to display a chart from an array of values:

Example

@{
var myChart = new Chart(width: 600, height: 400)
   .AddTitle("Employees")
   .AddSeries(chartType: "column",
      xValue: new[] {  "Peter", "Andrew", "Julie", "Mary", "Dave" },
      yValues: new[] { "2", "6", "4", "5", "3" })
   .Write();
}

Run example »
new Chart creates a new chart object and sets its width and height
- the AddTitle method specifies the chart title
- the AddSeries method adds data to the chart
- the chartType parameter defines the type of chart
- the xValue parameter defines x-axis names
- the yValues parameter defines the y-axis values
- the Write() method displays the chart 

Chart From Database Data

You can run a database query and then use data from the results to create a chart:

Example

@{
var db = Database.Open("SmallBakery");
var dbdata = db.Query("SELECT Name, Price FROM Product");
var myChart = new Chart(width: 600, height: 400)
   .AddTitle("Product Sales")
   .DataBindTable(dataSource: dbdata, xField: "Name")
   .Write();
}

Run example »
var db = Database.Open opens the database (and assigns the database object to the variable db)
var dbdata = db.Query runs a database query and stores the result in dbdata
new Chart creates a chart new object and sets its width and height
- the AddTitle method specifies the chart title
- the DataBindTable method binds the data source to the chart
- the Write() method displays the chart 
An alternative to using the DataBindTable method is to use AddSeries (See previous example). DataBindTable is easier to use, but AddSeries is more flexible because you can specify the chart and data more explicitly:

Example

@{
var db = Database.Open("SmallBakery");
var dbdata = db.Query("SELECT Name, Price FROM Product");
var myChart = new Chart(width: 600, height: 400)
   .AddTitle("Product Sales")
   .AddSeries(chartType:"Pie",
      xValue: dbdata, xField: "Name",
      yValues: dbdata, yFields: "Price")
   .Write();
}

Run example »


Chart From XML Data

The third option for charting is to use an XML file as the data for the chart:

Example

@using System.Data;

@{
var dataSet = new DataSet();
dataSet.ReadXmlSchema(Server.MapPath("data.xsd"));
dataSet.ReadXml(Server.MapPath("data.xml"));
var dataView = new DataView(dataSet.Tables[0]);
var myChart = new Chart(width: 600, height: 400)
   .AddTitle("Sales Per Employee")
   .AddSeries("Default", chartType: "Pie",
      xValue: dataView, xField: "Name",
      yValues: dataView, yFields: "Sales")
   .Write();}
}

ASP.NET Web Pages - The WebGrid Helper


WebGrid - One of many useful ASP.NET Web Helpers.

Doing the HTML Yourself

In a previous chapter, you displayed database data by using razor code, and doing the HTML markup yourself:

Database Example

@{
var db = Database.Open("SmallBakery");
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}

<html>
<body>
<h1>Small Bakery Products</h1>
<table>
<tr>
<th>Id</th>
<th>Product</th>
<th>Description</th>
<th>Price</th>
</tr>
@foreach(var row in db.Query(selectQueryString))
{

<tr>
<td>@row.Id</td>
<td>@row.Name</td>
<td>@row.Description</td>
<td style="text-align:right">@row.Price</td>
</tr>
}
</table>
</body>
</html>

Run example »


Using The WebGrid Helper

Using the WebGrid helper is an easier way to display data.
The WebGrid helper:
  • Automatically sets up an HTML table to display data
  • Supports different options for formatting
  • Supports paging through data
  • Supports Sorting by clicking on column headings

WebGrid Example

@{
var db = Database.Open("SmallBakery") ;
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
var data = db.Query(selectQueryString);
var grid = new WebGrid(data);
}

<html>
<head>
<title>Displaying Data Using the WebGrid Helper</title>
</head>
<body>
<h1>Small Bakery Products</h1>
<div id="grid">
@grid.GetHtml()
</div>
</body>
</html>

ASP.NET Web Pages - Databases


This chapter is about working with databases.

What We Will Do

In this chapter we will:
  • Create a web page to list data from a database

Displaying Data from Database

With Web Pages, you can easily display data from a database.
You can connect to an existing database, or create a new database from scratch.
In this example we will connect to an existing SQL Server Compact database.
If you want to learn how to create a database for your web, please go to the chapter Web Database.

Adding a Customers Page

In the "DemoWebPages" folder, create a new CSHTML file named "Products.cshtml".
Replace the code in the file with the code from the example below:

Products.cshtml

@{
var db = Database.Open("SmallBakery");
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}

<html>
<body>
<h1>Small Bakery Products</h1>
<table>
<tr>
<th>Id</th>
<th>Product</th>
<th>Description</th>
<th>Price</th>
</tr>
@foreach(var row in db.Query(selectQueryString))
{

<tr>
<td>@row.Id</td>
<td>@row.Name</td>
<td>@row.Description</td>
<td align="right">@row.Price</td>
</tr>
}
</table>
</body>
</html>

Run example »

ASP.NET Web Pages - The WebMail Helper

ASP.NET Web Pages - The WebMail Helper


The WebMail Helper - One of many useful ASP.NET Web Helpers.

The WebMail Helper

The WebMail Helper makes it easy to send an email from a web application using SMTP (Simple Mail transfer Protocol).

Scenario: Email Support

To demonstrate the use of email, we will create an input page for support, let the user submit the page to another page, and send an email about the support problem.

First: Edit Your AppStart Page

If you have built the Demo application in this tutorial, you already have a page called _AppStart.cshtml with the following content:

_AppStart.cshtml

@{
WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId", "Email", true);
}
To initiate the WebMail helper, add the the following WebMail properties to your AppStart page:

_AppStart.cshtml

@{
WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId", "Email", true);
WebMail.SmtpServer = "smtp.example.com";
WebMail.SmtpPort = 25;
WebMail.EnableSsl = false;
WebMail.UserName = "support@example.com";
WebMail.Password = "password-goes-here";
WebMail.From = "john@example.com";

}
Properties explained:
SmtpServer: The name the SMTP server that will be used to send the emails.
SmtpPort: The port the server will use to send SMTP transactions (emails).
EnableSsl: True, if the server should use SSL (Secure Socket Layer) encryption.
UserName: The name of the SMTP email account used to send the email.
Password: The password of the SMTP email account.
From: The email to appear in the from address (often the same as UserName).

Second: Create an Email Input Page

Then create an input page, and name it Email_Input:

Email_Input.cshtml

<!DOCTYPE html>
<html>
<body>
<h1>Request for Assistance</h1>

<form method="post" action="EmailSend.cshtml">
<label>Username:</label>
<input type="text name="customerEmail" />
<label>Details about the problem:</label>
<textarea name="customerRequest" cols="45" rows="4"></textarea>
<p><input type="submit" value="Submit" /></p>
</form>

</body>
</html>
The purpose of the input page is to collect information, then submit the data to a new page that can send the information as an email.

Third: Create An Email Send Page

Then create the page that will be used to send the email, and name it Email_Send:

Email_Send.cshtml

@{ // Read input
var customerEmail = Request["customerEmail"];
var customerRequest = Request["customerRequest"];
try
{
// Send email
WebMail.Send(to:"someone@example.com", subject: "Help request from - " + customerEmail, body: customerRequest );
}
catch (Exception ex )
{
<text>@ex</text>
}
}