Wednesday, September 17, 2014

Project Euler Solution using C#: Problem 28 : Number Spiral Diagonals

Problem:

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13

It can be verified that the sum of the numbers on the diagonals is 101.

What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? My Solution:

static void Main(string[] args)
{
    static void Main(string[] args)
    {
        int limit = 1001 * 1001;
        int count = 0;
        int loopCount = 2;

        int sum = 1;   //1 coz the centervalue is 1. In loop counting from 3. 
        // every 4 iteration the increment count is adding +2
        for (int i = 3; i <= limit; i += loopCount)
        {
            sum += i;
            count += 1;
            if (count >= 4)
            {
                loopCount += 2;
                count = 0;
            }
        }
        Console.WriteLine(sum);
        Console.ReadLine();
    }
}

Note: You can simplifies the coding :)

Project Euler Solution using C#: Problem 25: 1000 Digit Fibonacci Number

Problem:

The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144

The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits? My Solution:

static void Main(string[] args)
{
    int count = 3;
 Dictionary F = new Dictionary();
 F.Add(0, 0);
 F.Add(1, 1);
 F.Add(2, 1);
 while (true)
 {
  BigInteger index1 = count - 1;
  BigInteger index2 = count - 2;
  BigInteger val = F[index1] + F[index2];
  F.Add(count, val);
  if (val.ToString().Length >= 1000)
  {
   break;
  }
  count += 1;
 }
 Console.WriteLine(count);
 Console.ReadLine();
}

Note: You can simplifies the coding :)

Get the Hash value of a file byte[] (byte array) in CSharp ( C# )

Here is a simple code to get the Hash value of a byte[] (byte array). The byte[] can be from any file. You can see my previous post to get the hash value directly from file. Click Here.
public static string GetHashValue(byte[] content)
{
    string hash;
    using (System.Security.Cryptography.SHA1CryptoServiceProvider sha = new System.Security.Cryptography.SHA1CryptoServiceProvider())
    {
        hash = Convert.ToBase64String(sha.ComputeHash(content));
    }
    return hash;
}

Happy coding :)

Thursday, September 11, 2014

Get MIME Content Type From Extensions C#

I have seen most of the people hard coding the MIME Content Type as a Constant or List to use it in their code. It's not possible to hard code all MIME Content types and use it. So here is a simple code to get those MIME Content type from the System itself based on the extension you are giving.
public static string GetMimeTypeFromExtension(string extension)
{
   string mimeType = string.Empty;
   RegistryKey key;
   object value;
   if (!string.IsNullOrEmpty(extension))
   {
      if (!extension.StartsWith("."))
      {
      extension = "." + extension;
      }
key = Registry.ClassesRoot.OpenSubKey(extension, false); value = key != null ? key.GetValue("Content Type", null) : null; mimeType = value != null ? value.ToString() : string.Empty; }
return mimeType; }
While calling you can pass the parameter like,
 " .pdf "
Or
"  pdf  "

our code will handle the dot !.

Monday, June 9, 2014

Get the return value from ASP.NET Code behind function to the client using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side. Here the GetSquareOfNumber function is called from client side and return the calculated value from the server when we click the Button2. The c# function should be static, decorated using [WebMethod] attribute and the parameter variable should be same as one we used in the ajax call "param". The returned value will be retrieved in the ajax success function. Use the Breakpoint to check the server code getting called or not.
Script in ASPX page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $("#Button2").click(function ()
            {
                var num = $('#TextBox1').val();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetSquareOfNumber", // Your page and function name
                    data: '{param: "' + num + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data)
                    {
                        if (data.d != null)
                        {
                            alert(data.d);
                        }
                    },
                    failure: function (response)
                    {
                        console.log(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <input id="Button2" type="button" value="button" />
        </div>
    </form>
</body>
</html>

Namespace:

using System.Web.Services;

Code behind C#:

[WebMethod]
public static int GetSquareOfNumber(int param)
{
 return param * param;
}

Call and pass parameter to ASP.NET Code behind function from the client side using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side with parameter also. Here the SendTheID function is called from client side and the TextBox1 value will be passed as a parameter when we click the Button2. The c# function should be static, decorated using [WebMethod] attribute and the parameter variable should be same as one we used in the ajax call "param". Use the Breakpoint to check the server code getting called or not.
Script in ASPX page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $("#Button2").click(function ()
            {
                var num = $('#TextBox1').val();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/SendTheID", // Your page and function name
                    data: '{param: "' + num + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data)
                    {
                        //will return null
                    },
                    failure: function (response)
                    {
                        console.log(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <input id="Button2" type="button" value="button" />
        </div>
    </form>
</body>
</html>


Namespace:

using System.Web.Services;


Code behind C#:

[WebMethod]
public static void SendTheID(int param)
{
 int returnId = param;
//Write whatever you neeed..
}

Call ASP.NET Code behind function without parameter from the client side using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side. Here the RunMe function is called from client side when we click the Button1. The c# function should be static and decorated using [WebMethod] attribute. Use the Breakpoint to check the server code getting called or not. Script in ASPX page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $("#Button1").click(function ()
            {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/RunMe", // Your page and function name
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (res)
                    {
   //will return null
                        console.log(res);
                    },
                    failure: function (response)
                    {
                        console.log(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input id="Button1" type="button" value="button" />
        </div>
    </form>
</body>
</html>

Namespace:

using System.Web.Services;

Code behind C#:

[WebMethod]
public static void RunMe()
{
//Write whatever you neeed..
}

Monday, May 26, 2014

ASP.NET Gridview sorting that bound to a List<> of custom objects as DataSource

In AsP.NET, Gridview with List<> of custom objects as DataSource does not support sorting. Here is a code to achieve it. Here the sort direction and Sort column is stored in a ViewState. So when we click a column name to sort it will check the previous sort direction from the ViewState["SortDirection"] and ViewState["SortColumn"]. If the previous direction is ASC means it will do DESC sort vice versa. I have used LINQ to sort the List. The sorting is done inside the GridView Rowcommand event with the help of CommandName and CommandArgument as parameter. And also you have to change the Gridview header from Label to LinkButton in the Header Template as it will make postbacks. Check out the code you can learn some new C# techniques as i have learned when i tried to implement this functionalities. Design Code:

<asp:GridView ID="grdManageUsers" runat="server" AutoGenerateColumns="False" OnRowCommand="grdManageUsers_RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="First Name">
            <HeaderTemplate>
                <asp:LinkButton ID="lnkFirstname" runat="server" CommandName="Sort" CommandArgument="Firstname">First Name</asp:LinkButton>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:Label ID="lblFirstNameEdit" runat="server" Text='<%# Eval("Firstname")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtFirstname" runat="Server" Text='<%# Eval("Firstname") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Last Name">
            <HeaderTemplate>
                <asp:LinkButton ID="lnklastname" runat="server" CommandName="Sort" CommandArgument="Lastname">Last Name</asp:LinkButton>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:Label ID="lblLastnameEdit" runat="server" Text='<%# Eval("Lastname")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtLastname" runat="Server" Text='<%# Eval("Lastname") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Email">
            <HeaderTemplate>
                <asp:LinkButton ID="lnkEmail" runat="server" CommandName="Sort" CommandArgument="Email">Email</asp:LinkButton>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:Label ID="lblEmailEdit" runat="server" Text='<%# Eval("Email")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtEmail" runat="Server" Text='<%# Eval("Email") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        </Columns>
    </asp:GridView>

Code behind C#:

List userList = new List();

private SortDirection LastSortDirection
{
    get
    {
        return (ViewState["LastSortDirection"] == null) ? SortDirection.Descending : (SortDirection)ViewState["LastSortDirection"];
    }
    set
    {
        ViewState["LastSortDirection"] = value;
    }
}

private string LastSortColumn
{
    get
    {
        return (ViewState["LastSortColumn"] == null) ? "Firstname" : (string)ViewState["LastSortColumn"];
    }
    set
    {
        ViewState["LastSortColumn"] = value;
    }
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        try
        {
           userList = GetUsers(); // It will return the List of users from data source.
           ViewState["USERLIST"] = userList; // It can be used for sorting
        }
        catch (Exception ex)
        {
           
        }
    }
}
protected void grdManageUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try
    {
        if (e.CommandName == "Sort" && !string.IsNullOrEmpty(e.CommandArgument.ToString()))
        {
            userList = ViewState["USERLIST"] as List;
            if (userList != null && userList.Count > 0)
            {
                IQueryable query = userList.AsQueryable();
                string newSortColumn = string.Empty;
                SortDirection newSortDirection = SortDirection.Descending;
                BindGridView(Sort(query, e.CommandArgument.ToString(), LastSortColumn, LastSortDirection, out newSortColumn, out newSortDirection));
                LastSortColumn = newSortColumn;
                LastSortDirection = newSortDirection;
            }
        }
    }
    catch (Exception ex)
    {      
    }
}
private void BindGridView(List users)
{
     grdManageUsers.DataSource = users;
     grdManageUsers.DataBind();
}
public List Sort(IQueryable list, string sortColumn, string lastSortColumn, SortDirection lastSortDirection, out string newSortColumn, out SortDirection newSortDirection)
{
    newSortColumn = string.Empty;
    newSortDirection = SortDirection.Descending;
    var result = new List();
    try
    {
        if (sortColumn == lastSortColumn)
        {
            newSortColumn = sortColumn;
            if (lastSortDirection == SortDirection.Ascending)
            {
                newSortDirection = SortDirection.Descending;
                result = SortProcess(list, SortDirection.Descending, sortColumn);
            }
            else
            {
                newSortDirection = SortDirection.Ascending;
                result = SortProcess(list, SortDirection.Ascending, sortColumn);
            }
        }
        else
        {
            newSortColumn = sortColumn;
            newSortDirection = SortDirection.Ascending;
            result = SortProcess(list, SortDirection.Ascending, sortColumn);
        }
    }
    catch
    {
        throw;
    }
    return result;
}
public List SortProcess(IQueryable list, SortDirection sortDirection, string sortColumn)
{
    IQueryable query = list.AsQueryable();
    try
    {
        var pi = typeof(T).GetProperty(sortColumn);

        if (sortDirection == SortDirection.Ascending)
        {
            query = query.OrderBy(x => pi.GetValue(x, null));
        }
        else
        {
            query = query.OrderByDescending(x => pi.GetValue(x, null));
        }
    }
    catch
    {
        throw;
    }
    return query.ToList();
}

Thursday, May 22, 2014

Project Euler Solution using C#: Problem 22: Names Scores

Problem:

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?
My Solution:

static void Main(string[] args)
{
    StreamReader sr = new StreamReader("names.txt");
    string textNames = sr.ReadToEnd().Replace("/", "").Replace("\"", "");
    char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
    long result = 0;
    string[] arr = textNames.Split(',');
    Array.Sort(arr);
    for (int i = 1; i <= arr.Length; i++)
    {
        int score = 0;
        foreach (var eachChar in arr[i - 1].ToCharArray())
        {
            score += (Array.IndexOf(alpha, eachChar) + 1);
        }
        score *= i;
        result += score;
    }
    Console.WriteLine(result);
    Console.ReadLine();
}

Note: You can simplifies the coding :)

Project Euler Solution using C#: Problem 20: Factorial Digit Sum

Problem:

n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! My Solution:

static void Main(string[] args)
{
    BigInteger multi = 1;
    long result = 0;
    int digits = 100;
    for (int i = digits; i >= 1; i--)
    {
        multi *= i;
    }
    foreach (var item in multi.ToString().ToCharArray())
    {
        result += long.Parse(item.ToString());
    }
    Console.WriteLine(result);
    Console.ReadLine();
}

Note: You can simplifies the coding :)

Wednesday, May 14, 2014

Handle Synchronous and Asynchronous Postbacks from the ASP.NET Updatepanel using Javascript

Here is a simple code to handle all the Synchronous and Asynchronous Postbacks from the ASP.NET Updatepanel using Javascript. We can get the control that makes the Postback. So Its very useful to show/hide loading image when asynchronous Postback happens. JavaScript Code:
<script type="text/javascript">
        $(document).ready(function ()
        {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_initializeRequest(prm_InitializeRequest);
            prm.add_endRequest(prm_EndRequest);
            var ctrl;
            function prm_InitializeRequest(sender, args)
            {
                ctrl = args.get_postBackElement().id;
                if (ctrl == "ContentPlaceHolder1_btnAddUser") 
                {
                $('#imgLoading').show();
                }
            }
            function prm_EndRequest(sender, args)
            {
              $('#imgLoading').hide();
            }
        });
</script>

Note: I have used jquery show/hide function to show/hide loading image. so you have to use the Jquery API.

How to search for a text in SQL Server Database using Stored procedure

Here is the stored procedure that will search and display the table name and column name of the text you are passing as a parameter to search from the Database.
SQL Query
CREATE PROC SearchTextFromDatabaseTables
(
    @SearchString nvarchar(100)
)
AS
BEGIN
    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
    SET NOCOUNT ON
    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchString + '%','''')
    WHILE @TableName IS NOT NULL
    BEGIN
        SET @ColumnName = ''
        SET @TableName =
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )
        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )
            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO #Results                 EXEC                 (                     'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)                     FROM ' + @TableName + ' (NOLOCK) ' +                     ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2                 )             END         END       END     SELECT ColumnName, ColumnValue FROM #Results END

Execute the Procedure using the below query and pass the text to be searched in it.
exec SearchTextFromDatabaseTables 'TEXT TO BE SEARCHED'

and you will get the result as below
    ColumnName                                    ColumnValue
1  [dbo].[TABLENAME].[COLUMNNAME]                SEARCHED TEXT STRING

Wednesday, April 16, 2014

(Solved) Error: Uncaught Sys.ArgumentTypeException: Sys.ArgumentTypeException: Object of type 'Sys.Extended.UI.Animation.GenericAnimationBehavior' cannot be converted to type 'Sys.UI.Behavior'. Parameter name: instance in ASP.NET

Error:

Uncaught Sys.ArgumentTypeException: Sys.ArgumentTypeException: Object of type 'Sys.Extended.UI.Animation.GenericAnimationBehavior' cannot be converted to type 'Sys.UI.Behavior'. Parameter name: instance
Solution:

Error resolved by adding ScriptMode="Release" like below
<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release">
</asp:ScriptManager>
or
<asp:ToolkitScriptManager ID="ToolkitScriptManager2" runat="server"  ScriptMode="Release">
</asp:ToolkitScriptManager>

(Solved) Error: Uncaught TypeError: Cannot read property 'UI' of undefined in ASP.NET

Error:

Uncaught TypeError: Cannot read property 'UI' of undefined
Solution:

Error Resolved by Changing,
<asp:ScriptManger>
to
<asp:ToolScriptManager>

Note: You need to add the latest Ajax Control Toolkit in your Visual Studio Toolbox to access the <asp:ToolScriptManager>

Thursday, April 10, 2014

Project Euler Solution using C#: Problem 16: Power Digit Sum

Problem:

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
My Solution:

static void Main(string[] args)
{
    int pwr = 1000;
    int sum = 0;
    BigInteger l =(BigInteger)Math.Pow(2, 1000);
    foreach (var item in l.ToString().ToCharArray())
    {
        sum += Int32.Parse(item.ToString());
    }
    Console.WriteLine(sum);
    Console.ReadLine();
}

Note:
You can simplifies the coding :)

Project Euler Solution using C#: Problem 12: Highly Divisible Triangular Number

Problem:

The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
My Solution:

static void Main(string[] args)
{
    int length = 1;  
    bool isFound = false;
    int divCount = 500;
    while (isFound == false)
    {
        int triNum = 0;
        int factorsCount = 0;
        for (int i = 1; i <= length; i++)
        {
            triNum += i;
        }
        for (int i = 1; i <= triNum; i++)
        {
            if (triNum % i==0)
            {
                factorsCount += 1;
                if (factorsCount > divCount)
                {
                    Console.WriteLine(factorsCount);
                    Console.WriteLine(triNum);
                    isFound = true;
                    break;
                }
            }
        }
        length += 1;
    }
    Console.ReadLine();
}

Note:
You can simplifies the coding :)

Project Euler Solution using C#: Problem 10: Summation Of Primes

Problem:

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
My Solution:

static void Main(string[] args)
{
    bool isPrime = false;
    long limit = 2000000;
    long ans = 2;
    for (long i = 3; i < limit; i += 2)
    {
            for (long j = 2; j < i; j++)
            {
                if (i % j != 0 && i != j)
                {
                    isPrime = true;
                }
                else
                {
                    isPrime = false;
                    break;
                }
            }

            if (isPrime)
            {
                Console.Clear();
                ans += i;
                Console.WriteLine(ans);
            }
    }
    Console.WriteLine("The sum of all the primes below " + limit + " is : " + ans);
    Console.ReadLine();
}

Note: You can simplifies the coding :)

Project Euler Solution using C#: Problem 9: Special Pythagorean Triplet

Problem:

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
My Solution:

static void Main(string[] args)
{
    int total = 1000;
    for (int i = 1; i <= total; i++)
    {
        for (int j = 1; j <= total; j++)
        {
            int k = total - i - j;
            int res = (i * i) + (j * j) + (k * k);
            int r = i + j + k;

            int left = (i * i) + (j * j);
            int right = (k * k);

            if (left == right && i < j && j < k)
            {
                Console.WriteLine(i + " " + j + " " + k);
                Console.WriteLine(Math.Pow(i, 2) + " " + Math.Pow(j, 2) + " " + Math.Pow(k, 2));
                Console.WriteLine(i * j * k);
                Console.WriteLine("---------------------");
            }
        }
    }
    Console.ReadLine();
}

Note: You can simplifies the coding :)

Monday, January 27, 2014

How to Set the ASP.NET Server Control Textbox value using JavaScript or Jquery

We can not access the server control by directly using it's id. You need to append and prepend the <%= and %> and also the ClientID. Because when rendering in browser the server control id will be change. If you are using JQuery to set the textbox value means you need to use # symbol. Check out the sample code clearly.
To get the server control value check my another post Click Here
HTML Code:
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

JavaScript Code:
document.getElementById("<%= textbox1.ClientID %>").value = "values to set using JavaScript";

JQuery Code:
$("#<%= textbox1.ClientID %>").val("values to set using JQuery");

How to Get the ASP.NET Server Control Textbox value using JavaScript or Jquery

We can not access the server control value by directly using it's id. You need to append and prepend the <%= and %> and also the ClientID. Because when rendering in browser the server control id will be change. If you are using JQuery to get the textbox value means you need to use # symbol. Check out the sample code clearly.
To Set a value to server control check my another post Click Here
HTML Code:
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

JavaScript Code:
var val1= document.getElementById("<%= textbox1.ClientID %>").value;

JQuery Code:
var val2= $("#<%= textbox1.ClientID %>").val();

Project Euler Solution using C#: Problem 7: 10001st Prime

Problem:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number?
My Solution:

static void Main(string[] args)
{
    bool isFound = false;
    bool isPrime = false;
    int limit = 10001;
    int count = 0;
    int val = 1;
    while (isFound == false)
    {
        if (val == 2)
        {
            count++;
        }
        else
        {
            for (int i = 2; i < val; i++)
            {
                if (val % i != 0 && val != i)
                {
                    isPrime = true;
                }
                else
                {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime)
            {
                count++;
                if (count == limit)
                {
                    Console.WriteLine("The" + limit + " th prime number is : " + val);
                }
            }
        }
        val++;
    }
    Console.ReadLine();
}
Note: You can simplifies the coding :)

Select only one checkbox at a time from the list of checkboxes using JQuery

Here i have created three checkbox named 1,2,3. When we click a checkbox, the name property of the current checkbox is retrived and checked using JQuery is() function and all other checkbox are unchecked using JQuery not() function.
HTML Code:
<input type="checkbox" name="fruits">1</input>
<input type="checkbox" name="fruits">2</input>
<input type="checkbox" name="fruits">3</input>

JQuery Code:
$(':checkbox').on('change',function(){
 var thiscb = $(this);
 var name = thiscb.prop('name');
 if(thiscb.is(':checked'))
 {
     $(':checkbox[name="'  + name + '"]').not($(this)).prop('checked',false);  
  }
});

Demo:

Click Here for Demo

Thursday, January 23, 2014

ASP.NET pie chart sample to set the chart area colors manually in code behind

Check out my previous sample to bind DataTable to Chart control Click Here. From the below code you can understand how to set the chart type, enable 3D chart, set the chart inclination angle, set the chart area colours manually in code behind and finally to format the lable displaying in the chart area. Here i have added the "%" symbol with label value that is displaying in the pie chart.
C# Code:
Chart1.Series["Series1"].Points.DataBind(chartData, "Key", "Value", string.Empty);
Chart1.Series["Series1"].ChartType = SeriesChartType.Pie;
Chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
Chart1.ChartAreas[0].Area3DStyle.Inclination = Convert.ToInt32(50);
foreach (Series charts in Chart1.Series)
{
     foreach (DataPoint point in charts.Points)
     {
             switch (point.AxisLabel)
             {
                      case "Name1": point.Color = Color.Green; break;
                      case "Name2": point.Color = Color.Blue; break;
                      case "Name3": point.Color = Color.Orange; break;
                      case "Name4": point.Color = Color.SandyBrown; break;
             }
             point.Label = string.Format("{0}%", point.YValues[0]);
             point.LegendText = point.AxisLabel;
     }
}

(Solved) Error: No http handler was found for request type 'GET' in ASP.NET Chart Control

Error:

No http handler was found for request type 'GET' in ASP.NET Chart Control
Solution:
  • Open your application web.config file.
  • Copy the below code and paste it inside the <configuration></configuration> tags.
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
    <remove name="ChartImageHandler"/>
    <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </handlers>
</system.webServer>
  • Hope it's fixed now

Project Euler Solution using C#: Problem 6: Sum Square Difference

Problem:

The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural  numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
My Solution:

static void Main(string[] args)
{
       int min = 1;
       int max = 100;
       int sumOfSq = 0;
       int temp = 0;
       int sqOfSum = 0;
       for (int i = min; i <= max; i++)
       {
           sumOfSq += (i * i);
       }
       for (int i = min; i <= max; i++)
       {
           temp += i;
       }
       sqOfSum = temp * temp;
       Console.WriteLine("Difference between the sum of the squares of the first one hundred"
       + "natural numbers and the square of the sum is :" + (sqOfSum - sumOfSq));
       Console.ReadLine();
}
Note: You can simplifies the coding :)

Wednesday, January 22, 2014

Show confirm alert before closing a page using JavaScript

Simple JavaScript code to display confirm alert before a page getting closed.
JavaScript Code:

    <script type="text/javascript">
        window.onbeforeunload = function (e) {
            return "Are you sure you want to close?";
        }
    </script>

Tuesday, January 21, 2014

Project Euler Solution using C#: Problem 5: Smallest Multiple

Problem:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
My Solution:

       static void Main(string[] args)
        {
            int num = 1;
            bool isDivisiblyByAll = false;
            bool isFound = false;
            while (isFound == false)
            {
                for (int i = 1; i <= 20; i++)
                {
                    if (num % i == 0)
                    {
                        isDivisiblyByAll = true;
                    }
                    else
                    {
                        isDivisiblyByAll = false;
                        break;
                    }
                }
                if (isDivisiblyByAll)
                {
                    isFound = true;
                    Console.WriteLine("Smallest positive number that is evenly divisible by all of the numbers from 1 to 20 is : " + num);
                }
                num++;
            }
            Console.ReadLine();
        }
Note: You can simplifies the coding :)

JavaScript Timer sample to hide a loading image after some seconds

A simple code to perform the timer functionality in Javascript. In the following example initially i have shown loading image using JQuery show() function. Then using the window.setInterval function i have set the Timer time to 5000 microseconds ie, 5 seconds. So the Hide function will execute after 5 seconds and the loading image will be hidden using the JQuery  hide() function. The JQuery show() and hide() function is equivalent to the CSS display block and none.
JavaScript Code:

<script type="text/javascript">
$('.img').show();
window.setInterval(Hide, 5000);
function Hide()
{
        $('.img').hide();

}
</script>

Monday, January 20, 2014

Catch Asynchronous postback from Updatepanel in ASP.NET to Show / Hide loading image

In some situation we need to display loading image when the Asynchronous post back in AP.NET Updatepanel. For that we need to catch the Asynchronous postback event. The below code will catch the postback and get the corresponding id of the control that makes the postback. So using the controlId you need to find the Updatepanel from which the postback occurred. So that we can show and hide the loading images in the specific Updatepanel. To find the Updatepanel here i used JQuery's closest function. Check the code.
Client Script:

<script type="text/javascript">
        $(document).ready(function() {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            if (prm != null) {
                prm.add_beginRequest(function(sender, e) {
                    var controlId = sender._postBackSettings.sourceElement.id;
                    var closestUpdatePanel= $('#' + controlId).closest(".UpdatepanelClass")
                });
            }
            prm.add_endRequest(function(sender, e) {
                var controlId = sender._postBackSettings.sourceElement.id;
                var closestUpdatePanel = $('#' + controlId).closest(".UpdatepanelClass")  
            });
        });
</script>

Thursday, January 16, 2014

Project Euler Solution using C#: Problem 4: Largest Palindrome Product

Problem:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
My Solution: 


        static void Main(string[] args)         {             int min = 100;             int max = 999;             List<int> list = new List<int>();             int multiplied=0;>             for (int i = min; i < max; i++)             {                 for (int j = min; j < max; j++)                 {                     multiplied = i * j;                     string reversed = new string(multiplied.ToString().ToCharArray().Reverse().ToArray());                     if (reversed == multiplied.ToString())                     {                         list.Add(multiplied);                     }                 }             }             Console.WriteLine("the largest palindrome made from the product of two 3-digit numbers is : " + list.Max());             Console.ReadLine();         }
Note: You can simplifies the coding :)

Tuesday, January 14, 2014

(Solved) Error: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

Error:

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Solution:

You need to download and install the "2007 Office System Driver: Data Connectivity Components" to fix this error

Click Here to download from Microsoft


Note: Other version may not fix this error.