Friday 24 April 2015

How to write a Exception to Text file in c# asp.net

Here I am writing a program, program, throw a exception in try block then it catch by catch block.
finally pass this exception to method called writeInFile(string excep) and this method will write
the thrown exception in text file in the base directory by default.

source code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;

namespace ConsoleDemoApp
{
    class WriteException
    {
        /* program to write a exception in c# */
       
        static void Main(string[] args)
        {
            int numerator=100;
            int Denominator=0;
            try{
                // throw a exception
                 int result=   numerator/Denominator;
                 Console.ReadKey();
               }
            catch(Exception ex)
            {
                //catch the exception and write to txt file
                writeInFile(ex.ToString());
            }
           
        }

        static void writeInFile(string excep)
        {
            // it will get base directory path but you can change it.
            string path = AppDomain.CurrentDomain.BaseDirectory;
            String dir = Path.GetDirectoryName(path);
            dir += "\\Error\\";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string newFileName = string.Format("{0:dd-MMM-yyyy_hh-mm-ss-tt}" + ".txt", DateTime.Now);
            string filepath = dir + newFileName;
            if (!File.Exists(filepath))
            {
                File.Create(filepath).Close();
            }
            using (StreamWriter w = File.AppendText(filepath))
            {
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Excepation :" + excep;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
    }
}

Output



How to generate a fibonacci series in c# aps.net ?


This is one of the most asked question in interviews, calculating and printing Fibonacci series.
 Here I am writing a program in C# to generate Fibonacci series.The numbers that precedes the series are 0 and 1.The next number is found by adding up the two numbers before it.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleDemoApp
{
    namespace fibonaciSeries
    {
        class Program
        {
            static void Main(string[] args)
            {

                int i, count, f1 = 0, f2 = 1, f3 = 0;
                Console.Write("Please enter the Limit : ");
                count = int.Parse(Console.ReadLine());
                Console.WriteLine(f1);
                Console.WriteLine(f2);
                for (i = 0; i <= count; i++)
                {
                    f3 = f1 + f2;
                    Console.WriteLine(f3);
                    f1 = f2;
                    f2 = f3;
                }
                Console.ReadLine();

            }
        }
    }

}



Please enter the Limit : 6
Output:-
 0
 1
 1
 2
 3
 5
 8
 13
 21


Calculate nth Fibonacci number:


Itreative method
 we can calculating the nth Fibonacci number, we just need to pass the value with the right index.
 We will first have a look at an iterative approach.
 Here we are using an integer array to keep the Fibonacci numbers until n and returning the nth Fibonacci number.


Source code:- 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleDemoApp
{
    namespace fibonaciSeries
    {
        class Program
        {
            static void Main(string[] args)
            {

                int num = 0, NthValue = 0;
                Console.Write("Please enter the nth number : ");
                num = int.Parse(Console.ReadLine());
                NthValue = getNth_fibonaciSeriesNumber(num);
                Console.WriteLine(NthValue);
                Console.ReadLine();

            }
            public static int getNth_fibonaciSeriesNumber(int n)
            {
                //Need to decrement by 1 since we are starting from 0
                int number = n - 1;
                int[] Fib = new int[number + 1];
                Fib[0] = 0;
                Fib[1] = 1;

                for (int i = 2; i <= number; i++)
                {
                    Fib[i] = Fib[i - 2] + Fib[i - 1];
                }
                return Fib[number];
            }
        }
    }
}


 Please enter the nth number: 9
Output:-
 21


Recursive method:-

We can also look for a recursive method. The only thing to consider is, here we need to pass a number less than 1 to get the nth Fibonacci number.

 For example if we want the 5th Fibonacci number then we need to pass 5-1 (in other words 5) as an input (we can also create a pass-through method alternatively)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleDemoApp
{
    namespace fibonaciSeries
    {
        class Program
        {
            static void Main(string[] args)
            {

                int num = 0, NthValue = 0;
                Console.Write("Please enter the number : ");
                num = int.Parse(Console.ReadLine());
                NthValue = getNth_Fibonacci_Recursive(num);
                Console.WriteLine(NthValue);
                Console.ReadLine();

            }
            public static int getNth_Fibonacci_Recursive(int n)
            {
                if ((n == 0) || (n == 1))
                {
                    return n;
                }
                else
                    return getNth_Fibonacci_Recursive(n - 1) + getNth_Fibonacci_Recursive(n - 2);
            }
        }
    }
}




In the above article I try to explain how to generate  Fibonacciseries and how get nth   Fibonacci in c#. I hope its useful to you. Please post your feedback, question, or comments about this article.