My Notes on Exception Handling

First, I want to thank my good friend Chew Min for introducing the book, “C# 6.0 and the .NET 4.6 Framework” by Andrew Troelsen and Philip Japikse to me. It is a very good book which includes basics of C# and .NET framework every developer should know. I am going to share my notes on the chapter, “Understanding Structured Exception Handling”.

  • There are mainly 3 types of errors which can be included in a program
    • Bugs – errors made by the programmer
    • User Errors – Errors in user inputs
    • Exceptions – Runtime errors
  • Catch all possible exceptions in production level projects
  • You can throw and handle exceptions, when you know about certain possible occurrence of errors. The keywords used for this are try, catch, throw, finally and when (C# 6.0)
  • Exception class implements
    • _Exception – .NET exception to be processed by an unmanaged code base
    • ISerializable – Exception object to be persisted across boundaries
  • Properties in  Exception class
    • Data – IDictionary type, programmer defined info about the exception (key-value pair)
    • HelpLink – Url to a help page or a document
    • InnerException – information about previous exceptions
    • Message – error message
    • Source – gets/sets name of the assembly
    • Stacktrace – sequence of calls triggered exception, this is useful for debugging to dump the error to external log
    • TargetSite – return MethodBase object, describe information about the method that threw the exception (ToString() will give this)
  • Throwing a new exception
    • throw new Exception(“message”);
  • You are not required to handle each and every exception thrown by the program
  • Some ways to deal with an exception
    • Log information to a report or a file
    • write data to the windows event log
    • email a system administrator
    • display problem to an end user
    • dump content to the console window
  • Exceptions from .NET framework or CLR known as System Exceptions
  • Writing a Custom Exception
    • Derives from Exception/ ApplicationException
    • Marked with the [System.Serializable] attribute
    • Defines a default constructor
    • Defines a constructor, sets the inherited Message property
    • Defines a constructor to handle InnerExceptions
    • Defines a constructor to handle the serialization of your type.
  • Catch most specific exceptions first and then catch the generic exceptions
  • Throw in catch to re-throw exceptions(partial handling)
  • Throw exceptions only until the callers who has the ability to handle incoming exceptions gracefully
  • C# 6.0 has when keyword to filter exception logic
    • eg:  catch(Exception ex) when(isItTrue == True) { // do something }

Book Review: Rich Dad Poor Dad

Rich Dad Poor DadRich Dad Poor Dad by Robert T. Kiyosaki

My rating: 3 of 5 stars

This book made me think about my personal finance. I have never read a book on this topic before. I think this book is a good starting point which makes the reader think about their own life, jobs and finance. The author talks about the importance of financial intelligence and he encourage every one to learn about money in order to get out of the “rat race”. The talks about his journey to become “rich”.

View all my reviews

Change default pdf reader to Adobe Reader in Windows 10

If you willingly or mistakenly upgraded your operating system to Windows 10  and no idea how to change the default pdf reader from Microsoft Edge to Adobe Reader, because the good old way no longer works and gives you errors, you can try this way.

Go to http://www.howtogeek.com/237512/how-to-change-the-default-pdf-reader-in-windows-10/ and read the second part of the article which has the title

Change the Default by Using Default Programs in Control Panel

You are welcome 😉

 

AWS Summit Singapore 2016

There are so many good events around Singapore and I make sure I attend an event once a month to keep my knowledge up to date. I thought of start writing about the events I participate hoping it will help you to get an idea what it is about and encourage you to attend some of them.

Last Thursday we had AWS Summit in Singapore. As my company is using AWS services and has more plans to experiment with them I attended the conference with two of my colleagues. Thanks to my boss for suggesting the event and the giving me approval to attend. It was a big conference with 5 tracks and 3000 participants. Yes, that was a lot of people.

Keynote

The conference started with a keynote by Dr. Werner Vogels (@Werner), CTO of Amazon.com. He talked about usage of Amazon Web Services and specially in the context of DevOps, IOT(Internet of Things), Serverless Architecture and data, database and application migration to the cloud. During his session, the event partners came and presented how they solve their problems using AWS.

I personally like the talks by the Cheif Infrastructure Consultant at data.gov.sg, Mr. Pallanikumaran Selvan and CTO at Zalora, Mr. Karthik Subramanian, as they told us the story about their journey to the cloud. Mr. Selvan showed the overall architecture of data.gov.sg including the integration of DevOps. If you do not know it yet, all the major components in their architecture has built on AWS Cloud Platform.

Ms. Anju Patwardhan, Global Chief Innovation Officer at Standard Charted Bank demonstrated us how they have used Amzon’s IOT device, Amazon Echo with the assistant Amazon Alexa in their Research and Development project. This was a fascinating experience.

This slideshow requires JavaScript.

Continue reading “AWS Summit Singapore 2016”

How to add Log4Net to your ASP.Net MVC (C#) project

  1. Add log4net dll to your references using Nuget Package Manager.
  2. Add this line to your AssemblyInfo.cs file
    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
  3. Add the following xml code to your Web.config file, inside the configurations tags. The value for version should be the version of your log4net dll.
    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
    </configSections>
  4. Also add the following lines to the Web.config file inside the configuration tags. Here I am logging to a file called “Jumppage.log” inside a folder named “Log”.
    <!-- Log4net Logging Setup -->
    <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
    <file value="Log\Jumppage.log" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="INFO" />
    <levelMax value="FATAL" />
    </filter>
    </appender><root>
    <level value="DEBUG" />
    <appender-ref ref="FileAppender" />
    </root>
    </log4net>
    
  5. Go to your class file and add the namespace, log4net as follows.
    using log4net;
  6. Add following code inside your class. You need to write your class name inside the typeof() method. In this project my class name is “AnnouncementController”.
    private static readonly ILog Logger = LogManager.GetLogger(typeof(AnnouncementController));
  7. Then you can log your error as follows.
    Logger.Error("Error in posting announcements. error message:"+ ex.Message + ", stacktrace:" + ex.StackTrace);

File upload control using ASP.Net MVC (C#)

HTML code
<input id="file-upload-control" name="UploadFile" type="file"/>
<button id="file-upload-button" class="button tiny" style="border: 1px solid #cccccc;">Upload</button>

JQuery code

var selectedFiles;
$('#file-upload-control').on('change', function (e) {
        selectedFiles = e.target.files;
    });

    $('#file-upload-button').on('click', function () {
        var files = selectedFiles;

        if (files.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < files.length; x++) {
                    data.append("file" + x, files[x]);
                }

                $.ajax({
                    type: "POST",
                    url: 'File/UploadFile',
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (result) {
                        console.log(result);
                        showInfo("File upload was successful! ");
                    },
                    error: function (xhr, status, p3, p4) {
                        var err = "Error " + " " + status + " " + p3 + " " + p4;
                        if (xhr.responseText && xhr.responseText[0] == "{")
                            err = JSON.parse(xhr.responseText).Message;
                        console.log(err);
                        showInfo("Something went wrong uploading file! ");
                    }
                });
            } else {
                alert("This browser doesn't support HTML5 file uploads!");
            }
        }
    });

FileController code

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace DHI.Controllers
{
public class FileController : Controller
{
[HttpPost]
public async Task UploadFile()
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
using (var fileStream = System.IO.File.Create(path))
{
stream.CopyTo(fileStream);
}
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Upload failed");
}

return Json("File uploaded successfully");
}
}
}