mobile ads

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

Friday, 29 November 2013

Constructors

A constructor is a method in the class which gets executed when its object is created. Whenever a class or struct is created, its constructor is called. Even if we don't write the constructor code, default constructor will be created and called first when object is instantiated and sets the default values to members of claas. A class or struct may have multiple constructors that take different arguments.
 Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.Constructors have the same name as Class
Default constructor will no take parameters and will be invoked when instance is created.
We can prevent the class instantiation by declaring the constructor as private
class sample
{
      private sample()
     {
      }
}
Classes can define the constructors with parameter also and must be called by "new" keyword.
class sample
{
   public int y;
   public sample (int i)
   {
        y=i;
    }
}
constructor with parameters.
sample s= new sample(10);
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only, and does not take access modifiers or have parameters.It is called automatically before the first instance is created or any static members are referenced.
It is called automatically to initialize the class before the first instance is created or any static members are referenced. The user has no control on when the static constructor is executed.
class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;
    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say, for example, we have only private constructor(s) in the class and if we are interested in instantiating the class, i.e., want to create an object of
 the class, then having only private constructor will not be sufficient and in fact it will raise an error. So, proper access modifies should be provided to the constructors.

Monday, 25 November 2013

Sending SMS from ASP.NET

Write a method in class file

public static void CreateRequestTOSENDSMS()
        {
            string url = "SMS gateway url, which will be provided by SMS people";//      HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("AutoLogin", "Login");
            CookieContainer myCookieContainer = new CookieContainer();
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = myCookieContainer;
            request.Method = "GET";
            request.KeepAlive = false;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            System.IO.Stream responseStream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            string srcString = reader.ReadToEnd();
             // Concat the string data which will be submit
            string formatString ="username={0}&pass={1}&senderid={2}&mtype=txt&tempid={3}&f1={4}&f2={5}&f3={6}&dest_mobileno={7}&response=Y";
            string postString = string.Format(formatString, "demo12", "demo123", "DEMOVL", "1018", "1234", "5673", "tyyty");
            byte[] postData = Encoding.ASCII.GetBytes(postString);

            // Set the request parameters
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.Referer = url;
            request.KeepAlive = false;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; CIBA)";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = myCookieContainer;
            System.Net.Cookie ck = new System.Net.Cookie("SMS", "Value of SMS cookie");
            ck.Domain = request.RequestUri.Host;
            request.CookieContainer.Add(ck);
            request.CookieContainer.Add(response.Cookies);
            // Submit the request data
            System.IO.Stream outputStream = request.GetRequestStream();
            request.AllowAutoRedirect = true;
            outputStream.Write(postData, 0, postData.Length);
            outputStream.Close();
            // Get the return data
            response = request.GetResponse() as HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            srcString = reader.ReadToEnd();
            }

The parameters "url", "formatstring" may vary from one SMS provider to another. Add these namespaces.
using System.Text;
using System.IO;
using System.Net;

Why we use Static Keyword?

The static keyword defines, that the class or property or method we declare as static does not require a previous instance of an object. In the other hand, a static method for example cannot use any instance method / instance property of the own object.

Also static defined things will be optimized by the compiler, for example that a static object is only written once in the memory and everything accesses to the same object. When we use static keyword it means there is no need to create an instance of object . Static class including a static method can called by class name. Static class can have only static methods.

Friday, 11 October 2013

Difference between Convert.ToString() and .ToString()

We can convert the integer i using i.ToString () or Convert.ToString
The basic difference between them is the Convert function handles NULLS while i.ToString () does not; it will throw a NULL reference exception error. So as good coding practice using convert is always safe.


You can create a class and override the toString method to do anything you want.

The Convert.toString converts the specified value to its equivalent string representation.

Can we define a Private Constructor

Yes, In static classes.
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class. For example:
class NLog
{
    // Private Constructor:
    private NLog() { }

    public static double e = System.Math.E;
}
The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don't use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static.

What is Abstract Class and Interface? Why we use them and at What scenario we use?

AbstractClass: Abtract class cannot be instantiated, it can only be inherited.

When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.


Interface: Interface is like contract between the base class and interface used. If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.

For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.

 If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.

For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .


Use an abstract class

  • When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.)

  • Use an abstract class to define a common base class for a family of types.

  • Use an abstract class to provide default behavior.

  • Subclass only a base class in a hierarchy to which the class logically belongs.

 Use an interface

  • When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.

  • Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.

  • Use an interface to design a polymorphic hierarchy for value types.

  • Use an interface when an immutable contract is really intended.

  • A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.

Simple way to encrypt and decrypt querystring

Encrypt code:


string data="query string";
     string encodedData = String.Empty;
       try
       {
           byte[] data_byte = Encoding.UTF8.GetBytes(data);
           encodedData = HttpUtility.UrlEncode(Convert.ToBase64String(data_byte));
        }
        catch (Exception exception)
        {
           //Log exception
        }
        return encodedData;
 
 
 
Decrypt code

string data="encoded data";
        string decodedData = String.Empty;
        try
        {
             byte[] data_byte = Convert.FromBase64String(HttpUtiltity.UrlDecode(data));
             decodedData = Encoding.UTF8.GetString(data_byte);
        }
        catch (Exception exception)
        {
             //Log exception
         }
         return decodedData;
 

Thursday, 10 October 2013

Difference between Int.Parse(), Convert.ToInt() and Int.TryParse()

Int32.parse(string)

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException

 Convert.ToInt32(string)

Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException

 Int32.TryParse(string, out int)

Int32.Parse(string, out int) method converts the specified string representation of 32-bit signed integer equivalent to out variable, and returns true if it is parsed successfully, false otherwise. This method is available in C# 2.0. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than an integer value, the out variable will have 0 rather than FormatException. When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException.

  Convert.ToInt32 is better than Int32.Parse since it returns 0 rather than an exception. But again, according to the requirement, this can be used. TryParse will be the best since it always handles exceptions by itself.