Thursday, November 20, 2014

Enterprise Library 6 Exception Logging Tutorial

Hi everyone,

Since my last post it looks like the problems with EntLib6 and NuGet have been resolved so I wanted to give you all a simple tutorial on how to get exception logging working with your Visual Studio 2013 application.

Step 1: Install EntLib6 from NuGet package manager.


Step 2: Add reference for System.Configuration


Step 3: Setup the App.config


Add Application Settings
Add Configuration Sources
Add Exception Handling Settings
Add Logging Settings

Configure an Exception Handling Policy.  I used no post handling action "none"


Add a Handler


Make note of the logging Categories.  You can create your own but I simply used the General Category for this step by step guide.


Save the config.


Now you need to add some code to the Program.cs file to register a Logging Factory.  You can simply copy and paste the following code into your Main() method.

            IConfigurationSource source = ConfigurationSourceFactory.Create();

            LogWriterFactory logwriterFactory = new LogWriterFactory(source);
            var logWriter = logwriterFactory.Create();
            Logger.SetLogWriter(logWriter);

            var exceptionPolicyFactory = new ExceptionPolicyFactory(source);
            var exceptionManager = exceptionPolicyFactory.CreateManager();
            ExceptionPolicy.SetExceptionManager(exceptionManager);

            Application.ThreadException +=
                Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException +=
                CurrentDomain_UnhandledException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

Now you have to add two additional methods in order to catch, handle and log Thread Exceptions and Unhandled Exceptions. Copy and paste the following below you Main() method.

         static void Application_ThreadException(object sender,                                   System.Threading.ThreadExceptionEventArgs e)
        {
            ExceptionPolicy.HandleException(e.Exception, "UI Policy");
            MessageBox.Show("An unexpected exception occurred"
                    + " and has been logged. Please contact support." + e.Exception.Message);

        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception)
            {
                ExceptionPolicy.HandleException((Exception)e.ExceptionObject, "Unhandled Policy");
                MessageBox.Show("An unhandled exception occurred"
                    + " and has been logged. Please contact support.");

            }
        }



Finally you need to add a try and catch around some code.  Inside the catch add the following code.

                bool rethrow = ExceptionPolicy.HandleException(ex, "UI Policy");
                if (rethrow)
                {
                    throw;
                }
                MessageBox.Show("Error handled and logged to the event viewer. " + ex.Message, "Failure",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);


Now you can run and test it out!

NOTE; When you go to test this out for the first time, you will have to save your application and close it.  You then have to open Visual Studio 2013 as an administrator.  So right click the VS2013 shortcut and click runas administrator.  Now open your project and test it out.

What will happen is a MessageBox will alert you that an exception was caught and has been logged.  The way this example is setup the exceptions will be logged in the EventViewer.  To view the error log simply go to start, in the search bar type event viewer and open it.  Once you have opened the event viewer, expand the Windows Logs and click on Application.  You will see an Error with the Source, "Enterprise Library Exception Logging".

I hope this helps those who are looking for an exception logging solution.  Enterprise Library 6 is very nice.  There wasn't a lot of documentation out there when I first started using EntLib6 with Visual Studio 2013 so I had a somewhat difficult time getting it to work initially but once I did it has worked flawlessly.

Peace!

Wednesday, April 23, 2014

Installation of Enterprise Libraries Version 6 on Visual Studio 2013

It's been a while since my last post.  I have started a new job which has kept me pretty busy.  The project I am currently working on needed an error tracking and reporting system.  I chose to use EntLib6 as a means to my solution.  During the installation through the NuGet package manager I started running into errors and problems.  NuGet does not have the latest version available so you must download them manually.  Below I will share the links that got me going with EntLib6.


Download From Here:
http://www.microsoft.com/en-us/download/details.aspx?id=38789

NOTE: this install will only work for Visual Studio 2010 and 2012.  To get this to work for VS2013 follow this link:
http://blog.sublogic.com/2012/04/11/getting-your-favorite-visual-studio-2010-extension-to-run-in-visual-studio-11/

Special thanks to James Manning!

Hope this helps someone having issues getting Enterprise Library installed for Visual Studio 2013.  Until my next post, be well.

Tuesday, January 21, 2014

[Report #1] Populate ASP DropDownList Using a Database

In this blog post I am going to demonstrate how to use an ASP DropDownList with a database.  This will be the first part of a multi-part series on simple, on the fly, ad-hoc reporting.

This example was developed using Visual Studio Express 2012 Web.  The project is a WebForms project but this can be easily used with a MVC project as well.  This example uses the Northwind Sample Database from the SQL Server 2000 Sample Databases.  You can download and get instruction on how to install the Northwind database here.  You can also use the newer AdventureWorks database which can be found here.

First we need to create a webforms page with an ASP DropDownList.

Report.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="report.aspx.cs" Inherits="reports.report" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="text/javascript" src="../Scripts/report.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <asp:DropDownList ID="ddl_Tables" runat="server"
                    ClientIDMode="Static"></asp:DropDownList>
</asp:Content>


Now in the C# aspx.cs file we will open a connection to a database, populate a List<string> and set it as the DropDownList's DataSource.

Report.aspx.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace reports
{
    public partial class report : System.Web.UI.Page
    {
        private SqlConnection myConnection;
        private string myConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    OpenConnection();
                    populateTablesDdl(sender, e);
                }
                catch
                {
                    throw;
                }
            }
        }

        protected void populateTablesDdl(object sender, EventArgs e)
        {
            List<string> tableNames = new List<string>();
            try
            {
                using (
myConnection)
                {
                    OpenConnection();
                    DataTable schema =
myConnection.GetSchema("Tables");

                    foreach (DataRow row in schema.Rows)
                    {
                        if (!row[2].ToString().Contains("_dss"))
                        {
                            tableNames.Add(row[2].ToString());
                        }
                        else
                        {
                            //nothing at this time
                        }
                    }
                    ddl_Tables.DataSource = tableNames;
                    ddl_Tables.DataBind();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            ddl_Tables.Items.Insert(0, new ListItem("<Select Table>", " "));
        }

        protected void OpenConnection()
        {
            // Create a connection object
           
myConnection= new SqlConnection();

            // Create the connection string
           
myConnectionString= @ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
           
myConnection.ConnectionString = myConnectionString;

            // Open the connection
           
myConnection.Open();
        }
    }
} 


Note: There's a method and an if statement I need to explain. First, myConnection.getSchema("Tables") is used to populate a DataTable. There are different ways to get the database tables but the getSchema method is clean. When I develop a webapp, one tool I often use is Microsoft SQL Data Sync (Preview). One thing about Data Sync (Preview) is that it makes copies of the User Tables with a _dss suffix. I use if(!row[2].ToString().Contains("_dss")) to filter out these tables.  It should work fine with your tables unless your naming convention uses _dss.

On my next post I will build on this example and show how to populate an ASP ListBox with the RowNames of any table the user selects. Until next time, keep calm and carry on.

Friday, January 17, 2014

Using JavaScript To Collect Data In ASP Table

This builds on my first post which demonstrates how to generate tables using C#.  If you haven't read my first post that is perfectly fine.  I have written my posts so each one is complete on its own.  Please click the following link if you would like to read my first post Dynamically Creating asp Tables in C#.

This example as with all of my .NET posts was written using Visual Studio Express 2012 Web.  This was developed in a webforms project but this can be used in any MVC project as well.

We first start with a table with each row containing an ASP CheckBox, Label, and HiddenField element.

Tables.aspx

<script src="../Scripts/reporting.js" type="text/javascript"></script>
    <input type="submit" name="button1" value="show table" id="button1" />
    <table id="table1">
 <tr>
  <td>
     <input id="cb_0" type="checkbox" name="cb_0" />
  </td>
  <td>
     <span id="lbl_0">0</span>
     <input type="hidden" name="hidden_0" id="hidden_0" value="0" />
  </td>
 </tr>
 <tr>
  <td>
     <input id="cb_1" type="checkbox" name="cb_1" />
  </td>
  <td>
     <span id="lbl_1">1</span>
     <input type="hidden" name="hidden_1" id="hidden_1" value="1" />
  </td>
 </tr>
 <tr>
  <td>
     <input id="cb_2" type="checkbox" name="cb_2" />
  </td>
  <td>
     <span id="lbl_2">2</span>
     <input type="hidden" name="hidden_2" id="hidden_2" value="2" />
  </td>
 </tr>
 <tr>
  <td>
     <input id="cb_3" type="checkbox" name="cb_3" />
  </td>
  <td>
     <span id="lbl_3">3</span>
     <input type="hidden" name="hidden_3" id="hidden_3" value="3" />
  </td>
 </tr>
 <tr>
  <td>
     <input id="cb_4" type="checkbox" name="cb_4" />
  </td>
  <td>
     <span id="lbl_4">4</span>
     <input type="hidden" name="hidden_4" id="hidden_4" value="4" />
  </td>
 </tr>
</table>
    <input
      type="submit"
      name="button2"
      value="get values"
      onclick="getValues(event);"
      id="button2" />
    <input type="hidden" name="hidden1" id="hidden1" />


Again, if you read my first post Dynamically Creating asp Tables in C# this would be the table created by the C# code behind. Now we want to have the users select checkbox(es) and click a button to get all the values of the rows the user checked. There are a few, actually many ways to approach this really. You could build an array and add or remove items to and from it the moment the user checks or unchecks a checkbox using the onchange event handler and checking if the checkbox was checked. I didn't like this approach. I wanted the user to make their selection, then have the selections gathered and passed to the hidden field all at once. To do this we need to use a loop to iterate through the table.

Tables.js

function addNames(event) {
    event.preventDefault();

    var hidden_names = document.getElementById('hidden1');
    var table = document.getElementById('table1');
    var inputs = table.getElementsByTagName('input');
    var inputsPerRow = 
        table.rows[0].getElementsByTagName('input').length;

    hidden_names.value = '';

    for (i = 0; i < inputs.length; i+=inputsPerRow) {
        if (inputs[i].type === 'checkbox') {
            if (inputs[i].checked) {
                if (
                       hidden_names.value == null || 
                       hidden_names.value == '') {
                    hidden_names.value = inputs[i+1].value;
                }
                else if (hidden_names.value != null) {
                    hidden_names.value += 
                        ', ' + inputs[i + 1].value;
                }
                else {
                    //nothing for now
                }
            }
        }        
    }
    alert(hidden_names.value);    
}  
This function gets all of the table input elements using table.getElemetnsByTagName('input'). This creates a list of elements that have an <input> tag. Note: When I first thought of this I tried not using <asp:HiddenField> and only used <asp:Label> in my table and thought I would be able to access the label text or value. What I learned was asp labels do not render as anything but text. I would have to use table.getElementsByTagName('span') and then iterate through those checking each element. I felt that was wasteful so I simply used the HiddenField..

In my next post I will show how to populate dynamically generated tables using input from a SQL database. 

Dynamically Creating asp Tables in C#

For a project I was tasked with at work I needed to program something that had to generate tables on the fly based on user input, accept user selections via textboxes on that table and loop through the table gathering the users' selections and append that to an asp hiddenfield to be passed back to C# codebehind.  I had the concept in my head on how to program it but I did run into some problems and didn't see much documentation on the web on what I wanted to do so I decided to start a blog.  This is my first blog and first post.  Hope I can be clear and to the point.  Enjoy!

I am programming using Visual Studio Express 2012 Web Edition.  The project I am working with is a webforms project.  This concept can be easily translated to any MVC project.  First off we need to generate the table programmatically and assign meaningful, unique names to the table elements. Using a simple for loop I am creating a table containing an asp CheckBox, Label, and HiddenField with a value in each row.

Tables.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Tables.aspx.cs" Inherits="Project.Tables" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <script src="../Scripts/table.js" type="text/javascript"></script>
    <asp:Button ID="button1" runat="server" Text="show table"
        ClientIDMode="Static"
        OnClick="createTable"/>
    <asp:Table ID="table1" runat="server"
        ClientIDMode="Static"></asp:Table>
    <asp:Button ID="button2" runat="server"
        Text="get values"
        ClientIDMode="Static"
        OnClientClick="addNames(event)" /> //ignore this

                                           //javascript function
                                           //for now
    <asp:HiddenField ID="hidden1" runat="server" //also ignore

                                                 //this for now
        ClientIDMode="Static" />
</asp:Content>

Pretty simple.  We just create a webform(with or without masterpage), added a couple of buttons, a table element, and one hidden field.  We will use this hidden field to store values later.

Tables.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Project
{
    public partial class test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //do nothing
            }
        }

        protected void createTable(object sender, EventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {
                TableRow tr = new TableRow();

                TableCell tc1 = new TableCell();
                TableCell tc2 = new TableCell();

                HiddenField hiddenField = new HiddenField();
                hiddenField.ID = "hidden_" + i;
                hiddenField.Value = i.ToString();
                hiddenField.ClientIDMode = 

                    System.Web.UI.ClientIDMode.Static;

                Label lbl = new Label();
                lbl.ID = "lbl_" + i;
                lbl.Text = i.ToString();
                lbl.ClientIDMode = 

                    System.Web.UI.ClientIDMode.Static;

                CheckBox cb = new CheckBox();
                cb.ID = "cb_" + i;
                cb.AutoPostBack = false;
                cb.ClientIDMode = 

                    System.Web.UI.ClientIDMode.Static;

                tc1.Controls.Add(cb);
                tc2.Controls.Add(lbl);
                tc2.Controls.Add(hiddenField);

                cb.Attributes.Add("onchange",

                    "Javascript:addNames(event)");

                tr.Controls.Add(tc1);
                tr.Controls.Add(tc2);

                table1.Controls.Add(tr);
            }
        }
    }
}

Method createTable will build our table row by row, adding the controls to the cells and cells to the rows.  Note, if (!IsPostBack) this will prevent the page from completely reloading and resetting data. If you do not understand IsPostBack please follow this tutorial and you will get it, http://www.codeproject.com/Articles/12810/The-Intricacies-of-the-IsPostBack-If-Block-in-ASP

At this point the webapp will create a table of any length you want with a checkbox, label, and a hiddenfield with a value.  These checkboxes and hiddenfields all have unique names and can be accessed from the codebehind C#.

Well this was my first blog and first post.  Next post I will show how to get the value of the hidden fields if the checkbox in the row is checked and append the hiddenfields' values to one hidden field that will store them all using JavaScript!