Sunday, August 30, 2015

Arrays C#.NET Tutorial

Introduction
This article explain about arrays, how to declare and use in c#.net

Contents
  • Definition 
  • Types of Arrays 
  • Passing array as parameter 
  • foreach on Array

Definition:
Array is a group of elements of same type. Array is data structure that contains a number of variables called elements of array. Arrays is zero based indexed i.e. index starts from zero. Array can be of any type. Arrays are reference types

Types of Arrays

    1.     Single – Dimensional Arrays
    2.     Multi – Dimensional Arrays
    3.     Jagged Arrays


    1.     Single – Dimensional Array

Array Declaration
Syntax:
<datatype>[] <arrayname>=new <datatype>[arraysize];

int[] a=new int[12];
string[] s=new string[10];

Array Initialization
int[] n=new int[3]{1,2,3};  -- Array initialize by mentioning size
int[] n=new int[]{1,2,3};   -- Array initialization without mentioning size
string[] months=new string[] {“Jan”,”Feb”,”Mar”,”Aprl”,”May”,”Jun”,”July”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”};

Assigning Value to Arrays
n[0]=23;
months[0]=”January”;



     2.     Multi – Dimensional Array

Array Declaration
Syntax:
            int[,] n=new int[3,4];                    -----> 3 rows and 4 columns
            int[,,] n=new int[2,3,4]                ----->Three dimensional array

Array Initialization
            int[,] n=new int[2,3]{  {2,3,4}, {45,67,8} };
            int[,] n=new int[,]{  {2,3,4}, {45,67,8} };
            string[,] s=new string[,]{  {“abc”,”xyz”}, {“pqr”,”lmn”} };

Assigning Value to Arrays
            n[0,0]=1;
            s[0,0]=”sateesh”;


      3.     Jagged Array
 A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes.

     Array Declaration
Example:  
Following is array of array. It has 3 rows, 4 elements in first row, 2 elements in second row, 5 elements in third row, 3 elements in 4th row

1
2
3
4

34
23

12
13
14
151
16
7
8
9


int[][]  n=new int[4][];

n[0]=new int[4];
n[1]=new int[2];
n[2]=new int[5];
n[3]=new int[3];


Array Initialization
int[][] n=new int[][]{
                                    new int[]{1,2,3,4},
                                    new int[]{34,23},
                                    new int[]{12,13,14,151,16},
                                    new int[]{7,8,9}
                                    };
Or
n[0]= new int[]{1,2,3,4};
n[1]= new int[]{34,23};
n[2]= new int[]{12,13,14,151,16};
n[3]= new int[]{7,8,9};

or
int[][]  n={
                                    new int[]{1,2,3,4},
                                    new int[]{34,23},
                                    new int[]{12,13,14,151,16},
                                    new int[]{7,8,9}
            };


Assigning Value to Arrays
n[0][0]=1;
n[0][1]=2;
……
n[1][0]=34;




Passing Array to Parameters

class Program
{
        static void Main(string[] args)
        {
         
            int[] a = new int[] { 1, 2, 3, 4 };
            test(a);
                     for (int i = 0; i < a.Length; i++)
                Console.WriteLine(a[i]);
        }

        static void test(int[] n)
        {
            for (int i = 0; i < n.Length; i++)
                Console.WriteLine(n[i]);
            n[2]=23;
        }

}


Output:

1
2
3
4
1
23
3
4

Array ‘a’ is passed to method test as reference. Hence elements of array ‘a’ is accessed and printed on console from test method. And also update the 2nd element of array ‘a’ is updated to 23.




foreach on Array
foreach can be used with all types of arrays

class Program
{
        static void Main(string[] args)
        {
         
            int[] a = new int[] { 1, 2, 3, 4 };
            test(a);
                     for (int i = 0; i < a.Length; i++)
                Console.WriteLine(a[i]);
        }

        static void test(int[] n)
        {
         foreach (int i in n)
                Console.WriteLine(i);
            n[2]=23;
        }
}
Output:

1
2
3
4
1
23
3
4

class Program
    {
        static void Main(string[] args)
        {
         
            int[,] a = new int[,] { {1, 2, 3, 4},{7,8,9,10} };
            test(a);
        }

        static void test(int[,] n)
        {
            foreach (int i in n)
                Console.WriteLine(i);
            n[1,1]=23;
        }
    }
Output:

1
2
3
4
7
8
9
10


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.