HTML to PDF

Have you ever wanted a function to convert HTML to PDF? It is really easy. A good use of this is when you have a resume on your website and you want to create a download of it as a PDF. Mind you; you will have to properly format your resume so it looks good in both cases. Not the easiest job, but totally worth while to have a resume download created on demand. Continue reading HTML to PDF

The Story of C# Meeting AngularJS

Most of you already know that I still like my WebForms. People have argued that using AngularJS with WebForms is pointless, but I say NA! It makes the user experience a little bit smoother.

In this blog I will show you how to create a table that can be sorted and paged using AngularJS. I chose not to use a webserivce as I did not feel like this warranted the extra overhead and code. I wanted to keep this absolutely simple. I would have used a webserivce had I been creating an API for others to use. This is also a project that is ultimately using WebForms, had I been doing an MVC project; webservices would have been a better choice.

Is this the best way; probably not! This is my first run with this, so I am doing it the way I know and the way I find the easiest to manipulate for my purpose.
Continue reading The Story of C# Meeting AngularJS

Starting a WebForm Project

    I started working in the DotNet while it was in the Beta stage. Ewe Beta! Since then I discovered there is more than one way to tackle a start of a project and I have perfected it for my purpose.

    I would suggest starting with an empty project rather than letting Microsoft build you one. By you creating an empty project you are able to control what goes in it. The “Web Forms”template that Microsoft offers has so many files and structure that you would likely not even use.
    Continue reading Starting a WebForm Project

Auto-Link Using Regular Expressions

Auto-LinkingI was recently asked if I could automatically turn website text (ex: www.google.com ) into HTML hyperlinks.  My first thought was ah CRAP!  I also wondered why they could not use the link tool in the editor, but they asked so I delivered. With about 5 minutes on Google, I found the perfect solution that worked for me.

Mind you I was working in C# for this, but since it is a regular expression solution; it will apply to virtually any language.  The one change that I had made from the original code was to add in a piece that also auto-linked when the text included “http://www.”.  You may or may not want the extra addition that I had made.

Continue reading Auto-Link Using Regular Expressions

Building a C-Sharp Class

I have created this example of a C# class to demonstrate one way of creating a basic class cbject representing one employee.  This class could be used as a starting point for just about any object.

Take note that there are no business rules in this example.  It is of my opinion that you create a basic object first and create a business class second which extends the basic object.  In the business class you may put an EmployeeNumber generator, MaxLength controls on the fields, Phone number validation and other rules that may apply based on your business practices.  A business class will be demonstrated in a later blog.

You may also want to create a collection class.  A collection class or a manager class would manage a collection of objects with Add, Remove, Select, Sort type functions.  This too will be demonstrated in a later blog.

    /// <summary>
    /// Class Object Representing Employee
    /// </summary>
    public class Employee : Dictionary<String, Object>, IEmployee
    {
        // ***********************| Properties |***********************
        /// <summary>
        /// Employee Number
        /// </summary>
        public String EmployeeNumber
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's First Name
        /// </summary>
        public String FirstName
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Last Name
        /// </summary>
        public String LastName
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }
        /// <summary>
        /// Employee's Address Line 1
        /// </summary>
        public String Address1
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Address Line 2
        /// </summary>
        public String Address2
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's City
        /// </summary>
        public String City
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Province / State
        /// </summary>
        public String Province
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Country
        /// </summary>
        public String Country
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's ZIP / Postal Code
        /// </summary>
        public String ZipPostal
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Home Phone Number
        /// </summary>
        public String HomePhoneNumber
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Cell Phone Number
        /// </summary>
        public String CellPhoneNumber
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Full Name ( ReadOnly )
        /// </summary>
        public String FullName
        {
            get { return String.Format("{0}, {1}", FirstName, LastName); }
        }

        /// <summary>
        /// Employee's Start Date
        /// </summary>
        public DateTime StartDate
        {
            get { return (DateTime)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's TerminationDate ( Nullable )
        /// </summary>
        public DateTime? TerminationDate
        {
            get { return (DateTime?)this[GetName()]; }
            set { this[GetName()] = value; }
        }
        // ***********************| Constructor(s) |***********************
        /// <summary>
        /// Constructor
        /// </summary>
        public Employee()
        {
            Initialize();
        }

        /// <summary>
        /// Employee
        /// </summary>
        /// <param name="employeeNumber">Initial Employee Number</param>
        public Employee(String employeeNumber)
        {
            Initialize();
            EmployeeNumber = employeeNumber;
        }
        // ***********************| Methods |***********************

        /// <summary>
        /// Initialize the Class
        /// </summary>
        private void Initialize()
        {
            EmployeeNumber = "";
            FirstName = "";
            LastName = "";
            Address1 = "";
            Address2 = "";
            City = "";
            Province = "";
            Country = "";
            ZipPostal = "";
            HomePhoneNumber = "";
            CellPhoneNumber = "";
        }

        /// <summary>
        /// Get Method Name
        /// </summary>
        /// <returns>First and Last Name</returns>
        public String GetName()
        {
            StackTrace stackTrace = new StackTrace();
            StackFrame stackFrame = stackTrace.GetFrame(1);
            MethodBase methodBase = stackFrame.GetMethod();
            return methodBase.Name.Replace("set_", "").Replace("get_", "");
        }

        /// <summary>
        /// Re-initializes the Class
        /// </summary>
        public void Reset()
        {
            this.Clear();
            Initialize();
        }
    }

What Languages do I Use

I was recently asked what I use to develop software and websites. I mostly use DotNet Technologies as it is often interchangeable between websites, web applications and desktop applications. I can often use the same data access classes and business logic between multiple platforms. I find that DotNet allows me to easier structure objects visually and logically.  I prefer to develop using C-Sharp, but I get requests to use VB.NET and J-Sharp on a regular basis.

When I went to college, I had learned C, Pascal, COBOL and some Mainframe language that I cannot remember.  Upon graduating I taught myself VisualBasic 3, RPG.  My first programming job was Visual COBOL.  I had created a company in the Caribbean Islands programming public utility and insurance software in RPG.   I can honestly say since I sold my shares of the company, I cannot foresee myself developing in RPG again.

Why don’t I use PHP?  Well I do use PHP, but for specific purposes and upon request by a customer. A specific purpose is when I create a WordPress site or other content driven sites. I will not often create a website or web application from scratch using PHP as Microsoft made ASP.NET easy for rapid development.

Do I use JAVA? Yes; I do believe there are cases where JAVA is still relevant. JAVA is still a good tight platform for developing small single purpose applications.  I have used JAVA 3 times in the past 2 years for applications that I believe fit the bill well.

Now, I am curious;  What do you use and why?

Shortcut To Creating Properties in C-Sharp – Revisited

Based on my earlier an post, a I had a question about my technique and if there was a benefit, or could you use MethodBase.GetCurrentMethod().Name. Truthfully I did not know the answer until I tried it. I found this new way works, but I also find it is a little tougher to look at style-wise. You need to use stack frames if you nest the routine like I had in my original post.

public class ErrorLogRecord
    {
        public Hashtable _hsh = new Hashtable();

        public DateTime DateOfOccurance
        {
            get { return (DateTime?)_hsh[MethodBase.GetCurrentMethod().Name.Replace("set_", "").Replace("get_", "")] ?? DateTime.Now; }
            set { _hsh[MethodBase.GetCurrentMethod().Name.Replace("set_", "").Replace("get_", "")] = value; }
        }
        public String ErrorText
        {
            get { return (String)_hsh[MethodBase.GetCurrentMethod().Name.Replace("set_", "").Replace("get_", "")]; }
            set { _hsh[MethodBase.GetCurrentMethod().Name.Replace("set_", "").Replace("get_", "")] = value; }
        }
    }

Original Referenec Shortcut To Creating Properties in C-Sharp

Shortcut To Creating Properties in C-Sharp

I was looking for an easy and consistent way of creating properties for classes.  I sometimes find that it can be a long drawn out process creating 5 to 100 properties for database classes.  Here is a quick example of what I did.
You will need the following references to make this example work.

  1. System.Diagnostics;
  2. System.Reflection;
  3. System.Collections;
public class ErrorLogRecord
{
     Hashtable _hsh = new Hashtable();
     public DateTime DateOfOccurance
     {
          get { return (DateTime?)_hsh[GetName()] ?? DateTime.Now; }
          set { _hsh[GetName()] = value; }
     }        
     public String ErrorText
     {
          get { return (String)_hsh[GetName()]; }
          set { _hsh[GetName()] = value; }
     }

     public String GetName()
     {
          StackTrace stackTrace = new StackTrace();
          StackFrame stackFrame = stackTrace.GetFrame(1);
          MethodBase methodBase = stackFrame.GetMethod();
          return methodBase.Name.Replace("set_", "").Replace("get_", "");        
     }
}

While this method is probably not perfect and could be argued there is a better way, this seems to satisfy the need. I would welcome alternatives.

Alternate Reading: Shortcut To Creating Properties in C-Sharp (revisited)

Why use LINQ

I was asked “Why I never used LINQ?”   I guess the real answer was, I never thought about it.  I really had no good reason for not using LINQ other it was new and unfamiliar.  When I finally used LINQ; I found I was getting rid of old habits and making code simpler and cleaner.

Example of code written in C#:

foreach (Charges charge in (ary))
{
if (charge.ChargeDescription.ToLower().Contains("total"))
{
ary.Remove(charge);
}
}

Code converted to LINQ:

var rslt = from Charges charge in ary where charge.ChargeDescription.ToLower().Contains("total") select charge;

while(rslt.Count() > 0)
{
Charges chargese = rslt.ElementAt(0);
ary.RemoveAt(ary.IndexOf(Chargese));
}

To this day I still use C# with a little LINQ to simplify my code.   I use LINQ for validations, quick look up and data manipulations.  It is definitely a change from what I used to do, but worth learning.  What I like about the above code is I had eliminated the nested if without complicating the code.

Caching Locally

One of the applications I have been working recently is a windows based application. Most things that the user keys into the system results in a database hit validation. To cut back on this I have implemented classes that assist in caching to the user’s local system. Based on the user’s habits, it will cache what the user uses commonly.

I am using a datatable in this example, but you could use a dictionary object. Should you choose to use a dictionary object, you could use LINQ to query the object. You could also make the caching class an extension which could cut down on some code an make it a little cleaner.

At the end of the day, this is one example only of what could be done.

Class Example

public class CurrencyCodes
private static CurrencyCodes _instance; // Instance Of Self

private static DataTable dt = new DataTable("CurrencyCodes");

public static CurrencyCodes Instance
{
get
{
if (_instance == null)
{
_instance = new CurrencyCodes();
}
return _instance;
}
}

private CurrencyCodes()
{
dt.Columns.Add("CurrencyCode", typeof(String));
dt.Columns.Add("LastUpdated", typeof(DateTime));
}

public String Search(String value)
{
DataRow[] rows = dt.Select("CurrencyCode='" + value + "'");
if (rows.Count() == 1) return value;
return "";
}

public void Add(String value)
{
DataRow row = dt.NewRow();
row["CurrencyCode"] = value;
row["LastUpdated"] = DateTime.Now;
dt.Rows.Add(row);
}

public void ClearCache()
{
dt.Rows.Clear();
}

public void LoadCache(String xml)
{
StringReader theReader = new StringReader(xml);
dt.ReadXml(theReader);
}

public String SaveCache()
{
using (MemoryStream ms = new MemoryStream())
{
dt.WriteXml(ms);
ms.Position = 0;

StreamReader sr = new StreamReader(ms, System.Text.Encoding.UTF8);

return sr.ReadToEnd();
}
}
}

Calling the class

Directory.SetCurrentDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
if (!Directory.Exists("YourSoftwareCache"))
{
Directory.CreateDirectory("YourSoftwareCache");
}

if (File.Exists("CurrencyCodes.XML"))
CurrencyCodes.Instance.LoadCache(File.ReadAllText("CurrencyCodes.XML"));

CachedCurrencyCodes cachedCurrencyCodes = CachedCurrencyCodes.Instance;
CurrencyCode = cachedCurrencyCodes.Search(Criteria);

Note Comments have been stripped to clean up the posting. Always Comment Your Code.