Saturday, September 28, 2013

Adding Log Feature to Entity Framework

Today I will show how you can add auditing / logging to entity framework. [Code First]

Please note that this is an old blog post. An update to date instruction page is now at https://github.com/bilal-fazlani/tracker-enabled-dbcontext/wiki & repository is shared on github



As developers who deal with database everyday, we all are aware of those 4 columns that are present at the end of all tables,  i.e. create date,update date,create user, update user, etc. Depending on implementation these columns may differ in different scenario. But the objective here is same, auditing/logging.

The same can be achieved with entity framework by adding 4 extra properties to all POCO classes. This can be made more efficient by inheriting from and a class who already has these properties. To be honest, I have never followed that approach with entity framework.


I follow a different approach where you have a separate table which is dedicated for log entries.

-------------------------------------------------------------------------
Update: 5 March 2015
  1. For ASP.NET MVC 5 and above use: TrackerEnabledDbContext.Identity
  2. For everything else use: TrackerEnabledDbContext
Update: 26 March 2015
If you find any bugs, please raise them on : github.com
-------------------------------------------------------------------------

How do we do it ? - In 4 easy steps

Step 1: Install the nuget package

Install the package I have created from nuget package. 
you can easily do that by typing "Install-Package TrackerEnabledDbContext" in the package manager console.

Package Manager Console

Step 2: Inherit

Inherit your DbContext from TrackerContext (or TrackerIdentityContext for MVC 5 or above). It's present in TrackerEnabledDbContext namespace.
And instantiate it with connection string for example :

        public DatabaseContext()
            : base("DefaultConnection")
        {
        }

Add a migration and update your database. You will notice that 2 new tables are created for recording changes. (dbo.AuditLog)

      

Step 3: Decide

Decide which tables you want to track. and apply [TrackChangesattribute to those POCO classes.
Once you do that all the columns in that table will be tracked. In case you want to skip tracking for some specific columns, you can apply [SkipTrackingattribute to those columns (properties).

here is an example :

    

Step 4: Start using

Whenever you make a change in database, you call DbContext.SaveChanges(). Now you have an overload available for that which takes an integer. This should be the logged in persons user id. Please note that if you don't pass the user id, this change will not be recorded into the tracking table.

Example :
    databaseContext.SaveChanges(userId);


Now with version 2.5, there new methods available to fetch logs from audit log table.

       var ProductLog = context.GetLogs<Product>(426);

Please leave your comments and feedbacks. Thank you.





Saturday, March 16, 2013

Time Out Exception While Executing an Sql Command

Problem :

System.Exception: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

Cause : 

sqlcommand has a property called commandTimeout. Its default value is 30 seconds. If the query execution time is more than this value, It will throw above exception.

Friday, December 14, 2012

How to add an icon to your custom control

How to add an icon to your custom control

There's a lot of confusion for this on the internet. However, this is a very simple process.
This is how you do it :

  1. Have an image ready
  2. Make sure the image name is same as the control class.
  3. Resize it to 16 x 16 px (can be done with paint)
  4. While saving, select type as "16 Color bitmap" (paint is really cool !)
  5. Add it to your project (root directory)
  6. Go to its properties
  7. Select the build action as embedded resource.
  8. Rebuild the control
  9. Done!


Tuesday, October 16, 2012

Accessing deleted row field values from data table with C#.net


Accessing deleted row field values from data table with C#.net

Solution #1

Sometimes we delete data row in data table of dataset. Then we may need again to get deleted row field information from the dataset back for some calculation purpose. It gives error if we want to access the row data from the data table telling "The data row has been deleted ...".

We can still access the field data information by using DataRowVersion.Original parameter. For example 

int customerId = Convert.ToInt32( DataTable1.Rows[0][0, DataRowVersion.Original];

This will give the original version of the row data. And voila - we have our original data back.

Solution #2


We can make a Data View out of the datatable. Then convert that data view into data table again. This will give us the original data. But this time the datarowstate = "added".

We see one example code for this.

DataView myView = new DataView(sourceTable, null, null,DataViewRowState.Deleted);DataTable myTable = myView.ToTable();

Continuous Integration for .net Core projects ( for beginners )

Hello developers, This article is about how you can easily setup continuous integration for your dot net core (dnx) projects with appveyo...