Saturday, November 30, 2013

Getting started with ELMAH and ASP.NET MVC

We all need a framework to log exceptions in our web application. Today, We are going to learn about same. ELMAH(Error Logging Modules and Handlers) is an application wide error logging framework. How we can install it in ASP.NET MVC.

What is ELMAH:


ELMAH(Error logging Modules and Handlers) is an application wide error logging facility that is an pluggable framework. It can dynamically added to running an ASP.NET application. You also have Nuget package for the same.
You can find more information about on following link.

https://code.google.com/p/elmah/

Once you install ELMAH, You can have following advantages
  1. You can log almost all unhandled exceptions in the system.
  2. An RSS feed of last 15 errors from the log
  3. An email notification of each error occurs.
  4. A remote web page to log all the exceptions.
  5. You can insert log a various locations like files text file, SQL Server, Oracle etc.

ELMAH NuGet Package:


There is a nuget package also available for ELMAH. You can find at following link.

http://www.nuget.org/packages/elmah/

and Following Command you have to run for installing NuGet Pacakge.

ELMAHNuGetPackageASP.NETMVC

Getting Started with ASP.NET MVC and ELMAH:


So Let’s first create a new project with ASP.NET MVC  from Visual Studio via File->New Project –>ASP.NET MVC 4 Application.

ELMAHNewProjectMVC

Once you click OK it will ask you for type of application like following. We are going to select internet application here.

TypeofApplicationELMAHMVC

Once you click on OK it will create new ASP.NET MVC 4 Application. Once our ASP.NET MVC 4 application is ready. It’s time to add ELMAH to ASP.NET MVC4 Application. The best way to add ELMAH is nuget package so we don’t have to worry about the configuration settings in web.config. So Let’s go to Tools-> Library Package Manager-> Package Manger Console and run the NuGet Command like following.

PackageManagerConsoleNuGetPacakgeELMAH

So now if you see in web.config all configuration is added.
Web.ConfigErrorHandlingSection
Now let’s run our asp.net application via pressing f5.

ElMAHASP.NETMVCSite

Now let’s create some unhandled errors for example test Action Result does not exist in our ASP.NET MVC application. So Let’s write that in URL and it will give error like following.

ErrorElMAHASPNETMVC

Now let’s see whether this error is logged by ELMAH or not. Here you go

ErrorLogELMAH

Once you click on details. It will show details error like following.

DetailErroLogELMAH

That’s it. You can see now it’s very easy to log errors and unhandled exceptions in ELMAH. There are various options to log errors in ELMAH we will see that in future posts.

Hope you like it. Stay tuned for more..
Share:

How to find days in year except Saturday and Sunday in C#

Before 2 years I have written a blog post to find Saturday and Sunday in given date range.  It has gain a lot of popularity and on that blog post one user ask about how we can find days in year except Saturday and Sunday in C#. This post is a in reply for that. Following is a code for that.
using System;

namespace DatimeApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startDate = new DateTime(2013, 1, 1);
            DateTime endDate = new DateTime(2013, 12, 31);

            TimeSpan diff = endDate - startDate;
            int days = diff.Days;
            int j=0;
            for (var i = 0; i <= days; i++)
            {
                var testDate = startDate.AddDays(i);
                if (testDate.DayOfWeek != DayOfWeek.Saturday && testDate.DayOfWeek != DayOfWeek.Sunday)
                {
                    j = j + 1;
                    Console.WriteLine(testDate.ToShortDateString());
                }
            }
            Console.WriteLine(string.Format("Total Days:{0}",j));
            Console.ReadLine();
        }
    }
}

If you see above code,  Its very easy to find all days except Saturday and Sunday in a year. I have created two dates with Start date and end date and then I found a difference between those two days. And then in for loop I have checked whether they are weekdays then I have printed a date for that. I have calculated all days except Saturday and Sunday for year 2013. At the end I have printed total days also.

Once you run the code following is a output as expected.

FindDaysExceptSatudaySundayInCsharp

That’s it. Hope you like it. Stay tuned for more…
Share:
Thursday, November 14, 2013

My visual studio settings

Lots of people send me email about what kind of visual studio settings I am using and I am replying them again and again so I thought it will be good idea to write a blog post about it.

Yes, Since last 2 months I have been using dark theme of Visual Studio 2012 but I am not using default dark theme color settings of visual studio. I’m using dark theme color settings created by Keith Elder. You can find more information about color settings of this theme from following link.

http://keithelder.net/2010/03/05/my-visual-studio-color-settings-again/

I simply love this one and its works on all flavours of Visual Studio starting from Visual Studio 2008 to 2012. Below are few screenshots from that.

VisualStudioDarkTheme

Here is another screenshot.

ClearDarkTheme

It’s been great for eyes and I can work with very easily and as you may notice my default font for visual studio is Consolas and size is 11.

Now lots of people ask me whether its working fine with resharper or not and Its works like a charm. See following screenshot.

ResharperBlackTheme

And this is how intellisense look with Visual studio 2012 dark theme.

VisualStudioIntellisenseDark

And this how HTML part of ASP.NET MVC looks in the dark theme.

DarkHtmlVisualStudioTheme

If you still never try of any dark theme for visual studio then try it and it is great for your eyes. I would like to say big thanks to  Keith Elder for creating a great black theme. If you want to try same theme then you can download that from above link I have mentioned.
Hope you like it. Stay tuned for more..Happy Programming Smile
Share:
Friday, November 8, 2013

How to find space used by table in SQL Server

Recently there was requirement for a client where we need to find space occupied/used  by particular table in SQL Server. I did some research a found a very cool way to get space used information from SQL Server.

With SQL server 2005 and higher version you can use ‘sp_spaceused’ to find space used by table in SQL Server.

Following is a syntax for that.
sp_spaceused N'YourTableName'

You can find more information about it from the following link.
http://msdn.microsoft.com/en-us/library/ms188776.aspx

When you run this in SQL Server, Its displays Number of Rows, disk space served and disk space used by a table or indexed view and also displays disk space reserved and used by database.

SpaceUsedByTableSQLServer

Here in the above example, You have seen that I have used to find space for employee table in my blog sample database and its providing information about rows, reserved space, data size, index_size space and unused space.

That’s it. Hope you like it. Stay tuned for more.
Share:
Thursday, November 7, 2013

How to find path of database data files and log files in SQL Server

In this post, We will learn about different technique to find path of data files and log files on SQL Server. Let’s go through one by one of them.

The first technique, We are going to use is very simple way to finding file path for database. But with this you can find path for one database only. It’s very simple, Select database on object explorer and right click and select properties.


HowToSelectDatabaseFilePathSQLServer1

Now once you click on properties a dialog box appear like following. Select files and go to path column it will show path of database data files and log files.

HowToSelectDatabaseFilePathSQLServer2
Now we will learn another technique where we can find database data file and log file path from query. Below is query for that.

SELECT name, physical_name FROM sys.master_files where database_id= db_id('blog')

Now once you run this query it will load result like following.

HowToSelectDatabaseFilePathSQLServer3


That’s it you can find you database file path very easily. You can use above query to find files path for multiple databases also without using where clause. Hope you like it. Stay tuned for more.
Share:
Sunday, October 27, 2013

All about Virtual,Override and New in C#


I have seen that lots of people get confused with Virtual, Override and new keyword in C#. So I thought it will be a good idea to write a blog post about it. In this blog post we will learn what is virtual, override and new keyword in C# and what’s difference between override and new in C#.

Virtual and Override in C#:


Virtual keyword allows class member to override in derived class. Let’s take simple example. I have class A which contains Print Method method as virtual method and I have another class B which is derived from class A which overrides Print method. Following is a code for that.

public class A
{
    public virtual void Print()
    {
        System.Console.WriteLine("Virtual Print method from a");
    }
}

public class B:A
{
    public override void Print()
    {
        System.Console.WriteLine("Override Print method from b");
    }
}
Now If I create a object of class A like following and run the code Print method run as normal method. Following is code for for that.
class Program
   {
       static void Main(string[] args)
       {
          A a=new A();
          a.Print();
       }
   }

Once you run this it will have following output.

VirutalAsNormalMethodinCsharp

But when you create a object of class B like following it will completely override the functionality of class A. That is called method Method Overriding. Following is a code for that.

class Program
{
    static void Main(string[] args)
    {
       B b=new B();
       b.Print();
    }
}

Now, if you run this code it will completely override the code and following will be output as expected.

OverrideMethodinCsharp

How to call base class method with override:


In some scenario, we need base class functionality also while overriding the method of that class. C# provides that functionality with ‘base’ keyword. For that I have changed code of class B like following.
public class B:A
{
public override void Print()
{
    System.Console.WriteLine("Override Print method from b");
    base.Print();
}
}

class Program
{
    static void Main(string[] args)
    {
       B b=new B();
       b.Print();
    }
}

Now if you run the code you will see output of both method as expected.

BaseKeywordwithoverridecsharp

What is difference between new and override in C#:


After looking into above example some people will argue that this functionality will be achieved by new keyword also. This is call Method Hiding where with new keyword you can hide functionality of base class.  But wait there is a difference. Both are slightly different let’s take some simple example to show difference following is a code for that.
namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
           A a=new B();
           B b=new B();

           a.Print();
           b.Print();
        }
    }

    public class A
    {
        public virtual void Print()
        {
            System.Console.WriteLine("Virtual Print method from a");
        }
    }

    public class B:A
    {
        public override void Print()
        {
            System.Console.WriteLine("Override Print method from b");
        }
    }
}

In this code, same A class Print method is override by B class Print method and I have created two object of class B. One with reference to base class A and another B itself. Now let’s run this example and following is a output.

OverridewithInheritancedifferencebetweenoverideandnew

Here you see both time it will override class A’s Print Method. Now let’s change above code with new keyword like following.
namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
           A a=new B();
           B b=new B();

           a.Print();
           b.Print();
        }
    }

    public class A
    {
        public virtual void Print()
        {
            System.Console.WriteLine("Virtual Print method from a");
        }
    }

    public class B:A
    {
        public new void Print()
        {
            System.Console.WriteLine("Override Print method from b");
        }
    }
}

Now you run this code. Following is output.

OverridewithInheritanceDifferenceBetweenoverrideandnew

If you see both output carefully then you will notice a difference. With override keyword it will override Print method in both scenarios. While with new keyword it will only hide print method and both method exist as separate method so if you create a class A object with B then it will class A’s Print method without hiding it and If you create class B object with B then it will hide the base class method and print from class B’s method. So that was the difference.

That’s it. Hope you like it. Stay tuned for more..
Share:
Tuesday, October 22, 2013

Linq- AddRange Method in C#

In this post I’m going to explain you about Linq AddRange method. This method is quite useful when you want to add multiple elements to a end of list. Following is a method signature for this.
public void AddRange(
    IEnumerable<T> collection
)
To Understand let’s take simple example like following.

using System.Collections.Generic;
using System;
namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            foreach (var newname in newnames)
            {
                names.Add(newname);
            }
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Here in the above code I am adding content of array to a already created list via foreach loop. You can use AddRange method instead of for loop like following.It will same output as above.
using System;
using System.Collections.Generic;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            names.AddRange(newnames);
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Now when you run that example output is like following.

AddRangeLinqCsharp

Add Range in more complex scenario:

You can also use add range to more complex scenarios also like following.You can use other operator with add range as following.
using System;
using System.Collections.Generic;
using System.Linq;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            names.AddRange(newnames.Where(nn=>nn.StartsWith("Vi")));
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Here in the above code I have created array with string and filter it with where operator while adding it to an existing list. Following is output as expected.

AddRangeLinqCsharpAdvanceScneario

That’s it. Hope you like it. Stay tuned for more..
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews