Showing posts with label Toolbox Components. Show all posts
Showing posts with label Toolbox Components. Show all posts

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);
}








Tuesday, September 16, 2014

Professional UI – The Recent List (Part 1)

In this Post I will start to talk about how to project a Professional UI and what it should be useful to develop in order to maintain and create it.

In figure below you can see an UI that I have projected for GSLab, a computational program used to project substation grounding grid.



I toke inspiration by Visual Studio Interface, Microsoft Word and other common application on commercial market. What works for many it should work for few. In this UI it is possible to find many useful features.


  • A Toolbar (Ribbon Style), with items  that appear and disappear it depends on program status.
  • A Status bar that resume all main selections, program status, some user advice
  • A Left Panel where the user input parameters
  • A Start Page that works like a web browser.


Let's concentrate on Start Page.





We can distinguish three areas: Every one of which is very useful for the user’s experience.

Start: Gives to users the mains starting functionalities.

Recent: The List of last used projects.

Html: Area with useful information and links.

Before create this page, we have to create the separate functionalities that it grasp together. These functionalities could be accessed from different parts of the program. For example the "Recent List".

The “Recent List”


What is "the Recent List"?

Well. It is quite trivial to explain it and maybe it is not necessary to do that, but I will try anyway. First of all, it is a list, where we can find a maximum number of project references. This list has a project reference as unique key, this is because a project reference can appear just one time.

A project reference can be seen as a file, a name, a title, doesn't matter. In this particular case a Project Name.

Furthermore, the top item of the list is the last inserted. If an element already exist into the list when we try to insert it, then it is moved on top.


Example:

Recent List - State 1
1
Project C
2
Project B
3
Project F

Three projects inserted.

We Add a New project Project Z

Recent List - State 2
1
Project Z
2
Project C
3
Project B
4
Project F

Four projects inserted.

We Add again a project Project C

Recent List - State 3
1
Project C
2
Project Z
3
Project B
4
Project F

Four projects inserted.

Now it is clear how it works and we can start to make a class that do that.

Where to store these information?

Also in this case there are many possibilities I decide to use the Windows Registry.

 
public class FilesHistory: RegistryBase
{
const int MAX_ELEMENTS = 10;
List moFiles = new List(MAX_ELEMENTS);

public List Files

public FilesHistory(string sCompany, string sApplicationName)

public void Save()

public void Load()

public void Add(string sFileName)
}

The class definition it is very easy as it should be. It inherited from another class (RegistryBase) that it is not here explained but also easy to create.

A single property “Files” that contains the elements, and three methods: Save, Load, Add.

  • Save, as the name said, saves a list into the registry.
  • Load, loads from the registry and populate the list.
  • Add, append a new item into the list.

The Add() method use a private method Append() as well.

It removes the element instance if exist then append it. If a maximum number of elements is reached the last element is removed.

 
public void Add(string sFileName)
{
moFiles.Remove(sFileName);
Append(sFileName); //FIFO

if (moFiles.Count == MAX_ELEMENTS)
moFiles.RemoveAt(moFiles.Count-1);
}

The Append() method use a temporary list, where inserts the new element at the top, and then append all the old list.

 
private void Append(string sFileName)
{
List moFilesNew = new List(MAX_ELEMENTS);

moFilesNew.Add(sFileName);
foreach (string item in moFiles)
{
moFilesNew.Add(item);
}

moFiles.Clear();
moFiles.AddRange(moFilesNew);
}

Lets check the other two methods Save() and Load():

 
public void Save()
{
for (int i = 0; i < MAX_ELEMENTS; i++)
{
if (i < moFiles.Count)
Write("Main", "File" + i.ToString(), moFiles[i]);
else
Write("Main", "File" + i.ToString(), "");
}
}

public void Load()
{
for (int i = 0; i < MAX_ELEMENTS; i++)
{
string s = Read("Main", "File" + i.ToString());
if (s != "")
moFiles.Add(s);
}
}

As you can see these two methods uses Write(), and Read() methods inherited from the base class RegistryBase.

Ready to use

Now you are ready to use this class

Declaration:

FilesHistory HistoryFiles = new FilesHistory("MyCompany", "AppID");

The constructor parameters are the keys used for registry storing.

Starting the Application, the list is loaded:

HistoryFiles.Load();

Populate a menu list:

 
private void RefreshMenuHistory()
{
    mnuHistory.ClearLinks();
           

    for (int i = 0; i < moApp.HistoryFiles.Files.Count; i++)
    {
        BarButtonItem bt = new BarButtonItem();
        string[] lInfo = moApp.HistoryFiles.Files[i].Split('|');

        try
        {
            bt.Caption = lInfo[1];
            bt.Hint = "Dir: " + lInfo[0];
            bt.Tag = i;

            if (Directory.Exists(lInfo[0] + lInfo[1]))
            {
                mnuHistory.AddItem(bt);
                bt.ItemClick += bt_ItemClick;
            }
            else
                moApp.HistoryFiles.Files.RemoveAt(i);
        }
        catch (Exception)
        {
            moApp.HistoryFiles.Files.RemoveAt(i);
        }
    }         
}

In this case, if a file does not exist the item is removed from the list.

Add new items on the list, when you open a project:

 
HistoryFiles.Add(ProjectsDir + "|" Project.ProjectName);
HistoryFiles.Save();


I end my explanation here, for the moment you have to enjoy.

Thursday, December 19, 2013

NetOffice an MsWord class Wrapper


In order to produce a Word document without MsOffice installed, I recommend to use this suite of libraries, that are Open Source (http://netoffice.codeplex.com/). There are plenty of reasons that convincing me that this is a good  way to interact with MsOffice, I let you to check if these are good enough also for you. By the way I had prepared a C# Class with an example to try. This class wraps very typical functionalities in document generation.

These functions are simple and intuitive:

  • Open and Create a Document.
  • Writing
  • Attach a Picture
  • Generating a Table
  • Text Formatting  
Many other can be added and you can improve this class very easy as you prefer.
First of all you have to download the package on your pc (http://netoffice.codeplex.com/releases/view/70943) and install it, then it is enough to find the dlls mentioned below, and attach that to the project.


Please set the “Embed Interop Types” property to False.


In the example I have prepared, it is possible to find every specific functionalities I wrote before. So with very few code here the demonstration:


List lPersons = new List();
lPersons.Add(new Person("John","Anderson", 43));
lPersons.Add(new Person("Lorenz", "Bullock", 36));
lPersons.Add(new Person("Frank", "Carlson", 28));
lPersons.Add(new Person("Frederick", "Doson", 33));

WordWrapper oWord = new WordWrapper();

if (File.Exists(sFile))
  oWord.OpenDocument(sFile);
else
  oWord.CreateDocument(sFile, false);

oWord.AddPicture(sDir + "image.png", true);

oWord.SetFont("Arial", WdColor.wdColorDarkRed, 14, true);
oWord.WriteText("1. Hello World!");

oWord.PrintTable(lPersons);
            
oWord.Save();
oWord.CloseAndDispose();
oWord.ShowDocument(sFile);

One thing I appreciate more is that the API is Syntactically and semantically identical to the Microsoft Interop Assemblies so if you before had used Microsoft API this is “easy peasy lemon squeezy”! The first thing to do is to create an Application object and disable all messages:

public WordWrapper()
{
  moApp = new Word.Application();
  moApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
}

Once you have the Application Member moApp you can manipulate the Word Documents:

public void OpenDocument(string sFileName)
{
  if (moApp == null) return;
  msFileName = sFileName;
  moDoc = moApp.Documents.Open(sFileName);
}

Your Document is now open and can be used to interact.

public void AddPicture(
string sFileName, 
bool bNewParagraph = true, 
int iWidth = 0, 
int iHeight = 0)
{
  if (!File.Exists(sFileName)) return;
  if (moApp == null) return;
  if (moDoc == null) return;

  var shape = moApp.Selection.InlineShapes.AddPicture(sFileName, true, true);

  if (iWidth > 0)
    shape.Width = iWidth;
  if (iHeight > 0)
    shape.Height = iHeight;

  if (bNewParagraph)
    moApp.Selection.TypeParagraph();
}

download here!

Thursday, September 12, 2013

Cripto Class


Some years ago after reading the Simon Singh book's "The Secret History of Codes and Code-breaking" I created my first Cripto class. The main idea was a kind of Enigma code, with simple tricks to improve it. In the time this class was used always more. In this article I present the class and the contained ideas.

public class Cripto
    {
        const int SIZE_ALPHABET = 256;
        const int LOWER_BOUND = 32;

        byte[] msKeyWord = new byte[] {0x49, 0x76, 0x60, 0x6e, 0x31, 0x4d, 
            0x3f, 0x60, 0x78, 0x43, 0x64, 0x65, 0x74, 0x5b, 0x6e, 0x7f};
        string msLastCriptedStr = "";

This class uses a key phrase (KP) that can have lenght as you want, in the example is 13 chars as default.
For security reason this key phrase is expressed in Hexadecimal and stored on an array. The german army had a book with these key phrases, every day had a different phrase. There is a nice movie directed by Michael Apted from a screenplay by Tom Stoppard about "Enigma" that  I suggest to watch. Alan Touring was also involved in decoding it and many spy stories talk about that tricky code.

It is possible to change this KP when the object is created.

public Cripto(string aKeyWord)
        {
            if (aKeyWord != "")
                msKeyWord = System.Text.Encoding.Unicode.GetBytes(aKeyWord);
        }

The main methods are simply two: Encrypt() and Decrypt() they returns as result a string.



public string Encrypt(string aText)
        {
            int apos; //alphabet pos
            int npos; //new coded pos
            int kwi = 0; //KeyWord Index
            int kwa; //KeyWord alphabet
            string s = ""; //coded string

            int l = aText.Length; //string length
            for (int i = 0; i < l; i++)
            {
                kwa = (int)msKeyWord[kwi]; //choose cripto alphabet
                kwi = kwi + 1; //set keyword index
                //if last key character restart from first position
                if (kwi == msKeyWord.Length) kwi = 0;

                apos = (int)aText[i];
                npos = (kwa + apos) % SIZE_ALPHABET;
                s = s + (char)npos; //multi alphabet traslation                
            }

            msLastCriptedStr = s;
            return s;
        }

public string Decrypt(string aText)
        {

            int l; //i=string pos;
            int apos; //alphabet pos
            int npos; //new coded pos
            int kwi = 0; //KeyWord Index
            int kwa; //KeyWord alphabet
            string s = ""; //coded string

            l = aText.Length; //string length
            for (int i = 0; i < l; i++)
            {
                kwa = (int)(msKeyWord[kwi]); //chose decripto alphabet
                kwi = kwi + 1; //set keyword index
                //if last key character restart from first position
                if (kwi == msKeyWord.Length) kwi = 0;

                apos = (int)(aText[i]);
                npos = (SIZE_ALPHABET + apos - kwa) % SIZE_ALPHABET;
                s = s + (char)(npos); //multi alphabet traslation                
            }

            return s;
        }

How the algorithm works: Every chars of your string is replaced with one new letter. This letter is taken each time from different alphabet (it depend on KP). The char position is the same of the examined input string character. The KP provides a sequence of index that are the characters position of the first alphabet.



Friday, September 6, 2013

Message Grid Component


Another component that cannot miss on your toolbox is a Form where to append all messages.
When I talk about messages, I mean debug messages, user messages, error messages. This form is used, typically, on automation program or calculation and analysis application but also in many other contexts.
By the way, it is really a useful component. What it makes, it is simply said: first of all defines some methods to append a message on a list and visualize it, then allows to save all rows on a text file, a log file.



Message Class

A Message class has four main properties:
• The Type that can be an enumerative value Error, Warning or Infos
• A Code. Often is useful assign a code to each message.
• A Text: the description.
• A Count: For example if an error appears systematically, it can be useful update a counter and a date, insted to append it again. While on file the message is always saved.

MessagesCollection Class

The MessagesCollection class, manage a list of Message objects with the possibility to limit a number of these. It save every new message on a log text file.
This is a constructor declaration:

public MessagesCollection(string asFileName, int aiMaxElements)


It defines a simple method to add a message:
public void Add(EnumMessageType aoType, string asCode, string asMessage, bool abAddOnlyIfNew = true)

or to clear a list of these:
public void Clear()

public void Clear(string asCode)


MessagesGrid Control

At the end, we have a grid for a front end visualization. For the developer it is possible to access the MessagesCollection object by the property Messages, it can use the Add method as well. All other user activity can be done from the Form.


download sample

Tuesday, May 7, 2013

Working Progress Form



On this post I documented how to realize a working progress Window, with two progress bars. One bar for a potential main loop and another one for a secondary loop. For example, this could be useful if you need to import many file with many records, in this case the main bar represent the file and the second bar a current record. Another typical situation is when you have to compute an algorithm that require two nested loops etc..
This Window must be independent in order to show a progression but also to control the process, allowing to Cancel the current computation.
Above How I designed a Window.

In this example, I have omitted the control part, like Cancel or Stop management.
To be independent the Window must be a Thread that live a part, so define a Thread object inside the class.

public partial class WorkInProgress : Form
{
   public static Thread moThread = null;
   public static Form moOwner = null;
   public static WorkInProgress moForm = null;

The idea is to have a unique static Class so it should be easy to use it with proper static methods like:

static public void StartFormAsThread(Form oOwner)
{
    moOwner = oOwner;
    moThread = new Thread(new ThreadStart(ShowForm));
    moThread.Start();
}
static public void StopFormAsThread()
{
    if (moForm == null) return;
    moThread.Abort();
    moThread = null;
    moOwner.Invoke((MethodInvoker)delegate
    {
        moForm.Close();
        moForm = null;
        moOwner = null;
    });
}

You can see that no Form is initialized or showed directly with this method, this is because there is another method that is involved in this, see ShowForm(). When thread starts a ShowForm() is called.
The purpose of UpdateProgress() is to show a Window, and refresh the bar progression:

public static void UpdateProgress(ProgressArgs arg)
{
    if (moForm == null) return;
    try
    {
        moForm.pbFiles.Minimum = arg.FileMin;
        moForm.pbFiles.Maximum = arg.FileMax;
        moForm.pbFiles.Value = arg.FilePos;
        moForm.pbFiles.Refresh();

        moForm.pbRows.Minimum = arg.Min;
        moForm.pbRows.Maximum = arg.Max;
        moForm.pbRows.Value = arg.Pos;
        moForm.pbRows.Refresh();

        moForm.labInfos.Text = arg.FileName;
        moForm.labInfos.Refresh();
        moForm.BringToFront();
    }
    catch (Exception ex)
    {
        MessageBox.Show(arg.FilePos.ToString() + ", " + arg.Pos.ToString());
        // throw;
    }
}

static public void ShowForm()
{
    moForm = new WorkInProgress();
    //moForm.TopMost = true;
    moForm.ShowDialog();
}

static public void StopForm()
{
    if (moForm == null) return;
    moForm.Close();
    moForm = null;
    moOwner = null;
}


It Accept, as input, a ProgressArgs object with all information needed. Here a simple example how to use it:

private void btnThread_Click(object sender, EventArgs e)
{
    const int MAX_FILE = 5;
    const int MAX_REC = 3600;
    int iPerc = 0;
    WorkInProgress.StartFormAsThread(this);

    for (int j = 1; j <= MAX_FILE; j++)
    {
        for (int i = 1; i <= MAX_REC; i++)
        {
            iPerc = (int)((i/(float)MAX_REC ) * 100 );
            Debug.Print(string.Format("record: {0} ({1}%) file: {2}", i, iPerc, j));
            WorkInProgress.UpdateThreadProgress(new ProgressArgs(MAX_FILE, 0, j, 100, 0, iPerc, "file: " + j.ToString()));
        }
    }

    WorkInProgress.StopFormAsThread();
}


/// 
/// Argument class used to monitoring the computation progress 
/// 
public class ProgressArgs : System.EventArgs
{
    public int FileMax;
    public int FileMin;
    public int FilePos;
    public int Max;
    public int Min;
    public int Pos;
    public string FileName;

    public ProgressArgs()
    {
        Max = 0;
        Min = 0;
        Pos = 0;
        FileMax = 0;
        FileMin = 0;
        FilePos = 0;
        FileName = "";
    }

    public ProgressArgs(int filemax, int filemin, int filepos, int max, int min, int pos, string fileName)
    {
        Max = max;
        Min = min;
        Pos = pos;
        FileMax = filemax;
        FileMin = filemin;
        FilePos = filepos;
        FileName = fileName;
    }
}