Wednesday, July 22, 2015

How to Convert Number to Words using Recursion in ASP.NET (c#.net)


The purpose of this article is to make beginners to understand practical use of recursion in ASP.NET (c#.net). I have taken a practical scenario which occurs widely in most of the applications. Hence I have come up with code for converting a number into Indian Rupees.

Here is a function “ConvertToWords” recursively called since same notation applies for digits in Thousands, Lakhs and Crores place in number once number crosses 999.  


using System;
namespace NumberConvertor.Models
{
    public class NumberConverter
    {
        public static string ConvertToWords(double num,bool appendCurrency=true)
        {
            string[] tens = new string[] { "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
            string[] ones = new string[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen" };
            string result = "";



            //Finding Number of Crores in a given number
            int noOfCrores = ((int)num) / 10000000;
            if (noOfCrores > 0) result += ones[noOfCrores] +" Crore ";
            num-= 10000000 * noOfCrores;

            //Finding Number of lakhs in a given number
            int noOfLakhs = ((int)num) / 100000;
            if (noOfLakhs > 0) result += ConvertToWords(noOfLakhs,false) + " Lakh ";
            num -= noOfLakhs * 100000;

            //Finding Number of thousands in a given number
            int noOfThousands=((int)num)/1000;
            if (noOfThousands > 0) result += ConvertToWords(noOfThousands,false) + " Thounsand ";
            num -= noOfThousands * 1000;

            //Finding Number of hundreds in a given number
            int noOfHundreds = (int)num / 100;
            if (noOfHundreds > 0) result += ones[noOfHundreds - 1] + " Hundred ";
            num -= noOfHundreds * 100;

            if (num < 20)
                result += ones[(int)num - 1];
            else
                result += tens[((int)num / 10) - 1] + " "+ones[(int)num % 10 - 1];

            if (appendCurrency) result += " Rupees";
          
            //extract digits after decimal point
            num = (int)(Math.Round((num - (int)num) * 100));
           
           
            if (num > 0)
            {
                result +=" "+ ConvertToWords(num,false);
                if (appendCurrency) result += " Paise";
            }

            return result;
        }

}

}

Monday, July 20, 2015

How to implement Captcha in ASP.NET MVC (C#.NET)

     Introduction


   CAPCTHA (Completely Automated Public Turing Test to tell Computers and Humans Apart) is used to protect website from machines accessing using automated scripts.  


 Pre-Requisites
       BotDetect CAPTCHA.


      Steps to Implement Captcha in Forgot Password page

Step 1: Create an MVC Project
              I.        Open Visual Studio 2012 and click on File->New->Project->Templates-Visual C#->Web->ASP.NET MVC 4 Web Application
            II.        Choose Location (your working folder ex: d:\samples) , give name as “Captcha” and click on OK button.


            III.        Choose Basic Template, Razor engine and click on OK
           IV.        Install BotDetect CAPTCHA from Visual Studio using Nuget packages. Right click on ‘Captcha’ solution and click on Manage NuGet  Packages
            V.        Click on Online->All and search for Captcha and choose BotDetect and click on Install

Step 2: Create a Model
              I.        Right click on Models folder, click on Add and click on Class
             II.        Name the class as “ForgotPasswordModel.cs” and create class as follows by importing namespace “System.ComponentModel.DataAnnotations

using System.ComponentModel.DataAnnotations;
public class ForgotPasswordModel
{

      [Required]
      [EmailAddress]
      [Display(Name="Enter your registered Email Address")]
      public string EmailId { get; set; }

      [Required]
      [Display(Name="Security Code")]
      public string SecurityCode { get; set; }
}
Step 3: Create a Controller
              I.        Right click on Controller, click on Add->Controller and name it as SamplesController and create an action “ForgotPassword” as follows
             II.        Import namespaces  ‘Captcha.Models’ and ‘BotDetect.Web.UI.Mvc’;
namespace Captcha.Controllers
{
      using Captcha.Models;
using BotDetect.Web.UI.Mvc;
public class SamplesController : Controller
    {

        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
//Following filter will validate security code
[CaptchaValidation("SecurityCode","Captcha","Incorrect Security Code")]        public ActionResult ForgotPassword(ForgotPasswordModel m)
        {
            if (ModelState.IsValid)
            {
                //here we need to write code to check whether email id exists in our database
                //Just for know I am checking whether given email id is equal to sateesh.gompa@gmail.com
                if (m.EmailId=="sateesh.gompa@gmail.com")
                    RedirectToAction("Thankyou");
                else
                    ModelState.AddModelError("NotFound","Email Address is not found in our database");

            }
            return View(m);

        }

}
            III.        Build the project
Step 4: Create a View
              I.        Right Click on action name “ForgotPassword” and click on Add View



             II.        turn on “Create a stongly-typed view’ checkbox,  Choose ForgotPasswordModel,  choose ‘Create’ in Scaffold Template and click on Add
            III.        ForgotPassword.cshtml page gets created in View->Samples folder.


           IV.        Import the namespace and include BotDetect styles inside BotDetectStyles section in view
@using BotDetect.Web.UI.Mvc
@section BotDetectStyles{
<link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" type="text/css" rel="stylesheet" />
}

            V.        Add a div below security code in ForgotPassword.cshtml and  create capctha instance and pass it to captcha htmlhelper
<div>
@{MvcCaptcha captchaInstance=new MvcCaptcha("Captcha");}
@Html.Captcha(captchaInstance)
</div>
<div>
@Html.ValidationMessage("IVC")
</div>



Step 5: Define BotDetect Section in _Layout.cshtml

Open _Layout.cshtml file in Shared folder and put following line inside head tag @RenderSection("BotDetectStyles",false)

 Step 6: Exclude BotDetect paths from ASP.NET MVC Routing:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // BotDetect requests must not be routed
        routes.IgnoreRoute("{*botdetect}",  new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

….

}

       Press F5 and append “/samples/forgotpassword” to the url in browser to access the page.    


Sunday, July 12, 2015

Data Types and Operators in C#.NET

Data Types & Operators


Data Types
Data Type is a set of allowable values. It defines type of data and size of memory required. C#.net has following of categories of data types.

           Value Types
           Value Type store its contents in memory allocated in stack
           
           Reference Types
Reference Type stores the address of memory where data stored. Reference Type store the data in heap memory.

Pointer Types ( it is unsafe and not advised to use)
           
Value Types
SNO
Data Type
Size
Range
Default Value
Framework Type
1
Int
4 bytes
-2,147,483,648 to 2,147,483,647
0
System.Int32
2
Uint
4 bytes

0
System.UInt32
3
short
2 bytes
-32,768 to 32,767
0
System.Int16
4
ushort
2 bytes
0 to 65,535
0
System.UInt16
5
long
8bytes
–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
0
System.Int64
6
ulong
8bytes
0 to 18,446,744,073,709,551,615
0
System.UInt64
7
byte
1 byte
0 to 255
0
System.Byte
8
sbyte
1 byte
-128 to 127

System.SByte
9
float
4 bytes

0.0F
System.Single
10
double
8 bytes

0.0
System.Double
11
decimal
16 Bytes

0
System.Decimal
12
bool
1 Byte

False

13
Struct




14
char
2 Bytes

‘\0’
System.Char
15
enum





Reference Types
  • class
  • interface
  • delegate
  • dynamic
  • string
  • object 

Pointer Types
            Pointer Type stores the address of another variable. Pointer Types can be used in unsafe context.
Ex;
            int* p1,p2;
int a=23;
            unsafe
{
            p1=&a;
}
Any of the following types may be a pointer type:
·         sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool
·         Any enum type.
·         Any pointer type.
·         Any user-defined struct type that contains fields of unmanaged types only.

To make run the unsafe code in c#.net, turn on ‘allow unsafe’ check box in visual studio 2012 under build properties (Project->Properties->Build).


Variable Declaration

Syntax:  <datatype> <variablename>;
int a =2;
int b=3,c=4;
float f=2.3F;   ( float f=2.3 will throw an error. In c# all decimal points will be treated as double. Hence float value has to be suffixed with F or f)
double b=2.45;
decimal c=2.6M;(decimal values should be suffixed with M or m)
string name=”sateesh”;




Operators
Arithmetic Operators
+, -, *, /
Assignment Operator
=
Arithmetic Assignment Operators
+=, -=, *=, /=
Relational Operators
>,<,>=,<=, !=, ==
Logical Operators
&& (and), || (OR), ! (NOT)
Ternary Operator
?:
Increment Operator
++
Decrement Operator
--

Examples:-
class Program
    {
        static void Main(string[] args)
        {
            int a = 3;
            int b = a ^ 2;
            int c = a + b;

            string s1 = "Jeorge";
            string s2 = "Bush";
            string s3 = s1 + " " + s2;

Console.Write("Values of variable: a={0},b={1},c={2},s1={3},s2={4},s3={5}",a,b,c,s1,s2,s3);
          
              a+=2; // this is equivalent to a=a+b;


        }
    }
Output : Values of variable: a=34,b=102,c=56,s1=Jeorge,s2=Bush,s3=Jeorge Bush

Note: + operator on strings concatenates the strings and on numeric data will add. + operator cannot be applied ob byte arguments.

Examples on Ternary Operator
int a=23;b=35
int big=a>b?a:b;

int a=34, b=102, c=56;
int big=a>b && a>c?a:(b>c)?b:c;

Examples on Increment and Decrement Operator
int a=105;
int b=a++;  (post increment)
value of b is 105 and value a is 106;
int a=105;
int b=++a;  (pre increment)
value of b is 106 and value a is 106;