Wednesday, October 15, 2014

Professional UI – Html Class (Part 2)

It is really nice to have a html page inside the application, it gives a professional dress, it links many URLs, like web sites, documentation, video and other useful information.

This page should be interactive in order to show dynamic information. That is why it needs to be created every time it is showed.



I this blog a pointed out everything (source code) that can be useful and shared for other programmer. I define a category called “Toolbox” in order to give more useful instrument, often necessary to provide a good program. That is why I have projected this class. 

We all know that HTML Language is the standard markup language used to create web pages. A HTML document is a simple text file, written in the form of HTML elements consisting of tags enclosed in angle brackets like in figure below.


So my class, works in order to manipulate this kind of documents, but how?

First of all the user have to create a HTML document template, that will have the desired layout structure with styles and some static contents and dynamic as well. 


Figure 1: Html Template File

Figure 2: How the template appears

How the dynamic content will be inserted will be documented ahead. 
The class will take this template, will manipulate the content that will became the definitive version showed into the application.
I summarize the specifics:

Input Elements:
  • HTML Template document
  • TagB and values: list of elements to replace run-time in template file.
  • Templates location: source directory where the templates are stored.
  • Report destination: where the elaborated copy will be produced.
  • Images location: the directory where images can be stored. It can manage image as well.

Output Element:
  • HTML Report or definitive HTML file manipulated.

Basic functions:
  • Loading the template file into a string list or collection.
  • Manipulation of this list.
  • Save the list into a new file Report.
  • Other support methods.

HTML Template document manipulation

One thing I omitted! This is how I will manage this file, in order to produce a new one.

Well, as we know Html uses tags closed into < and > brackets, so I have decided to introduce new custom tags but closed between curly brackets {}. This tags have significance only for the program or programmer. These tags will be replaced run-time by our application.

For example if I insert into my Html template {ref_version} when the program will find this tag then it will replace it with a string about the program version (eg. ManipulateHtml ver 1.0.1).

For convention, I called these tags TagB (Tags between Braces or Curly brackets).

So, my class has to:
  • Import the html template file.
  • Analyze it in order to find the TagB.
  • Replace these TagB with some values.
  • Produce a new html document.
The program will show this final html document.

 
public class HtmlReportBase
{
    //===============================================================================
    #region Variables Declarations
    protected string mTemplateDir;
    public string TemplateDir { get { return mTemplateDir; } }
    protected string mReportDir;
    public string ReportDir { get { return mReportDir; } }
    protected string mReportFile;
    public string ReportFile { get { return mReportFile; } }
    protected string mTemplateFile;
    public string TemplateFile { get { return mTemplateFile; } }
    protected string mImagesDir;
    public string ImagesDir { get { return mImagesDir; } }

    protected StringCollection mHtmlFile;
    protected FieldsItem myFieldList = new FieldsItem();
    protected TablesItem myTableList = new TablesItem();
    #endregion


The first part of our class defines the member variables and properties. In particular, the last three are more interesting.

  • mHtmlFile: contains all html original template text lines.
  • myFieldList: is a list of TagB to replace with their correspondent new values.
  • myTableList: Is a list of TagB to replace and their HtmlTable values. It is an improvement I did to this class, in order to manage also Html tables run-time.

First Step

 
// Constructor
//

// es. c:\myapp\print\report\
// es. c:\myapp\print\template\
// es. c:\myapp\print\images\
public HtmlReportBase(string sReportDir, string sTemplateDir, string sImagesDir)
{
    this.Initialize(sReportDir, sTemplateDir, sImagesDir);
}

Setup the involved directories.
 
// 
// Load the template into the mHtmlFile string collection.
//
// aTemplateFileNameOnly: File Name only! The Directory is already specified calling Initialize()
public void LoadTemplate(string aTemplateFileNameOnly)
{
    try
    {
        mTemplateFile = Path.GetFileName(aTemplateFileNameOnly);
        string sTemplate = (mTemplateDir + "\\" + mTemplateFile);

        Utility.LoadFileIntoCollection(sTemplate, out mHtmlFile);
    }
    catch (Exception ex)
    {
        Utility.ShowError("ReadTemplate(): " + ex.Message);
    }
}

Load html template into mHtmlFile string collection.


Second Step

Decide the TagB list to replace, and populate it.


 
// 
// Add and Item into the list (TagB, Value)
//
public void AddItem(string aFieldName, string aFieldValue)
{
    try
    {
        FieldItem oItem = new FieldItem("{" + aFieldName + "}", aFieldValue);
        myFieldList.Add(oItem);
    }
    catch (Exception ex)
    {

        Utility.ShowError("AddItem(): " + ex.Message);
    }
}


Third Step

Replace the TagB with values

 
// 
// Search the TagB into the html file and replace these with the FieldList values
//
public void ReplaceTags()
{
    try
    {
        int i, j;
        string s = "";

        for (i = 0; i < (mHtmlFile.Count); i++)
        {
            for (j = 0; j < myFieldList.Count; j++)
            {
                if (mHtmlFile[i].Contains("{"))
                {
                    s = mHtmlFile[i];
                    mHtmlFile[i] = mHtmlFile[i].Replace(myFieldList[j].FieldName, myFieldList[j].Value);
                    if (s != mHtmlFile[i])
                        break;
                }
            }
        }
        ReplaceTables();
    }
    catch (Exception ex)
    {
        Utility.ShowError("ReplaceFields(): " + ex.Message);
    }
}

Fourth Step

Generate the final document

 
// 
// Generate the final Report
//
public void WriteReport(string aReportFileNameOnly)
{
    try
    {
        mReportFile = aReportFileNameOnly;
        string sFileName = (mReportDir + "\\" + mReportFile);
        if (File.Exists(sFileName))
        {
            File.Delete(sFileName);
        }
        Utility.SaveCollectionIntoFile(ref mHtmlFile, sFileName);
    }
    catch (Exception ex)
    {
        Utility.ShowError("WriteReport(): " + ex.Message);
    }
}





At the end I have created an example, that loads the template and shows on a grid all the TagB contained in this document. The user can complete the grid with the values to replace.


 
private void btnCreate_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in grdTags.Rows)
    {
        if (row.Cells[1].Value != null)
            moHtml.AddItem(row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString());
    }

    moHtml.ReplaceTags();
    moHtml.WriteReport("Index.html");

    Utility.BrowseTo(moHtml.ReportDir + "\\" + moHtml.ReportFile);
}