Search...

Wednesday, June 6, 2012

params keyword in C#



The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.
No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.


using System;

namespace TestParam
{
    class Program
    {
        static void Main(string[] args)
        {

            TestCase _testCase = new TestCase();
            _testCase.TestMethod(1, 2, 3);
            _testCase.TestMethod(1, 2, 3,4,5);
            _testCase.TestMethod("a", "abc", "abcd");
            _testCase.TestMethod('a', 'b', 'c');
            _testCase.TestMethod(1,'a', "abc", "abcd");
            Console.Read();
        }
    }

    class TestCase
    {
        public void TestMethod(params object[] input)
        {
            foreach (var item in input)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine(Environment.NewLine);
        }
    }
}


Monday, June 4, 2012

Difference between ref and out in C#


using System;

namespace Difference_ref_out
{
    class Program
    {
        static void Main(string[] args)
        {

            int input1 = 10;// variable must be initialized

            Console.WriteLine("Initial value\t:\t{0}",input1);

            TestCase _testCase = new TestCase();
            _testCase.TestMethod1(ref input1);// the arg must be passed as ref

            Console.WriteLine("Processed value\t:\t{0}", input1);

            Console.WriteLine("***\t***\t***\t***");

            int input2;// variable need not be initialized

            _testCase.TestMethod2(out input2);// the arg must be passed as out

            Console.WriteLine("Processed value\t:\t{0}", input2);

            Console.Read();
        }
    }


    class TestCase
    {
        public void TestMethod1(ref int input1)
        {
            input1 = input1 + 10;
        }

        public void TestMethod2(out int input2)
        {
            input2 =10;//The out parameter 'input2' must be assigned to before control leaves the current method

        }
    }
}


Reference :  MSDN

Start windows stopped service in C#


using System;
using System.Management;
using System.ServiceProcess;

namespace StartStoppedService
{
    class Program
    {
        static void Main(string[] args)
        {
            SeviceStart _SeviceStart = new SeviceStart();
            //provide service name here and startup Type that must be automatic or manual or disabled.
            _SeviceStart.StartService("TapiSrv", "Manual");
            Console.Read();
        }
    }

    class SeviceStart
    {
        public void StartService(String serviceName, String startMode)
        {
            String status = String.Empty;
            ServiceController[] allService = ServiceController.GetServices();
            foreach (ServiceController serviceController in allService)
            {
                if (serviceController.ServiceName.Equals("TapiSrv"))
                {
                    status = serviceController.Status.ToString();
                    Console.WriteLine("Telephony Service status : {0}", status);
                    //Check service staus.
                    if (serviceController.Status.Equals(ServiceControllerStatus.Stopped))
                    {
                        bool IsStatus = StartStoppedService(serviceName, startMode);
                        if (IsStatus)
                        {
                            serviceController.Start();
                            Console.WriteLine("Telephony Service is : {0}", "Started");
                        }
                        else
                        {
                            Console.WriteLine("Telephony Service is : {0}", "Started");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Telephony Service already in running state");
                    }
                }
            }
        }

        private Boolean StartStoppedService(String serviceName, String startMode)
        {
            uint _status = 1;
            String filterService = String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName);
            ManagementObjectSearcher _managementObjectSearcher = new ManagementObjectSearcher(filterService);
            if (_managementObjectSearcher == null)
            {
                return false;
            }
            else
            {
                try
                {
                    ManagementObjectCollection _managementObjectCollection = _managementObjectSearcher.Get();
                    foreach (ManagementObject service in _managementObjectCollection)
                    {
                        //if startup type is Manual or Disabled then change it.
                        if (Convert.ToString(service.GetPropertyValue("StartMode")) == "Manual" ||
                            Convert.ToString(service.GetPropertyValue("StartMode")) == "Disabled" ||
                            Convert.ToString(service.GetPropertyValue("StartMode")) == "Automatic")
                        {
                            ManagementBaseObject _managementBaseObject = service.GetMethodParameters("ChangeStartMode");
                            _managementBaseObject["startmode"] = startMode;
                            ManagementBaseObject outParams =  service.InvokeMethod("ChangeStartMode", _managementBaseObject, null);
                            _status = Convert.ToUInt16(outParams.Properties["ReturnValue"].Value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                }
            }
            return (_status == 0);
        }

    }
}

How to exclude empty array null values while using string Split Method in C#.


using System;
using System.Linq;

namespace ExcludeEmptyArrayNullValues
{
    class Program
    {
        static void Main(string[] args)
        {
            string _stringS1 = "How to   exclude empty  array null  values    while using string     Split Method";

            string[] _stringArray = _stringS1.Split(' ');

            foreach (string item in _stringArray)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(Environment.NewLine);

            char[] charSeparators = new char[] { ' ' };
             _stringArray = _stringS1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray();
             foreach (string item in _stringArray)
             {
                 Console.WriteLine(item);
             }

             Console.Read();
        }
    }
}

How to remove empty strings from an array in C#?


using System;
using System.Linq;

namespace RemoveEmptyStringsFromAnArray
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] _UserId = { "1", "", "3", "4", "", "6", "7", "", "9", "10" };

            //Previous approach.

            string[] _NewUserId = new string[_UserId.Length];
            int iterator = 0;
            foreach (string item in _UserId)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    _NewUserId[iterator] = item;
                }
                iterator++;
            }

            foreach (string item in _NewUserId)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine(Environment.NewLine);

            //New approach.

            _UserId = _UserId.Where(UserId => (!string.IsNullOrEmpty(UserId))).ToArray();

            foreach (string item in _UserId)
            {
                Console.WriteLine(item);
            }

            Console.Read();
        }
    }
}

How to convert a string array to an integer array in C#?


using System;
using System.Linq;

namespace StringArrayToIntegerArray
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] _StringUserId = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };

            //Previous approach.

            int[] _IintUserId = new int[_StringUserId.Length];
            int iterator = 0;
            foreach (string item in _StringUserId)
            {
                int.TryParse(item, out _IintUserId[iterator]);
                iterator++;
            }

            foreach (int item in _IintUserId)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine(Environment.NewLine);

            //New approach.

            _IintUserId = new int[_StringUserId.Length];
            _IintUserId = _StringUserId.Select(UserId => int.Parse(UserId)).ToArray();

            foreach (int item in _IintUserId)
            {
                Console.WriteLine(item);
            }

            Console.Read();
        }
    }
}

Take Screenshot in C#


using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace TakeScreenshot
{
    class Program
    {
        static void Main(string[] args)
        {
            new Screenshot().TakeScreenshot();
        }
    }

    class Screenshot
    {
        public Screenshot() { }

        public void TakeScreenshot()
        {
            Bitmap bitmap = new Bitmap(1024, 768);

            Graphics graphics = Graphics.FromImage(bitmap as Image);

            graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

            bitmap.Save("c:\\screenshot.jpeg", ImageFormat.Jpeg);

        }
    }
}

Override ToString Method in C#

using System;

namespace OverrideToString
{
class Program
{
static void Main(string[] args)
{
Person _person=new Person("Kaushik","Mistry","Delhi","8800xxxxxx");
Console.Write(_person.ToString());
Console.Read();
}
}

class Person
{
public Person(String firstName,String lastName,String address,String phoneNumber)
{
FirstName=firstName;
LastName=lastName;
Address=address;
PhoneNumber=phoneNumber;
}

public String FirstName { get; set; }
public String LastName { get; set; }
public String Address { get; set; }
public String PhoneNumber { get; set; }

public override string ToString()
{
return String.Format("First Name\t:\t{0}\nLast Name\t:\t{1}\nAddress\t\t:\t{2}\nPhone Number\t:\t{3}",
FirstName,
LastName,
Address,
PhoneNumber);
}
}
}

********************************************************************************