Friday, February 18, 2011

Transactions in .net?

A transaction symbolizes code or a set of components or procedures which must be executed as a unit. All the methods must execute successfully or the complete unit fails. A transaction can be described to cover the ACID properties for mission critical applications. 

What are the ACID Properties?

  1. Atomicity
  2. Consistency
  3. Isolation
  4. Durability

Transfer Funds Sample 

We will build a sample ASP.NET web form for a fictitious bank which will transfer a specified amount from one account to another - if the  balance in the first account is sufficient to cover the transfer. 
First we need to create the database we will using in the example.
I used an MS Access database containing only one table : tblAccount.
 
Field Name
Field Type
AccNumber
Text
dBalance
Double
Listing 1 displays the code for the web page. Save the web page as Test.aspx.
First include the Namespaces required for accessing the data. 
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
Here is the function which processes the transaction for transferring the data.
For this example we assume that the transaction should be rolled back (Cancelled) if :
  1. There are insufficient funds in the From Account to cover the transfer. 
  2. Either of the SQL statements for marking credit or debit in the To and From accounts results in an error. 
We create the Connection needed to connect to our database.
OleDbConnection Conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:\\inetpub\\wwwroot\\dotnet\\test.mdb;");
In real life we would use Server.MapPath to map to the location of the database. 
We use the Data Reader oReader to check the validity of the amount in the From Account. The crux of the function is to execute the two SQL queries one to subtract the amount from the From Account and one to add the same amount to the balance in the To Account. 
We start the transaction after we have created the data objects .The transaction should be kept as short as possible to avoid concurrency issues and to enable maximum number of positive commits.
Create the transaction and associate the transaction with the OleDbCommand as follows: 
OleDbTransaction Trans = Conn.BeginTransaction(IsolationLevel.ReadCommitted);cmd.Transaction = Trans;
Within the Try block run the transaction and Commit the transaction if everything proceeds smoothly. Committing a transaction will write the changes to the database. 
If there is an exception we will Roll Back the transaction. This will cancel any changes that have been carried out as a part of the transaction. This is how we maintain the integrity of our transaction.
try
{
    oReader = cmd.ExecuteReader();
    oReader.Read();
    dCurrBalance = oReader.GetDouble(0);
    oReader.Close();
    if (dCurrBalance < Convert.ToDouble(txtAmt.Text))
    {
        throw (new Exception("Insufficient funds for transfer"));
    }
    strSQL = "Update tblAccount set dbalance =  dBalance - " + txtAmt.Text + " where AccNumber = '" +
    txtFrom.Text + "'";
    cmd.CommandText = strSQL;
    cmd.ExecuteNonQuery();
    strSQL = "Update tblAccount set dbalance =  dBalance + " + txtAmt.Text + " where AccNumber = '" +
    txtTo.Text + "'";
    cmd.CommandText = strSQL;
    cmd.ExecuteNonQuery();
    Trans.Commit();
    lbl.Text = "true";
}
catch (Exception ex)
{
    Trans.Rollback();
    lbl.Text = "Error: " + ex.Message;
}
finally
{
    Conn.Close();}
Note how we Throw an exception if the balance in the From Account is less than the transfer amount. 
throw (new Exception("Insufficient funds for transfer")); 
The string passed in the constructor of the Exception object initializes the message for the Exception that will be raised.
Finally we indicate the results of the transfer activity to the user .
lbl.Text = "Fund Transfer of Amount " + txtAmt.Text + " from Account " + txtFrom.Text + " to Account " + txtTo.Text + " was executed successfully.";ORlbl.Text = "Error: " + ex.Message; 
In real life, we would have converted the error message to a more meaningful and user friendly message. 
Here is the complete code listing for the web form.

Listing 1: Test.aspx : Transfer Funds Web Page. 
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<head>
    <title>Transfer Funds</title>
 
    <script language="C#" runat="server">
        protected void TransferFund(Object Sender, EventArgs e)
        {
            String strSQL = "Select dBalance FROM tblAccount where AccNumber='" + txtFrom.Text + "'";
            double dCurrBalance;
            OleDbConnection Conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA
            SOURCE=c:\\inetpub\\wwwroot\\dotnet\\test.mdb;");
            Conn.Open();
            OleDbDataReader oReader;
            OleDbCommand cmd = new OleDbCommand(strSQL, Conn);
            OleDbTransaction Trans = Conn.BeginTransaction(IsolationLevel.ReadCommitted);
            cmd.Transaction = Trans;
            try
            {
                oReader = cmd.ExecuteReader();
                oReader.Read();
                dCurrBalance = oReader.GetDouble(0);
                oReader.Close();
                if (dCurrBalance < Convert.ToDouble(txtAmt.Text))
                {
                    throw (new Exception("Insufficient funds for transfer"));
                }
                strSQL = "Update tblAccount set dbalance =  dBalance - " + txtAmt.Text + " where AccNumber = '"
                + txtFrom.Text + "'";
                cmd.CommandText = strSQL;
                cmd.ExecuteNonQuery();
                strSQL = "Update tblAccount set dbalance =  dBalance + " + txtAmt.Text + " where AccNumber = '"
                + txtTo.Text + "'";
                cmd.CommandText = strSQL;
                cmd.ExecuteNonQuery();
                Trans.Commit();
                lbl.Text = "true";
            }
            catch (Exception ex)
            {
                Trans.Rollback();
                lbl.Text = "Error: " + ex.Message;
            }
            finally
            {
                Conn.Close();
            } 
        } 
 
    </script>
 
</head>
<body>
    <form id="frmTransfer" runat="server">
        <asp:Label ID="lblFrom" runat="server">Enter the account number from which to transfer
          funds</asp:Label>
        <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox><br />
        <asp:Label ID="lblTo" runat="server">Enter the account number to which to transfer funds</asp:Label>
        <asp:TextBox ID="txtTo" runat="server"></asp:TextBox><br />
        <asp:Label ID="lblAmount" runat="server">Enter the amount to transfer</asp:Label>
        <asp:TextBox ID="txtAmt" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" OnClick="TransferFund" runat="server" Text="Start Transfer">
        </asp:Button><br />
        <asp:Label ID="lbl" runat="server"></asp:Label>
    </form>
</body>
</html>
TransaASPDPL2.gif

Figure 1 : Front end web page for the transaction example.
TransaASPDPL3.gif

Figure 2 : Successfully Committed Transactions.


TransaASPDPL4.gif
Figure 3: Insufficient Funds RollBack ! 
 
Note:  When the transaction is rolled back (Insufficient funds or an error in the SQL statements) the Balance field in both the From Account and To Account in the database is not updated.

What is service-oriented architecture(SOA)


The following diagram is an example of a service-oriented architecture using Web services. Click on the yellow boxes below to obtain more information on a subject.
Example enterprise service-oriented architecture

Amidst all the SOA-related activity that is currently underway, there still remains a significant amount of confusion as to what exactly constitutes a service-oriented architecture. Some qualify an SOA project by the fact that Web services technologies are being used, while others classify SOA as a Web-centric variation of object-oriented design.

What has become more clear than the actual meaning of SOA is the strategic vision that has emerged around it. This vision is comprised of a set of goals and benefits that most stakeholders fully expect to see realized when they support and commit to SOA initiatives. However, because the "SOA" acronym has been used to brand products, technologies, and even projects without a clear understanding of its meaning, many of these expectations have been and will continue to remain unfulfilled. For example, the common (and dangerous) assumption that a solution is service-oriented solely because it uses Web services has led to much disappointment.

There is, in fact, a wealth of information out there that communicates the meaning of SOA in detail. The only problem is that this information is fragmented - distributed across marketing literature, technology specifications, media reports, and independent research efforts. While there is no one recognized definition of SOA, there is a baseline of concepts and principles that exists among all of the organizations, platforms, and initiatives that have influenced and continue to shape the SOA movement. For any IT professional, project team, or organization interested in moving ahead with SOA, this baseline perspective is extremely important to understand because it reflects a current, industry-level, and vendor-agnostic representation of what SOA is in the real world.

My third book in the Prentice Hall Service-Oriented Computing Series from Thomas Erl (entitled SOA: Principles of Service Design) is dedicated to exploring the service-orientation design paradigm and service design techniques. It begins with some introductory chapters that leverage years of on-going industry research as part of my involvement in projects for SOA Systems Inc. This research has been synthesized to establish the aforementioned baseline perspective of SOA, and to further broaden the discussion to encompass the service-orientation design paradigm and service-oriented computing as a whole.

The book manuscript (including the content on this site) was subjected to a rigorous technical review involving over 60 reviewers from different vendors, organizations, and professions across North America, Europe, and Asia. The book ended up being formally endorsed by members of major SOA vendors, including IBM, Microsoft, Oracle, BEA, Sun, SAP, HP, and Intel.

With permission from Prentice Hall, I was able to publish some of the book’s introductory content on a modest network of Web sites (in exchange for posting book cover images on Web page footers). The primary reason these sites exist is to provide convenient on-line reference content for readers of the book series. It also helps us avoid publishing redundant content in the books, so that each title remains focused on its specialized subject matter.

WhatIsSOA.com essentially acts as the starting point for these sites by establishing some fundamental terminology and providing specific coverage of the strategic goals and benefits that collectively represent the modern-day vision of SOA and service-oriented computing. The last set of pages provide further supplementary content that addresses implementation technologies, processes, and other deliverables that are common in real world SOA projects.

Although this site positions SOA within the service-oriented computing platform, it only hints at what it means for solution logic to be considered "service-oriented." That particular topic deserves a study of its own, which is why I publishedwww.SOAPrinciples.com, a separate Web site dedicated to an exploration of service-orientation.




Data Types in sqlserver


In SQL Server, each column, local variable, expression, and parameter has a related data type. A data type is an attribute that specifies the type of data that the object can hold: integer data, character data, monetary data, date and time data, binary strings, and so on.
SQL Server supplies a set of system data types that define all the types of data that can be used with SQL Server. You can also define your own data types in Transact-SQL or the Microsoft .NET Framework. Alias data types are based on the system-supplied data types. For more information about alias data types, see Working with Alias Data Types. User-defined types obtain their characteristics from the methods and operators of a class that you create by using one of the programming languages support by the .NET Framework. For more information, seeWorking with CLR User-defined Types.
When two expressions that have different data types, collations, precision, scale, or length are combined by an operator, the characteristics of result are determined by the following:
  • The data type of the result is determined by applying the rules of data type precedence to the data types of the input expressions. For more information, see Data Type Precedence (Transact-SQL).
  • The collation of the result is determined by the rules of collation precedence when the result data type ischar, varchar, text, nchar, nvarchar, or ntext. For more information, see Collation Precedence (Transact-SQL).
  • The precision, scale, and length of the result depend on the precision, scale, and length of the input expressions. For more information, see Precision, Scale, and Length (Transact-SQL).
SQL Server provides data type synonyms for ISO compatibility. For more information, see Data Type Synonyms (Transact-SQL).

Data types in SQL Server are organized into the following categories:
Exact numericsUnicode character strings
Approximate numericsBinary strings
Date and timeOther data types
Character strings
In SQL Server, based on their storage characteristics, some data types are designated as belonging to the following groups:
  • Large value data types: varchar(max), nvarchar(max), and varbinary(max)
  • Large object data types: text, ntext, image, varchar(max), nvarchar(max), varbinary(max), and xml
    Note Note
    sp_help returns -1 as the length for the large-value and xml data types.

Exact Numerics

Approximate Numerics

Date and Time

Character Strings

Unicode Character Strings

Binary Strings

Other Data Types


example for table datatype


--code for userdefinefunction
-----------------------
create function div(@a decimal(14,2),@b int)
returns decimal(14,2)
as 
begin
declare @c decimal(14,2)
set @c=@a/@b
return @c
end
-------------------
--call the user define function
--------------------
select dbo.div(12.0,2)
---------------
--create a procedure name is sai which contain one parameter name is [@discount_product_code] which is varachar type and contains two userdefine table type[table datatype] variable [1-@sai and 2-@sai1]
--------------------
CREATE PROC sai(@discount_product_code varchar(30))
 AS
DECLARE @sai TABLE(recv_qty decimal(14,2),discountlist_quantity int)
INSERT INTO @sai
SELECT   sum(recv_qty)as recv_qty , Mas_Discount_Product_List.discountlist_quantity 

FROM         Mas_Stock INNER JOIN
                      Mas_Discount_Product_List ON Mas_Stock.product_code = Mas_Discount_Product_List.product_code 
where Mas_Discount_Product_List.discount_product_code like @discount_product_code+'%'
and Mas_Stock.branch_code='NEO2AND1' and Mas_Stock.warehouse_code='NEO6WHS1' and Mas_Stock.financial_year='2010-2011' group by Mas_Discount_Product_List.product_code,Mas_Discount_Product_List.discountlist_quantity

DECLARE @sai1 TABLE(recv_qty decimal(14,2),discountlist_quantity int,availableitem decimal(14,2))
INSERT INTO @sai1

SELECT recv_qty,discountlist_quantity,DBO.div(recv_qty,discountlist_quantity) 
FROM @sai  
select min(availableitem) from @sai1


----------------------

---call the procedure
---------------------
exec sai 'dp001'
-----------------
--drop the proc 
-------------
drop proc sai


Wednesday, February 16, 2011

Sending an SMS Message with ASP.NET

For Send SMS Through Code:

C#.net:

Step 1: Add Web Reference :
        http://www.spiritssoft.com/webservice/sendway2sms.asmx
Step 2: Add This "using com.spiritssoft.www;"
Step 3: Create a Object "SendWay2Sms smsobj = new SendWay2Sms();"
Step 4:
        string strResult = smsobj.sendSmsSpiritsSoft("UserName", "Password", "Number", "message");
  
    strResult  : Recieving the Result from Webservice

Note:
     - For Group SMS , Number seperated by commas(,).
     - Message should be Only 125 characters,
     - If No username , password form way2sms.com it will send message
       through Spirits Soft Technology Default Number.

Sending SMS using .NET through a Web service

 

This article is about sending SMS using .NET through web service. With the help of this article we can easily understand how to use web service in .NET and also you will get some information about SMS, GPRS etc. This web service will help you to give the notification if the service unable to deliver.

How does it work?

Initially when undergoing this study I think sending SMS to different services will be a problem, for sending SMS we have to tie up with all the services it is not possible at all, while studying this most of the services provides GPRS(General Packet Radio Service ) facility. GPRS has more functionality and here we are going to use only one that is Internet email services. So it makes our work little easier. After that I think how to find out the services for that particular mobile number. Now it became very critical, then I found a web service that provides us all the information that we needed. Let we discuss in upcoming paragraph.

What is GPRS?

With GPRS you can enjoy a continuous wireless connection to data networks and access your favorite information and entertainment services. GPRS technology allows mobile phones to be used for sending and receiving data over an Internet Protocol (IP)-based network. GPRS as such is a data bearer that enables wireless access to data networks like the Internet. The applications using GPRS are WAP, MMS, SMS, Java and the PC dial-up (for example, Internet and e-mail).
Internet email services come in the form of a gateway service where the messages are not stored, or mailbox services in which messages are stored. In the case of gateway services, the wireless email platform simply translates the message from SMTP, the Internet email protocol, into SMS and sends to the SMS Center. In the case of mailbox email services, the emails are actually stored and the user gets a notification on their mobile phone and can then retrieve the full email by dialing in to collect it, forward it and so on.
Upon receiving a new email, most Internet email users do not currently get notified of this fact on their mobile phone. When they are out of the office, they have to dial in speculatively and periodically to check their mailbox contents. However, by linking Internet email with an alert mechanism such as SMS or GPRS, users can be notified when a new email is received.
For more information about GPRS click here

Using the code

In this article I am using a web service which already exists. Since this web service is tie up with ICQ instant messaging service make our work easier. With the help of this web service we can able to send SMS to various countries like India, US, UK, Malaysia, Japan etc. In this article I have used the web service from www.webservicex.com they are providing Webs Service Definition Language (WSDL) link for sending SMS.
Here I m attaching the sample code for sending SMS.
Collapse
private void Send_Click(
 object sender, System.EventArgs e)
    {
      try
      {
        SmsTest.net.webservicex.www.SendSMS smsIndia= 
          new SmsTest.net.webservicex.www.SendSMS();
        SmsTest.com.webservicex.www.SendSMSWorld smsWorld =  
          new SmsTest.com.webservicex.www.SendSMSWorld();
        if(rdoType.SelectedValue == "1")
          smsIndia.SendSMSToIndia(txtMobileNo.Text.Trim(), 
            txtEmailId.Text.Trim(), txtMessage.Text);
        else 
          smsWorld.sendSMS(txtEmailId.Text.Trim(), 
           txtCountryCode.Text.Trim(), txtMobileNo.Text.Trim(), 
           txtMessage.Text);
        lblMessage.Visible = true;
        lblMessage.Text="Message Send Succesfully";
      }
      catch(Exception ex)
      {
        lblMessage.Visible = true;
        lblMessage.Text="Error in Sending message"+ex.ToString();
      }
    }

    private void rdoType_SelectedIndexChanged(
     object sender, System.EventArgs e)
    {
      if(rdoType.SelectedValue =="1")
        txtCountryCode.Enabled = false;
      else
        txtCountryCode.Enabled = false;

    }




Sending SMS using .NET

When do you want to send SMS via applications? There could be plethora of use cases for this. The simplest one is to validate a mobile number, and some of the complicated ones could involve sending an SMS after a huge workflow is complete or gone wrong. Let's find out ways to send SMS using C#/VB.NET.

Sending SMS

What are the ways in which one can send SMS?
  • Using a GSM modem:
    • Better when one wants to implement offline applications and a very small number of SMS go every minute, usually few 10s.
  • Using web service:
    • Better when it is an online application and a very few number of SMS go every minute, usually few 10s.
  • Using endpoints given by service the provider:
    • Better when the number of SMS exceeds a few 100s per minute. Service provider demands a commitment of at least 100,000 SMS per month.
Sending SMS via a webservice or endpoints is simplest. In contrast, sending SMS via GSM modem has a few additional steps to take care of. Let's understand each in detail.

Sending SMS via GSM modem

  1. First, find the best GSM modem that suits the needs. Specifications are available here.
  2. Understand the AT Command set required to communicate with the modem.
  3. Connect the modem to the computer according to the setup guide specified in the manual provided with the GSM modem. Sample connection details of the Maestro 20/100 modem can be found here. The connection settings explained are common for most GSM modems.
  4. Create a new Windows application or Web Application.
  5. Add a new class file with the name SMSCOMMS.
  6. Copy and paste the code given below into the class.

Coding with VB.NET

If you are using VB.NET for coding the application, you can use the class shared by Jeanred. Details are as follows:
Collapse
Option Explicit On    

Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.PortsPublic Class SMSCOMMS    

Private WithEvents SMSPort As SerialPort    

    Private SMSThread As Thread
    Private ReadThread As Thread
    Shared _Continue As Boolean = False
    Shared _ContSMS As Boolean = False
    Private _Wait As Boolean = False
    Shared _ReadPort As Boolean = False
    Public Event Sending(ByVal Done As Boolean)
    Public Event DataReceived(ByVal Message As String)    

    Public Sub New(ByRef COMMPORT As String)
        SMSPort = New SerialPort
        With SMSPort
            .PortName = COMMPORT
            .BaudRate = 9600
            .Parity = Parity.None
            .DataBits = 8
            .StopBits = StopBits.One
            .Handshake = Handshake.RequestToSend
                .DtrEnable = True
              .RtsEnable = True
            .NewLine = vbCrLf
        End With
        ReadThread = New Thread(AddressOf ReadPort)
        End Sub    

    Public Function SendSMS(ByVal CellNumber As String, 
        ByVal SMSMessage As String) As Boolean
        Dim MyMessage As String = Nothing
        'Check if Message Length <= 160

        If SMSMessage.Length <= 160 Then
            MyMessage = SMSMessage
        Else
              MyMessage = Mid(SMSMessage, 1, 160)
        End If
        If IsOpen = True Then
                SMSPort.WriteLine("AT+CMGS=" & CellNumber & vbCr)
                _ContSMS = False
                SMSPort.WriteLine(MyMessage & vbCrLf & Chr(26))
                _Continue = False
                RaiseEvent Sending(False)
        End If
    End Function    

    Private Sub ReadPort()
          Dim SerialIn As String = Nothing
        Dim RXBuffer(SMSPort.ReadBufferSize) As Byte
        Dim SMSMessage As String = Nothing
        Dim Strpos As Integer = 0
        Dim TmpStr As String = Nothing    

            While SMSPort.IsOpen = True
            If (SMSPort.BytesToRead <> 0) And (
                SMSPort.IsOpen = True) Then
                While SMSPort.BytesToRead <> 0
                    SMSPort.Read(RXBuffer, 0, SMSPort.ReadBufferSize)
                    SerialIn = 
                        SerialIn & System.Text.Encoding.ASCII.GetString(
                        RXBuffer)
                    If SerialIn.Contains(">") = True Then
                        _ContSMS = True
                    End If
                    If SerialIn.Contains("+CMGS:") = True Then
                        _Continue = True
                        RaiseEvent Sending(True)
                        _Wait = False
                        SerialIn = String.Empty
                        ReDim RXBuffer(SMSPort.ReadBufferSize)
                    End If
                End While
                RaiseEvent DataReceived(SerialIn)
                SerialIn = String.Empty
                ReDim RXBuffer(SMSPort.ReadBufferSize)
            End If
        End While
    End Sub    

    Public ReadOnly Property IsOpen() As Boolean
        Get
            If SMSPort.IsOpen = True Then
                IsOpen = True
            Else
                IsOpen = False
            End If
        End Get
    End Property    

    Public Sub Open()
        If IsOpen = False Then
            SMSPort.Open()
            ReadThread.Start()
        End If
    End Sub    

    Public Sub Close()
        If IsOpen = True Then
            SMSPort.Close()
        End If
    End Sub    

End Class
The above class exposes three functions: Open, SendSMS and Close. While creating the instance of the class, provide the port to which the modem is connected. In a Windows application, follow the steps below:
Collapse
SMSEngine = New SMSCOMMS("COM1")
SMSEngine.Open()
SMSEngine.SendSMS("919888888888","SMS Testing")
SMSEngine.Close()

Coding with C#

The C# implementation of the code is as follows:
Collapse
using System;
using System.Threading;
using System.ComponentModel;
using System.IO.Ports;   

public class SMSCOMMS
{
    private SerialPort SMSPort;
    private Thread SMSThread;
    private Thread ReadThread;
    public static bool _Continue = false;
    public static bool _ContSMS = false;
    private bool _Wait = false;
    public static bool _ReadPort = false;
    public delegate void SendingEventHandler(bool Done);
    public event SendingEventHandler Sending;
    public delegate void DataReceivedEventHandler(string Message);
    public event DataReceivedEventHandler DataReceived;    

    public SMSCOMMS(ref string COMMPORT)
    {
        SMSPort = new SerialPort();
        SMSPort.PortName = COMMPORT;
        SMSPort.BaudRate = 9600;
        SMSPort.Parity = Parity.None;
        SMSPort.DataBits = 8;
        SMSPort.StopBits = StopBits.One;
        SMSPort.Handshake = Handshake.RequestToSend;
        SMSPort.DtrEnable = true;
        SMSPort.RtsEnable = true;
        SMSPort.NewLine = System.Environment.NewLine;
        ReadThread = new Thread(
            new System.Threading.ThreadStart(ReadPort));
    }    

    public bool SendSMS(string CellNumber, string SMSMessage)
    {
        string MyMessage = null;
        //Check if Message Length <= 160

        if (SMSMessage.Length <= 160)
            MyMessage = SMSMessage;
        else
            MyMessage = SMSMessage.Substring(0, 160);
        if (IsOpen == true)
        {
            SMSPort.WriteLine("AT+CMGS=" + CellNumber + "r");
            _ContSMS = false;
                SMSPort.WriteLine(
                MyMessage + System.Environment.NewLine + (char)(26));
              _Continue = false;
            if (Sending != null)
                Sending(false);
        }
        return false;
    }    

    private void ReadPort()
    {
        string SerialIn = null;
        byte[] RXBuffer = new byte[SMSPort.ReadBufferSize + 1];
        string SMSMessage = null;
        int Strpos = 0;
        string TmpStr = null;
        while (SMSPort.IsOpen == true)
        {
            if ((SMSPort.BytesToRead != 0) & (SMSPort.IsOpen == true))
            {
                while (SMSPort.BytesToRead != 0)
                {
                    SMSPort.Read(RXBuffer, 0, SMSPort.ReadBufferSize);
                    SerialIn = 
                        SerialIn + System.Text.Encoding.ASCII.GetString(
                        RXBuffer);
                            if (SerialIn.Contains(">") == true)
                    {
                        _ContSMS = true;
                    }
                    if (SerialIn.Contains("+CMGS:") == true)
                    {
                        _Continue = true;
                        if (Sending != null)
                            Sending(true);
                        _Wait = false;
                        SerialIn = string.Empty;
                        RXBuffer = new byte[SMSPort.ReadBufferSize + 1];
                    }
                }
                if (DataReceived != null)
                    DataReceived(SerialIn);
                SerialIn = string.Empty;
                RXBuffer = new byte[SMSPort.ReadBufferSize + 1];
            }
        }
    }    

    public bool SendSMS(string CellNumber, string SMSMessage)
    {
        string MyMessage = null;
        if (SMSMessage.Length <= 160)
        {
            MyMessage = SMSMessage;
        }
        else
        {
            MyMessage = SMSMessage.Substring(0, 160);
        }
        if (IsOpen == true)
        {
            SMSPort.WriteLine("AT+CMGS=" + CellNumber + "r");
            _ContSMS = false;
                SMSPort.WriteLine(
                    MyMessage + System.Environment.NewLine + (char)(26));
              _Continue = false;
            if (Sending != null)
                Sending(false);
        }
        return false;
    }    

    public void Open()
    {
        if (IsOpen == false)
        {
            SMSPort.Open();
                ReadThread.Start();
        }
    }    

    public void Close()
    {
        if (IsOpen == true)
        {
            SMSPort.Close();
        }
    }    

}
Then use the code as below:
Collapse
SMSEngine = new SMSCOMMS("COM1");
SMSEngine.Open();
SMSEngine.SendSMS("919888888888","THIS IS YOUR MESSAGE");
SMSEngine.Close();

send sms