BODMAS rule using asp.net

Introduction: Hello everybody, in this article i will explain that how we can solve any mathamatic equation using BODMAS  rule using asp.net. This is very helpful artucle for the asp.net deveploer.

Implementation: Create a page named bodmas_rule.aspx page in your root folder. download NCalc - Binaries file from the above below link
create a bin folder in the root of your directory and place the NCalc.dll file. Place a label from the toolbox and set its id as lbl_msg. below I am giving code for .aspx page as well as .aspx.cs page . copy this code and paste it into your website and enjoy your code.
Code for .aspx page:

<div>
     <br />
        <asp:Label ID="lbl_check_answer" runat="server" Text="" Visible="false"></asp:Label>
        <asp:Button ID="btn_addition" runat="server" onclick="btn_addition_Click"
            Text="Addition" CausesValidation="False" />
        <br />
      
        <asp:Label ID="lbl_msg" runat="server" Visible="false"></asp:Label>
        <asp:Label ID="lblRandomEquation" runat="server" Text=""></asp:Label>
        <br />        <asp:TextBox ID="txt_answer" runat="server"></asp:TextBox>
       <%--<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="txt_answer" ErrorMessage="Enter only numbers"
            ValidationExpression="[-+]?[0-9]+"></asp:RegularExpressionValidator>--%>
        <br />
         <asp:Button ID="Button1" runat="server" Text="Click" onclick="Button1_Click" />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="btn_next_question" runat="server"
            onclick="btn_next_question_Click" Text="See next Question" Visible="False"
            CausesValidation="False" />
        <br />
        <asp:Label ID="lbl_answe" runat="server"  Visible="False"></asp:Label>
    </div>
Code for aspx.cs page:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text;

public partial class bodmas_latest : System.Web.UI.Page
{
    SqlCommand cmd;
    SqlConnection con = new SqlConnection();
    protected void Page_Load(object sender, EventArgs e)
    {
       // here  i am creationg the connection
        con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
        con.Open();

        if (con.State == ConnectionState.Closed)
        { con.Open(); }

        con.Close();
        if (Page.IsPostBack == false)
        {

        }

    }
    protected void btn_addition_Click(object sender, EventArgs e)
    {
        // in the session starting_time m storing the starting time when the question is generated
        Session["starting_time"] = "";
        Session["starting_time"] = DateTime.Now;
        Insert_user();
        method_bodmas(Convert.ToInt32(lbl_msg.Text));
        // Create a page named bodmas_rule.aspx in the root of your folder
        //http://ncalc.codeplex.com/releases/view/69050
        // download NCalc - Binaries file from the above below link
        // create a bin folder in the root of your directory and place the NCalc.dll file
        // inside the bin folder. after placing the NCalc.dll file NCalc.Expression  in the
        // help
        // here i am giving the equation which will solved by the BODMAS rule
        // inside the object e1
        //NCalc.Expression e1 = new NCalc.Expression("(13*3)+(39*2)-7");
        //NCalc.Expression e1 = new NCalc.Expression("(15*10)-17+23*(9-3)");
        NCalc.Expression e1 = new NCalc.Expression(lblRandomEquation.Text);
        ViewState["correct_answer"] = (e1.Evaluate().ToString());
        ViewState["question"] = lblRandomEquation.Text;
        lbl_check_answer.Text = ViewState["correct_answer"].ToString();
       
        btn_next_question.Visible = false;
        txt_answer.Enabled = true;
        lbl_answe.Text = "";

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (txt_answer.Text == "")
        {
            lbl_answe.Visible = true;
            lbl_answe.Text = "Type Your Answer Please";

        }
        else
        {
            // here m compairing the the answer entered by the user and 
            // the correct answer. if the both answer r same
            // then it goes inside the if
            // otherwise it will go inside the else
// and both answer will stored inside the table
            // if wrong or if correct
            if (Convert.ToInt32(ViewState["correct_answer"]) == Convert.ToInt32(txt_answer.Text))
            {
                if (con.State == ConnectionState.Closed)
                { con.Open(); }
                cmd = new SqlCommand();
                cmd.CommandText = @"INSERT INTO  tb_bodmas
                          VALUES(@question,@correct_answer,
                          @your_answer,@username,@starting_time,
                          @ending_time)";
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@question", ViewState["question"].ToString());
                cmd.Parameters.AddWithValue("@correct_answer", Convert.ToInt32(ViewState["correct_answer"]));
                cmd.Parameters.AddWithValue("@your_answer", txt_answer.Text);
                cmd.Parameters.AddWithValue("@username", string.Empty);
                cmd.Parameters.AddWithValue("@starting_time", Convert.ToDateTime(Session["starting_time"]));
                cmd.Parameters.AddWithValue("@ending_time", DateTime.Now);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
                lbl_answe.Visible = true;
                lbl_answe.Text = "correct";
                btn_next_question.Visible = true;
                txt_answer.Text = "";
                txt_answer.Enabled = false;

            }
            else
            {
                if (con.State == ConnectionState.Closed)
                { con.Open(); }
                cmd = new SqlCommand();
                cmd.CommandText = @"INSERT INTO  tb_bodmas
                          VALUES(@question,@correct_answer,
                          @your_answer,@username,@starting_time,@ending_time)";
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@question", ViewState["question"].ToString());
                cmd.Parameters.AddWithValue("@correct_answer", Convert.ToInt32(ViewState["correct_answer"]));
                cmd.Parameters.AddWithValue("@your_answer", txt_answer.Text);
                cmd.Parameters.AddWithValue("@username", string.Empty);
                cmd.Parameters.AddWithValue("@starting_time", Convert.ToDateTime(Session["starting_time"]));
                cmd.Parameters.AddWithValue("@ending_time", DateTime.Now);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
                lbl_answe.Visible = true;
                lbl_answe.Text = "Incorrect";
                txt_answer.Text = "";
                Session["starting_time"] = string.Empty;
                Session["starting_time"] = DateTime.Now;
            }
        }

    }
    protected void btn_next_question_Click(object sender, EventArgs e)
    {
        // in the session starting_time m storing the starting time when the question is generated
        Session["starting_time"] = "";
        Session["starting_time"] = DateTime.Now;
        Insert_user();
        method_bodmas(Convert.ToInt32(lbl_msg.Text));
        //NCalc.Expression e1 = new NCalc.Expression("(15*10)-17+23*(9-3)");
        //in The next i am passing the equation to the e1 object then
        // this equation will be solve by the method.
        NCalc.Expression e1 = new NCalc.Expression(lblRandomEquation.Text);
        // here m storing the correct answer vin the viewstate because when user enter their answer
        // then i'll compare this answer to the viewstate's value
        // if these values are equal then lbl_answe.Text shows the answer is correct and
        // if not then it shows the answer is incorrect
        ViewState["correct_answer"] = (e1.Evaluate().ToString());
        ViewState["question"] = lblRandomEquation.Text;
        lbl_check_answer.Text = ViewState["correct_answer"].ToString();
        btn_next_question.Visible = false;
        txt_answer.Enabled = true;
        lbl_answe.Text = "";
   


    }

    public void method_bodmas(int n)
    {
        // this function will generate the equation for the Bodmas
        //i am passing int n value  from the lbl_mgs.text inseide the Insert_use function
        StringBuilder equationBuilder = new StringBuilder();
        Random rnd = new Random();
        char[] operators = new char[] { '+', '-', '*', '/' };
        bool isBraces = rnd.Next(0, 2) == 1 ? true : false;
        bool isBracesOpened = false;
        int rndBracesLocation = rnd.Next(0, n - 1);

        int[] nums = new int[n];

        for (int i = 0; i < n; i++)
        {
            nums[i] = rnd.Next(1, 9);
        }

        char[] appOperator = new char[n - 1];


        for (int j = 0; j < n - 1; j++)
        {
            appOperator[j] = operators[rnd.Next(0, 3)];
        }

        for (int i = 0; i < n - 1; i++)
        {
            if ((isBraces && i == rndBracesLocation) || (isBracesOpened))
            {
                if (isBracesOpened)
                {
                    equationBuilder.Append(nums[i]);
                    equationBuilder.Append(")");
                    equationBuilder.Append(appOperator[i]);
                    isBracesOpened = false;
                }
                else
                {
                    equationBuilder.Append("(");
                    equationBuilder.Append(nums[i]);
                    equationBuilder.Append(appOperator[i]);
                    isBracesOpened = true;
                }

                isBraces = false;
            }
            else
            {
                equationBuilder.Append(nums[i]);
                equationBuilder.Append(appOperator[i]);
            }
        }
        equationBuilder.Append(nums[n - 1]);

        string equ = equationBuilder.ToString();
        if (equ.Contains("(") && !equ.Contains(")"))
            equ += ")";
        lblRandomEquation.Text = equ;





    }
    // This function will generate the value from 4 to 5
    // this function will decides that how many digits will come
    // inside the BODMAS equation
    public String recieptno(string rec)
    {

        int i = 0;
        int j = 0;
        int r = 0;

        Random ran = null;

        string str = null;

        str = "";

        ran = new Random();

        i = ran.Next(1, 1);

        for (j = 1; j <= i; j++)
        {
            r = ran.Next(4, 9);


            if (r < 65)
            {
            }

            str = str + r;
          

        }



        string recc = str;
        return recc;






    }
    private void Insert_user()
    {
        // the generated value will store inside the UID and after this lbl_msg
        string rec1 = "";
        string UID = recieptno(rec1);
        lbl_msg.Text = UID;
        //value wil be returned here


    }
}

Conclusion
Through this article, you have learned how to solve any equation using BODMAS rule. If you have any suggestion to improve this article then send mail me at bharti222000@yahoo.com.
Thanks



Comments

Popular posts from this blog

Sending reset password link for one time use only in asp.net

add delete update inside gridview using store procedure in ASP.NET

Change password using asp.net