Tuesday, 20 December 2016

ViewData, ViewBag and TempData

ViewBag

- ViewBag is used to send a small amount of data to the view.
- There may be some situation where you want to transfer some temporary data to view which is not included in the model object.
- The viewBag is a dynamic type property of ControllerBase class.
- It does not retain value when redirection occurs, It is available only for Current Request.
- ViewBag is a dynamic property and it makes use of the C# 4.0 dynamic features.

  public class DemoController : Controller
    {
        IList<Car> CarList = new List<Car>() {
                    new Car(){ CarName="i10", CarColor="Black",CarMileage=18.2 },
                    new Car(){ CarName="EON", CarColor="Silver", CarMileage=18.2 },
                    new Car(){ CarName="Swift", CarColor="Red", CarMileage=18.2},
                    new Car(){ CarName="Verna", CarColor="Black", CarMileage=18.2},
                    new Car(){ CarName="Ciaz", CarColor="Silver", CarMileage=18.2}
                };

        public ActionResult Index()
        {
            ViewBag.TotalCar = CarList.Count();
            return View();
        }
    }  
   
ViewData

- ViewData is similar to ViewBag, It can also be used to send data from controller to view.
- It is a dictionary, which possesses key-value pairs, where each key must be a string.
- Viewdata last long only for current HTTP request.

public class DemoController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Simple"] = "This string is stored in viewData.";
            return View();
        }
    }
   
    To get back the value from viewData write below line in view.
   
    <h4>@ViewData["Simple"]</h4>
   
TempData

- TempData retain value across subsequent HTTP Request
- It can be used to maintain data between controller actions as well as redirects.
- It internally stores data in session but it gets destroyed earlier than a session.

Saturday, 1 October 2016

OOPS Concepts, Features & Explanation with Example.

- OOP = Object Oriented Programming.
- It is a programming technique which provides an efficient way to manage Object and its behaviour across a system.
- It provides a way to show/hide relevant data.
- It provides an efficient way for code reusability.


Here I will explain you important concepts of OOP.

(1) Class

- The class can be considered as a blueprint for an object.
- A class is a collection of object.
- It is compulsory to create a class for representation of data.
- Class do not occupy memory space, so it is a merely logical representation of data.

The syntax for declaring a class.

public class College
{
       //your code goes here..
}

(2) Object

- The object is variable of type Class.
- Object possess property and behaviour.
- As a class do not occupy any memory, so to work with real-time data representation you need to make an object of the class.

Syntax
- Here is the syntax to create an object(we just created above).

College objCollege = new College();

(3) Encapsulation

- Encapsulation is the process of keeping item into one logical unit.
- Encapsulation is a technique used to protect the information in an object from another object.
- The concept of data hiding or information hiding can be achieved by encapsulation.
- In c#,Encapsulation is implemented using the access modifier keywords. C# provides 5 types of access modifier,
  which are listed below.
  (i) Public : Public members are accessible by any other code in the same  assembly or another            assembly that reference it.
  (ii)Private : Private member can only be accessed by code in the same class.
  (iii)Protected: Protected member can only be accessed by code in the same class or in a derived class.
  (iv)Internal : Internal member can be accessed by any code in the same assembly, but not from another assembly.
  (v) Protected Internal : Protected Internal member can be accessed by any code in the same assembly, or by any derived class in another assembly.

(4) Polymorphism

- Polymorphism is an ability to take more than one form in different case/scenario.
- It can make different logical units but with the same name. Its behaviour is executed based on input or the way it is called.

class PolymorphismExample
    {
        public void Add(int p_Value1, int p_Value2)
        {
            Console.WriteLine("Result ={0}", p_Value1 + p_Value2); // This will perform addition of p_Value1 and p_Value2
        }

        public void Add(string p_Value1, string p_Value2)
        {
            Console.WriteLine("Result ={0}", p_Value1 + p_Value2); // This will perform concatenation of p_Value1 and p_Value2
        }
    }
 
(5) Inheritance

- Inheritance provides a way to inherit member of another class.
- It Provides a way to reuse code which is already written.

class InheritanceExample
    {
        public abstract class AllCar
        {
            public abstract string GetCarName();
        }

        public class HondaSeries : AllCar
        {
            //this method name matches with same signature/parameters in AllCar class
            public override string GetCarName()
            {
                return "Car Name is Honda City";
            }
        }

        public static void Main(string[] args)
        {
            AllCar objAllCar = new HondaSeries();
            Console.WriteLine(objAllCar.GetCarName());
            Console.Read();
        }
    }

Sunday, 11 September 2016

C# Program to Check Whether the Given Number is a Prime number or not.

This C# Program Checks Whether the Given Number is a Prime number or not.
It will ask a user to enter a number and check whether it is prime or not.

using System;

namespace CsharpProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a Number : ");

            int _Number;

            _Number = Convert.ToInt32(Console.ReadLine());

            int _Flag;

            _Flag = 0;

            for (int i = 1; i <= _Number; i++)
            {
                if (_Number % i == 0)
                {
                    _Flag++;
                }
            }

            if (_Flag == 2)
            {
                Console.WriteLine("Entered Number is a Prime Number.");
            }
            else
            {
                Console.WriteLine("Not a Prime Number");
            }
            Console.ReadKey();
        }
    }
}


Mathematical Calculation in C# using Math Class.

Math class can be use for maths related calculation.

some of useful math class methods are illustrated with example.

- Math.BigMul() : use for getting multiplication of two number.
- Math.Ceiling() : use for getting number that is greater than or equal to the specified double-precision floating-point number.
- Math.Floor() : use for getting integer that is less than or equal to the specified double-precision floating-point number.
- Math.Sin() : Returns the sine of the specified angle.
- Math.Cos() : Returns the cosine of the specified angle.
- Math.Tan() : Returns the tangent of the specified angle.
- Math.Sqrt() : Returns the square root of a specified number.
- Math.Max() : Returns the larger of two number.
- Math.Min() : Returns the smaller of two number.

using System;

namespace CsharpProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            double Multiplication, CeilingValue, FloorValue;

            Multiplication = Math.BigMul(7823, 2345);

            CeilingValue = Math.Ceiling(76.43);

            FloorValue = Math.Floor(76.43);

            Console.WriteLine("7823 * 2345 = " + Multiplication);

            Console.WriteLine("Ceiling value of 76.43 is " + CeilingValue);

            Console.WriteLine("Floor value of 76.43 is " + FloorValue);

            double sin_Result, cos_Result, tan_Result;

            sin_Result = Math.Sin(30);
            cos_Result = Math.Cos(30);
            tan_Result = Math.Tan(30);

            Console.WriteLine("Sin of angle 30 is " + sin_Result);
            Console.WriteLine("Cos of angle 30 is " + cos_Result);
            Console.WriteLine("Tan of angle 30 is " + tan_Result);

            double SquareRoot;

            SquareRoot = Math.Sqrt(144);

            Console.WriteLine("Square Root of 144 is " + SquareRoot);

            int MaxValue, MinValue;

            MaxValue = Math.Max(34, 76);
            MinValue = Math.Min(34, 76);

            Console.WriteLine("Maximum of 34 and 76 is " + MaxValue);
            Console.WriteLine("Minimum of 34 and 76 is " + MinValue);

            Console.ReadKey();
        }
    }
}

Hello World in C#.Net

Hello World Program in C#.Net

using System;

namespace CsharpProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
    }
}


Here Console.WriteLine() is use to display message to console screen.
Console.ReadKey(); is used to retain console screen , it will wait for user to press any key.


c# program which ask for your name and write it back with Greet.

using System;

namespace CsharpProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string Name;
            Console.WriteLine("Please enter your name!");
            Name = Console.ReadLine();

            Console.WriteLine("Hello, Your name is " + Name);
            Console.ReadKey();
        }
    }
}

Console.ReadLine() is use to read message entered by user.

Friday, 9 September 2016

you can call javascript function from code behind using ScriptManager.

Declare required function in javascript,

<script type="text/javascript" language="javascript">
    function GetMessage() {
        alert("hello!")
    }
</script>

Write below line where you want to call Javascript function,
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "smMain", "GetMessage();", true);

Tuesday, 2 August 2016

Verbatim String

This are type of string which do not require to be escaped, like a filename:

string myFileName = "C:\\DotNet\\ReadMe.txt"; Can be replace with
string myFileName = @"C:\DotNet\ReadMe.txt";

The @ symbol means to read that string literally.

verbatim string can also have multi line.

String MultilineString = @" This is
                                           a multi line
                                          string which is span
                                          in 4 lines";

Friday, 29 July 2016

Hide Label Tag after some seconds(3 Second) in ASP.NET

Add below java script in .aspx page

 <script type="text/javascript">
        function HideLabelText() {
            var _Second = 3; // Specify duration in second
            setTimeout(function () {
                document.getElementById("<%=lblMessage.ClientID %>").style.display = "none";
            }, _Second * 1000); 
        };
  </script>
 
  lblMessage is a ID of Label control
  _Second = 3 i.e It will hide label after 3 seconds , you can change this as per your need.

Add below lines in the event handler in your code.

C#.NET : ClientScript.RegisterStartupScript(this.GetType(), "alert", "HideLabelText();", true); 
VB.NET : ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "HideLabelText();", True)

Tuesday, 14 June 2016

Visual Studio 2013 Tips and Tricks



(1) Matching brace/comment/region/quote
                "Ctrl+]" can be use to the match brace, region, quote. It can also be use to the match comment, region or quote depending on where is the cursor now.
               
(2) Create Property By Shortcut
                Creating Property are very common to get and/or set values. For writing Property you do not need to write it completely. just type PROP and then press TAB key twice.
               
(3) Vertical block selection.
                Select Alt key and then select the area you want with your mouse.
               
(4) Auto Complete
                Using intellisense in Visual Studio you can complete method, variable, class, object, property etc. by just writing its initial. Use Ctrl + Space or Alt + Right Arrow.

(5) Bookmark
                Using Bookmark you can navigate to code in visual studio.
    Create/Remove Bookmark - Ctrl+K, Ctrl+K
    Move to next bookmark - Ctrl+K, Ctrl+N
    Move to previous bookmark - Ctrl+K, Ctrl+P
    Clear all bookmarks - Ctrl+K, Ctrl+L
               
(6) Build and Debug
               
    Build - Ctrl+Shift+B
    Run - Ctrl+F5
    Debug - F5
    Cycle through build errors - F8
               
(7) Move Code Up or Down
                If you want to move line up then just keep cursor on that line and press "Alt + Up Arrow key" similar to this if you want to move line down then just keep cursor on that line and press "Alt + Down Arrow key".
               
(8) Comment Code block
                Comments are used for documentation purpose or temporarily disable the code. You can comment block of code by selecting that portion and then press Ctrl K + C. To uncomment code select code block and press Ctrl K + U.
               
(9) Switch between Currently open tabs.
                You can open lastly visited tab in visual studio by pressing Ctrl + Tab and for opposite direction Ctrl + Shift + Tab