Tuesday, December 31, 2013

Convert a CSV file to DataTable in C#

Here is a simple code to read CSV file and convert it to a DataTable using CSharp (C#). String enclosed with double quotes will not break the convertion process. In my previous post I have converted a DataTable to CSV with it's header. Check my previous post Click Here. So I have taken the first line in CSV as DataTable column headers. C# Code:


 public static DataTable ConvertCSVtoDataTable(string strFilePath)
 {
            StreamReader sr = new StreamReader(strFilePath);
            string[] headers = sr.ReadLine().Split(','); 
            DataTable dt = new DataTable();
            foreach (string header in headers)
            {
                dt.Columns.Add(header);
            }
            while (!sr.EndOfStream)
            {
                string[] rows = Regex.Split(sr.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
                DataRow dr = dt.NewRow();
                for (int i = 0; i < headers.Length; i++)
                {
                    dr[i] = rows[i];
                }
                dt.Rows.Add(dr);
            }
            return dt;
 } 

Call the ConvertCSVtoDataTable function like below by passing path of the CSV file.
static void Main(string[] args)
{
      string filepath = "d://ConvertedFile.csv";
      DataTable res = ConvertCSVtoDataTable(filepath);
}

Monday, December 30, 2013

Print HTML Div content using JavaScript

Well it's very easy to implement the print functionality using JavaScript. I have provided two kind of code. Try it.

JavaScript Code 1:
function PrintFunction1(divId) {
    var divElements = document.getElementById(divId).innerHTML;
    var oldPage = document.body.innerHTML;
    document.body.innerHTML =  "<html><head><title></title></head><body>" +  divElements + "</body>";
    window.print();
    document.body.innerHTML = oldPage;
}
JavaScript Code 2:
function PrintFunction2(divId)
{
    var DocumentContainer = document.getElementById(divId);
    var WindowObject = window.open('', "PrintWindow", "width=800,height=600,top=45,left=45,toolbars=no,scrollbars=yes,status=no,resizable=yes");
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}

HTML Code:

<a href="#" onclick="javascript:PrintFunction1('DivToPrint')">Print</a>
<div id="DivToPrint">
// --------------
// -------------
//Contents to be print
//---------------
// -------------
</div>

(Solved) Error: Object doesn't support property or method 'querySelectorAll' in IE 7

I fixed this issue using the JQuery reference and JQuery selector $. Just replace the document.querySelectorAll with $. and refer the JQuery api in the html body tag.
Javascript Error code in IE 7:

var sliders = document.querySelectorAll('.slider');

Javascript Error Solution:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
var sliders = $('.slider');

Project Euler Solution using C#: Problem 3: Largest Prime Factor

Problem:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My Solution:


static void Main(string[] args)
{
            const long constantInput = 600851475143;
            long input = constantInput;
            long divider = 2;
            long multiplyList = 1;
            bool largestPrimeFound = false;
            while (largestPrimeFound == false)
            {
                if (input % divider == 0)
                {
                    long val = input / divider;
                    input = val;
                    Console.WriteLine(divider);
                    multiplyList *= divider;
                    if (multiplyList == constantInput)
                    {
                        Console.WriteLine("The largest prime factor for the number " + constantInput + " is : " + divider);
                        largestPrimeFound = true;
                    }
                }
                else
                {
                    divider += 1;
                }
            }
            Console.ReadLine();
 }
Note: You can simplifies the coding :)

Tuesday, December 17, 2013

Call JavaScript function from Silverlight Code behind

Here is a very simple code to display an Javascript alert from Silverlight code behind.
Silverlight Code behind C#:

private void Button_Click(object sender, RoutedEventArgs e)
{
      HtmlPage.Window.Invoke("showAlert", "Hello!");
}

JavaScript:

function showAlert(message) 
{
    alert(message);
}

Wednesday, December 11, 2013

(Solved) Error: HTTP Error 404.3 - Not Found in IIS 7.5

Solution: 
  • Got to Control Panel -> Programs and Features -> Turn Windows features on or off
  • A popup window will be displayed
  • Navigate through the tree view Internet Information Services -> World Wide Web Services -> Application Development Features
  • Here check the ASP.NET , .NET Extensibility, ISAPI Extensions, ISAPI Filters checkboxes
  • Click OK
  • Go to Visual Studio Command prompt
  • Run the command : %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

(Solved) Error: HTTP Error 500.19 – Internal Server Error in IIS 7.5

Solution: 
  • Just check out the the Microsoft kb articles Click Here 
  • If you still can't find the solution just comment the web.config lines that's showing error.
  • It should work.


Project Euler Solution using C#: Problem 2: Even Fibonacci Numbers

Problem:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
My Solution:


      static void Main(string[] args)         {             int val1 = 1;             int val2 = 2;             Int64 evenTerms = 2;             while (val2 < 4000000)             {                 int temp = val1;                 val1 = val2;                 val2 = temp + val2;                 if (val2 % 2 == 0)                 {                     evenTerms += val2;                 }             }             Console.WriteLine(evenTerms);             Console.ReadLine();         }
Note: You can simplifies the coding :)

Monday, December 9, 2013

Project Euler Solution using C#: Problem 1: Multiples of 3 and 5

Problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
My Solution:
       static void Main(string[] args)
        {
            int sumOfMultiples = 0;
            for (int i = 1; i < 1000; i++)
            {
                if (i % 3 == 0 || i % 5 == 0)
                {
                    sumOfMultiples += i;
                }
            }
            Console.Write("The Sum of Multiples of 3 or 5 below 1000 is :");
            Console.Write(sumOfMultiples);
            Console.ReadLine();
        }

Note: You can simplifies the coding :)

Thursday, December 5, 2013

Expression Tree sample to build Dynamic queries to query List<> with Sorting in C#

Here is a Expression Tree sample to build Dynamic queries to query List<> with Sorting in C#
C# Code:

    static void Main(string[] args)
    {
        IQueryable<Country> queryableData = GetCountries().AsQueryable();
        ParameterExpression pe = Expression.Parameter(typeof(Country));
        MemberExpression me = Expression.PropertyOrField(pe, "Id");
        MethodCallExpression orderByCallExpression = Expression.Call(
              typeof(Queryable),
              "OrderByDescending",
              new Type[] { queryableData.ElementType, typeof(Int32) },
              queryableData.Expression,
              Expression.Lambda<Func<Country, Int32>>(me, pe));
        IQueryable<Country> results = queryableData.Provider.CreateQuery<Country>(orderByCallExpression);
        foreach (var item in results)
        {
            Console.Write(item.Id);
            Console.Write(" : ");
            Console.WriteLine(item.Name);
        }
        Console.ReadLine();
    }

    public static List<Country> GetCountries()
    {
        // To get the country list in c# check my previous post Click Here
        // i have added a Id property to the above link sample to make some condition work in this post
    }
    class Country
    {
        public Int32 Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
    }
Reference: MSDN 

Expression Tree sample to build Dynamic queries to query List<> with Where condition in C#

Here is a sample program to build Dynamic queries to query List<> with Where condition
C# Code:

static void Main(string[] args)
{
    IQueryable<Country> queryableData = GetCountries().AsQueryable();
    ParameterExpression pe = Expression.Parameter(typeof(Country));
    MemberExpression me = Expression.PropertyOrField(pe, "Id");
    ConstantExpression cex = Expression.Constant(10, typeof(int));
    BinaryExpression be = Expression.LessThan(me, cex);
    MethodCallExpression whereCallExpression = Expression.Call(
  typeof(Queryable),
  "Where",
          new Type[] { queryableData.ElementType },
          queryableData.Expression,
          Expression.Lambda<Func<Country, bool>>(be, pe));
   IQueryable<Country> results = queryableData.Provider.CreateQuery<Country>(whereCallExpression);
    foreach (var item in results)
    {
        Console.Write(item.Id);
        Console.Write(" : ");
        Console.WriteLine(item.Name);
    }
    Console.ReadLine();
}

public static List<Country> GetCountries()
{
    // To get the country list in c# check my previous post Click Here 
    // i have added a Id property to the above link sample to make some condition work in this post
}

class Country
{
    public Int32 Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

Reference: MSDN

Sample C# program to find Happy or Sad numbers

Here is a sample C# program to find the given number is Happy or Sad.

What is Happy or Sad Numbers?

Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are Sad numbers.

Example:

7 is a happy number: 7->49->97->130->10->1.
22 is NOT a happy number: 22->8->64->52->29->85->89->145->42->20->4->16->37->58->89
Code:
using System;
using System.Collections.Generic;

namespace HappyNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine();
                Console.WriteLine("Enter a Number : ");
                string num = Console.ReadLine();
                Console.WriteLine();
                HappyOrSad hs = new HappyOrSad();
                if (hs.IsEqulOne(num))
                {
                    Console.WriteLine();
                    Console.WriteLine("Happy :) ");
                    Console.WriteLine();
                    Console.WriteLine("----------------------");
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine("Sad :( ");
                    Console.WriteLine();
                    Console.WriteLine("----------------------");
                }
            }
        }
    }

    class HappyOrSad
    {
        public bool IsEqulOne(string numbr)
        {
            bool isOne = false;
            List<int> al = new List<int>();
            while (isOne == false)
            {
                int val = 0;
                char[] numArr = numbr.ToCharArray();
                foreach (char n in numArr)
                {
                    int nVal = Int32.Parse(n.ToString());
                    val += (nVal * nVal);
                }
                if (val == 1)
                {
                    al.Add(val);
                    isOne = true;
                    break;
                }
                else
                {
                    if (al != null)
                    {
                        if (al.Contains(val))
                        {
                            al.Add(val);
                            break;
                        }
                        else
                        {
                            al.Add(val);
                        }
                    }
                }
                numbr = val.ToString();
            }
            foreach (var item in al)
            {
                Console.Write(item + " -> ");
            }
            return isOne;
        }
    }
}

Sunday, December 1, 2013

Get the list of country code and names in c#

Here is a simple Linq code to retrive the list of country code and names
C# code:

public IEnumerable<Country> GetCountries()
{
    var countryList = from r in
                      from ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                      select new RegionInfo(ci.LCID)
                      group r by r.TwoLetterISORegionName into g
                      select new Country
                      {
                          Code = g.Key,
                          Name = g.First().DisplayName
                      };
    return countryList;
}
Also you need to add the below class
class Country
{
        public string Code { get; set; }
        public string Name { get; set; }
}