Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, 15 February 2015

Program that self replicates!

for (int i = 1; i <= 5; i++)
{
    string path= Application.ExecutablePath;
    exec = path.Insert(path.IndexOf("."), i.ToString());
    File.Copy(Application.ExecutablePath, path);
    Process.Start(path);
}

Write this code in Form_Load event , and it will replicate itself infinely.....

Friday, 9 January 2015

Nextgen Media Player


Nextgen Media Player has following features:

  • Eye Catching user interface
  • Mini & Compact  player mode
  • Fast Searching of Files
  • Playlist & Library support
  • Edit music information

 https://www.youtube.com/watch?v=y093ZW5jeWU&feature=youtu.be

Watch the working of Encrypt Decrypt V1.0- Folder Locking


Watch the working of Encrypt Decrypt V1.0- Folder Locking


https://www.youtube.com/watch?v=UyuWAptYy6o&feature=youtu.be

Code names for Windows Phones


Code names for Windows Phones

Version Codename
Windows Phone 7 Photon
Windows Phone 7.5 Mango
Windows Phone 8 Apollo
Windows Phone 8.1 Blue

Sunday, 21 December 2014

Method Overloading in C#

The process of creating more than one method in a class with same name or creating a method in derived class with same name as a method in base class is called as method overloading.


In VB.net when you are overloading a method of the base class in derived class, then you must use the keyword “Overloads”.


But in C# no need to use any keyword while overloading a method either in same class or in derived class.


While overloading methods, a rule to follow is the overloaded methods must differ either in number of arguments they take or the data type of at least one argument.


Example for Method Overloading


using System;

namespace ProgramCall
{

    class Class1
    {

        public int Sum(int A, int B)
        {
            return A + B;
        }

        public float Sum(int A, float B)
        {
            return A + B;
        }
    }

    class Class2 : Class1
    {
        public int Sum(int A, int B, int C)
        {
            return A + B + C;

        }
    }

    class MainClass
    {
        static void Main()
        {

            Class2 obj = new Class2();

            Console.WriteLine(obj.Sum(10, 20));

            Console.WriteLine(obj.Sum(10, 15.70f));

            Console.WriteLine(obj.Sum(10, 20, 30));

            Console.Read();
        }

    }
}

Output

30
25.7
60


Note

Method overloading provides more than one form for a method. Hence it is an example for polymorphism.


In case of method overloading, compiler identifies which overloaded method to execute based on number of arguments and their data types during compilation it self. Hence method overloading is an example for compile time polymorphism.

Method Overriding in C#

Creating a method in derived class with same signature as a method in base class is called as method overriding.
Same signature means methods must have same name, same number of arguments and same type of arguments.

Method overriding is possible only in derived classes, but not within the same class.


When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.


To allow the derived class to override a method of the base class, C# provides two options, virtual methods and abstract methods.

Abstract Classes and Abstract Methods in C#

The purpose of abstract class is to provide default functionality to its sub classes.

When a method is declared as abstract in the base class then every derived class of that class must provide its own definition for that method.

 An abstract class can also contain methods with complete implementation, besides abstract methods.

When a class contains at least one abstract method, then the class must be declared as abstract class.

It is mandatory to override abstract method in the derived class.

When a class is declared as abstract class, then it is not possible to create an instance for that class. But it can be used as a parameter in a method.


Abstract class in c# example



The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as abstract in Shape class and as Shape class contains abstract methods it is declared as abstract class.


using System;

namespace ProgramCall
{

    //Abstract class
    abstract class Shape1
    {

        protected float R, L, B;

        //Abstract methods can have only declarations
        public abstract float Area();
        public abstract float Circumference();

    }


    class Rectangle1 : Shape1
    {
        public void GetLB()
        {
            Console.Write("Enter  Length  :  ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");

            B = float.Parse(Console.ReadLine());
        }

      
        public override float Area()
        {
            return L * B;
        }

        public override float Circumference()
        {
            return 2 * (L + B);
        }

    }


    class Circle1 : Shape1
    {

        public void GetRadius()
        {

            Console.Write("Enter  Radius  :  ");
            R = float.Parse(Console.ReadLine());
        }

        public override float Area()
        {
            return 3.14F * R * R;
        }
        public override float Circumference()
        {
            return 2 * 3.14F * R;

        }
    }
    class MainClass
    {
        public static void Calculate(Shape1 S)
        {

            Console.WriteLine("Area : {0}", S.Area());
            Console.WriteLine("Circumference : {0}", S.Circumference());

        }
        static void Main()
        {

            Rectangle1 R = new Rectangle1();
            R.GetLB();
            Calculate(R);

            Console.WriteLine();

            Circle1 C = new Circle1();
            C.GetRadius();
            Calculate(C);

            Console.Read();

        }
    }
}

Output

Enter  Length  :  10
Enter Breadth : 12
Area : 120
Circumference : 44
Enter  Radius  :  5
Area : 78.5
Circumference : 31.4

Note

In the above example method calculate takes a parameter of type Shape1 from which rectangle1 and circle1 classes are inherited.

A base class type parameter can take derived class object as an argument. Hence the calculate method can take either rectangle1 or circle1 object as argument and the actual argument in the parameter S will be determined only at runtime and hence this example is an example for runtime polymorphism.

Virtual Methods in C#

When you want to allow a derived class to override a method of the base class, within the base class method must be created as virtual method and within the derived class method must be created using the keyword override.

When a method declared as virtual in base class, then that method can be defined in base class and it is optional for the derived class to override that method.

When it needs same definition as base class, then no need to override the method and if it needs different definition than provided by base class then it must override the method.

Method overriding also provides more than one form for a method. Hence it is also an example for polymorphism.


The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as virtual in Shape class.



using System;

namespace demo
{
    class Shape
    {

        protected float R, L, B;
        public virtual float Area()
        {

            return 3.14F * R * R;
        }

        public virtual float Circumference()
        {
            return 2 * 3.14F * R;
        }

    }

    class Rectangle : Shape
    {
        public void GetLB()
        {
            Console.Write("Enter  Length  :  ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");
            B = float.Parse(Console.ReadLine());
        }
        public override float Area()
        {

            return L * B;
        }

        public override float Circumference()
        {
            return 2 * (L + B);
        }
    }

    class Circle : Shape
    {
        public void GetRadius()
        {
            Console.Write("Enter  Radius  :  ");

            R = float.Parse(Console.ReadLine());
        }
    }

    class entryClass
    {
        static void Main()
        {

            Rectangle R = new Rectangle();
            R.GetLB();

            Console.WriteLine("Area : {0}", R.Area());

            Console.WriteLine("Circumference : {0}", R.Circumference());

            Console.WriteLine();

            Circle C = new Circle();
            C.GetRadius();

            Console.WriteLine("Area : {0}", C.Area());
            Console.WriteLine("Circumference : {0}", C.Circumference());

            Console.Read();
        }
    }
}

Output

Enter  Length  :  10
Enter Breadth : 20
Area : 200
Circumference : 60
Enter  Radius  :  25
Area : 1962.5
Circumference : 157

Sunday, 23 November 2014

How to add file security in C#?

To add file security to any file following function can be used:
Firstly add the name space:
using System.IO;
using System.Security.AccessControl;

public static void AddFileSecurity(string fileName, string account,FileSystemRights rights, AccessControlType controlType)
        {
             // Get a FileSecurity object that represents the current security settings.
             FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(account,rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

        }

Now you can use this function to add file security to any file or directory. Pass the name of file or directory as fileName. Account can be your current account or any other account. The argument rights can be any valid FileSystemRights (for e.g.: FullControl, Read, Write, Delete, Modify). The argument controlType can be any valid AccessControlType(Allow or Deny).

for e.g.:

AddFileSecurity("D:\music","Everyone",FileSystemRights.Delete,AccessControlType.Deny);

Now above file security added to D:\music ensures that no one can delete the folder. As it means 'Deny' 'Everyone' to 'Delete'

Now you can also deny current user to deny delete on this folder. For this just pass name of current user as the argument account.
To know how to get name of current user click the link below:
http://gsbprogramming.blogspot.in/2014/11/how-to-get-current-application-path.html

How to get current application path, current user's name and current application name in c#?

To get current application path:
MessageBox.Show(Application.ExecutablePath);

To get current user's name:
MessageBox.Show(System.Security.Principal.WindowsIdentity.GetCurrent ().Name);

To get current application name:
MessageBox.Show(Application.ProductName);

Friday, 10 October 2014

How to convert Stream to string?

To convert Stream to string write the following code:

public  string StreamToString(Stream stream)
{
 
 
 stream.Position = 0;

using (StreamReader reader = new StreamReader(stream))

{
 
 
return reader.ReadToEnd();
}

}
 
 
 

How to convert byte[ ] to string?

To convert byte[ ] to string write the following code:

//Convert byte[] to string
 
 
ASCIIEncoding aEncoding=new ASCIIEncoding();

string outputString= aEncoding.GetString(bytes);



Here bytes is your byte[ ]

How to convert string to byte[ ]?

 To convert a string to byte[ ] write the following code:

string stringToConvert="Input your string here";
ASCIIEncoding aEncoding = new ASCIIEncoding();

byte[] bytes = new byte[stringToConvert.Length];

//Convert string message to byte[]

bytes = aEncoding.GetBytes(stringToConvert);
 

Friday, 18 July 2014

Difference between value types and reference types.


Following are the differences between value types and reference types in C#:

  • Value types are stored on the stack where as reference types are stored on the managed heap
  • Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap
  • There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection
  • Value types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface 

Thursday, 17 July 2014

Types of comments

There are three types of comments in c#:

  1. Single line(//)
//This is a single line comment

  1. Multi line(/*   */)
/*  This is a 
multi line comment */

  1. Page/XML(///)
/// This is an XML comment

What is garbage collection?


It is a system where a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. 

Authentication and Authorisation


Authentication
Authentication is the process of verifying the identity of a user using some credentials like username and password. Authentication merely ensures that the individual is who he or she claims to be, but says nothing about the access rights of the individual.

Authorization
The process of granting or denying access to a network resource.  Authorization determines the parts of the system to which a particular identity has access. 

Authentication is required before Authorization.

For e.g. If an employee authenticates himself with his credentials on a system, authorization will determine if he has the control over just publishing the content or also editing it