Tuesday 29 September 2015

VS 2015 : Designer.cs not showing up for the .resx file

By default , the designer file for the .resx files are not turned up in the solution. In order to show them we need to right click on the resx file and "Run Custom Tool".






Then you can see the designer related files as follows.



Saturday 26 September 2015

MVC5 jquery client side unique validation - onblur

I have described how to do client side validation using data annotations using remote attribute in one of my previous posts. This post is about how to use pure jquery with Ajax to do unique validation in a MVC5 web app.

1. First of all, we need to implement a public method in our controller.


 
[HttpPost]
public JsonResult IsPassportExists(string passportNumber)
{
     return Json(db.Clients.Any(x => x.PassportNumber == passportNumber), JsonRequestBehavior.AllowGet);
}

This would do the server side query and do the validation. Note that we are going to return a JsonResult in order to support client side Ajax call.

2. Client side function to perform the server call.
 
 function CheckValue(ctrl) {
            $.ajax({
                url: '@Url.Action("IsPassportExists", "Client")',
                type: 'POST',
                dataType: 'json',
                cache: false,
                data: { 'passportNumber': ctrl.value },
                success: function (value) {
                    if (value) {
                        ctrl.style.backgroundColor = "red";
                        alert('Passport Number already exist!');
                        
                    } else {
                        ctrl.style.backgroundColor = "white";
                    }
                },
                error: function () {
                    alert('Error occured');
                }
            });
        }

We are passing the client controller (ie: textbox) to the function and do the background color change according to the validation result.

3. Finally , following is the way we can call to this function in the textbox
 
 @Html.TextBoxFor(m => m.PassportNumber, new {@class = "form-control", data_bind = "value: PassportNumber", maxlength = "20", onblur = "CheckValue(this)"})

Friday 25 September 2015

Add a non Database field to the Model using Data Annotations

Sometime we may need to add a new column to our model but do not want to reflect that in the database. Especially in the code first development , we do not want to migrate that particular field to the database.

One way of achieving this is using a ViewModel. For some reason, if we really want to add this our Model class we can easily use the NotMapped Data annotation attribute as follows. Most of the time this could be a calculated column.

 
[NotMapped]
public decimal AccountBalance{get;set;}


Thursday 24 September 2015

MVC5 Client side validation using REMOTE Data annotation

More often we need to do client side validation before we submit the view to the controller. Most of the time , we are using jquery or ajax calls to achieve this objective.

But there is much easier way of achieving this using the remote data annotation in our model class. What it is performing is, invoke an async call to the controller to perform required task.

Following are code samples for this.

1. We need to add following method to the controller which returns JsonResult
 
[HttpPost]
public JsonResult IsPassportExists(string PassportNumber)
{
    return Json(db.Clients.Any(x => x.PassportNumber == PassportNumber), JsonRequestBehavior.AllowGet);
}

2. Following is the corresponding model attribute. Note we are referring the controller's method in this.
 
 [Required]
 [Display(Name = "Passport Number")]
 [StringLength(20)]
 [Remote("IsPassportExists", "Client", HttpMethod = "POST", ErrorMessage = "Passport Number already registered")]
 public string PassportNumber { get; set; }

3. In the View, you just need to refer following js libraries.
 
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Tuesday 22 September 2015

Web API 2 : Convert default xml media type to json

Even if we specify a Web API call to return a json type, when we navigate tothe api call usign a browser, it returns an xml formatted data.

 
             var expenseGroups = _repository.GetExpenseGroups();

             return Ok(expenseGroups.ToList()
                    .Select(eg => _expenseGroupFactory.CreateExpenseGroup(eg)));

But we would get a result something as follows in the browser.

This happens because the browser request for the text/html type in its request header
Example browser request header
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
We can program our API in way that , if browser request for a text format the request to json.
Following is the formatting code we need to get done in the WebApiConfig
 
             var expenseGroups = _repository.GetExpenseGroups();

             return Ok(expenseGroups.ToList()
                    .Select(eg =gt; _expenseGroupFactory.CreateExpenseGroup(eg)));

We can get the following result.

Monday 21 September 2015

[Solved] : There is already an open DataReader associated with this Command which must be closed first.

The exception "There is already an open DataReader associated with this Command which must be closed first." occurs when you try to perform another read while there is an ongoing read. Most commonly when you are iterating through one result set and within the loop the you are trying to fetch another data set.

Following is a typical example for this.
 
             var res = GetPayrollforReport(month, year);            

            foreach (var payRoll in res)
            {
                PayrollViewModel pay = new PayrollViewModel();
                pay.PayRollId = payRoll.PayRollId;
                var emp = db.Employees.FirstOrDefault(e => e.EmployeeId == payRoll.EmployeeId);
            }

In here, its trying to fetch employee details inside the payroll loop. So this is leading to above exception. There are two solutions for this.
1. Caste the first fetch in to a proper list type.
 
             var res = GetPayrollforReport(month, year).ToList<PayRoll>();            

            foreach (var payRoll in res)
            {
                PayrollViewModel pay = new PayrollViewModel();
                pay.PayRollId = payRoll.PayRollId;
                var emp = db.Employees.FirstOrDefault(e => e.EmployeeId == payRoll.EmployeeId);
            }

2. Allowing MARS in your connection string. This can be easily fix by introducing the MultipleActiveResultSets=true param into your connection string.

Monday 14 September 2015

Customizing the google map and populating locations from Database using WEB API2 .Net

Following is a brief tutorial of how you can customize the default google map ( I have used the JS API) and populating geo locations from a Database.

There are many good tutorials where you can dynamically plot geo locations using a database table. Most of them are PHP based. For ASP and .Net fans, following is a very naive way of accomplish the same result.

We are going to use a WEB API2 Rest service to fetch data in to our map front end. You can see how easily we can built a Code first WEB API using SQL server in this link.

Following is my model class. It is very simple and contains only geo location data.

 
public class MapIcons
    {
        [Key]
        public Guid Id { get; set; }

        public double Latitude { get; set; }

        public double Longitude { get; set; }

        [StringLength(50)]
        public string Name { get; set; }

        [StringLength(50)]
        public string Caption { get; set; }

        public int CapSize { get; set; }

        [StringLength(50)]
        public string Icon { get; set; }
    
    }

Following is the context class
 
 public partial class MapDataContext : DbContext
    {
        public MapDataContext()
            : base("name=DBContext")
        {
        }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }

        public DbSet<MapXyIcons> MapIcons { get; set; }
    }

Updated configuration class to populate some initial data.
 
internal sealed class Configuration : DbMigrationsConfiguration
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(GoogleMapService.Models.MapDataContext context)
        {


            context.MapXyIcons.AddOrUpdate(m => m.Id,
                new Models.MapXyIcons
                {
                    Id = Guid.NewGuid(),
                    Name = "TestXy1",
                    Caption = "Test Xy 1 ",
                    Icon = "light",
                    Latitude = 6.9025191,
                    Longitude = 79.8596352,
                    CapSize = 10
                },
                new Models.MapXyIcons
                {
                    Id = Guid.NewGuid(),
                    Name = "TestXy2",
                    Caption = "Test Xy 2 ",
                    Icon = "poly",
                    Latitude = 6.9023642,
                    Longitude = 79.861076,
                    CapSize = 10
                },
                new Models.MapXyIcons
                {
                    Id = Guid.NewGuid(),
                    Name = "TestXy2",
                    Caption = "Test Xy 2 ",
                    Icon = "poly",
                    Latitude = 6.9019559,
                    Longitude = 79.8612179,
                    CapSize = 10
                },
                new Models.MapXyIcons
                {
                    Id = Guid.NewGuid(),
                    Name = "TestXy3",
                    Caption = "Test Xy 3 ",
                    Icon = "light",
                    Latitude = 6.9019559,
                    Longitude = 79.8612179,
                    CapSize = 10
                },
                new Models.MapXyIcons
                {
                    Id = Guid.NewGuid(),
                    Name = "TestXy4",
                    Caption = "Test Xy 4 ",
                    Icon = "Light",
                    Latitude = 6.9021217,
                    Longitude = 79.8617325,
                    CapSize = 10
                }
                );

        }
    }

The Web API controller goes as follows.
 
 [RoutePrefix("Icons")]
    public class MapIconController : ApiController
    {
        private MapDataContext db = new MapDataContext();

        // GET api/MapIcon
        [HttpGet, Route("GetAll")]
        [HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
        public IHttpActionResult GetMapIcons()
        {
            return Ok(db.MapIcons.ToListAsync());
        }

        // GET api/MapIcon/5
        [ResponseType(typeof(MapIcons))]
        public async Task<IHttpActionResult> GetMapIcons(Guid id)
        {
            MapIcons mapicons = await db.MapIcons.FindAsync(id);
            if (mapxyicons == null)
            {
                return NotFound();
            }

            return Ok(mapicons);
        }
     }

Note that I'm returning a Json response to the client with Map data. This would make the client implementation easy and independent.
[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")] : This attribute make your life easier when testing the applications in the development environment itself. Otherwise you need to install a CORS plugin in your browser and allow cross origin.
The server side code is done now and we need to concentrate on the client side implementation. I did a customization to the google default map and You can easily learn this using google tutorial itself.
You can access the service api as in following jquery code.
 

            function ajax(url) {
                return new Promise(function (resolve, reject) {
                    var xhr = new XMLHttpRequest();
                    xhr.onload = function () {
                        resolve(this.responseText);
                    };
                    xhr.onerror = reject;
                    xhr.open('GET', url);
                    xhr.send();
                });
            }

            ajax("http://localhost:1210/Icons/GetAll").then(function (result) {
                mapJson = result;

                var mapObj = JSON.parse(mapJson);
            };

Note that I have used promises to implement this in order to support Async server side calls.
Finally, we need to iterate thorough the data set and plot icons based on their locations.
 
   var features = [];

                for (var i = 0; i < mapObj.Result.length; i++) {

                    var pos = new google.maps.LatLng(mapObj.Result[i].Latitude, mapObj.Result[i].Longitude);

                    var feature = {
                        position: pos,
                        type: mapObj.Result[i].Icon
                    };

                    features.push(feature);

                    var mapLabel = new MapLabel({
                        text: mapObj.Result[i].Caption,
                        position: pos,
                        map: map,
                        minZoom: 10,
                        maxZoom: 25,
                        strokeColor: '#ffff7f',
                        strokeWeight: 20,
                        fontColor: '#ff0000',
                        fontSize: mapObj.Result[i].CapSize,
                        align: 'center'
                    });
                }

                for (var i = 0, feature; feature = features[i]; i++) {
                    addMarker(feature);
                }

                function addMarker(feature) {
                    var marker = new google.maps.Marker({
                        position: feature.position,
                        icon: icons[feature.type].icon,
                        map: map
                    });
                }


Additionally , I have added a small legend based on the icon types.
 
 var legend = document.getElementById('legend');

                for (var key in icons) {
                    var type = icons[key];
                    var name = type.name;
                    var icon = type.icon;
                    var div = document.createElement('div');
                    div.innerHTML = '<img src="' + icon + '"> ' + name;
                    legend.appendChild(div);
                }


Following is a screen of the output of this application.

You can download the full source code from this location.

Saturday 12 September 2015

Correct HTTP status codes for web APIs

Most of the time, when we are designing a web API, we do not consider much what status codes to return. Some codes are returning to the client  by default by the API but it is essential that we control what codes that get returned to the client.

This is essential when we are designing a generic  APIs where we do not know who would connect to the APIs to get a service. Following are some common HTTP status codes that we should return for common HTTP methods.

HTTP Verb
Applicable Status codes
GET
200-Ok, 404- Not Found,  400- Bad Request , 500- Internal Server error
POST
201- Created , 400- Bad Request , 500- Internal Server error
DELETE
204- No Content, 404- Not Found,  400- Bad Request , 500- Internal Server error
PUT
200-Ok, 404- Not Found,  400- Bad Request , 500- Internal Server error
PATCH
200-Ok, 404- Not Found,  400- Bad Request , 500- Internal Server error
General
401- Unauthorized, 403 Forbidden, 405 Method not allowed





Friday 11 September 2015

Recieve Encrypted SMS using Android

We have discussed how we can send encrypted SMS using Android in this post. Now it is time to analyze how we can decrypt those encrypted SMS using another application. Targeted functionality is when the SMS received , it should spawn the decryption application and show the clear text message to user.

Im using an Android BroadcastReceiver class in order to keep an alert on whats going on the phone. As you know it is running as a background thread in the phone. If there is an incoming SMS it tries decrypt it. First of all lets examine whats in the all important Manifest file.
   

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.priya.recievesms_mis023" >
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".PriyalBroacast">
        <intent-filter android:priority="999" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
    </application>

</manifest>



Permissions are granted to read and receive SMS.
<uses-permission android:name="android.permission.RECEIVE_SMS"/> <uses-permission android:name="android.permission.READ_SMS"/>
Note that I set the receiver as PriyalBroacast because this would be my Broacast listener class which inherited by BroadcastReceiver. I set up relatively higher value to priority in order to execute this operation before many other operations. action android:name="android.provider.Telephony.SMS_RECEIVED" This line would invoke the broadcast listener in the event of a SMS received.
The Broacast Class
   
public class PriyalBroacast extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        try {

            Bundle smsBundle = intent.getExtras();
            SmsMessage[] msg = null;
            String sms_str = "";
            String mySms = "";
            if (smsBundle != null) {
                Object[] pdus = (Object[]) smsBundle.get("pdus");
                msg = new SmsMessage[pdus.length];

                if(msg.length>0)
                {
                    msg[0] = SmsMessage.createFromPdu((byte[]) pdus[0]);
                    mySms = msg[0].getMessageBody().toString();
                }

                AESEncrypt aes = new AESEncrypt(256);
                mySms = mySms.substring(0, mySms.length() - 1);
                byte[] b= aes.decrypt(Base64.decode(mySms, Base64.DEFAULT));
                String decryptedSMS = new String(b);


                Intent smsShow = new Intent(context, MainActivity.class);
                smsShow.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                smsShow.putExtra("mySms", decryptedSMS);
                context.startActivity(smsShow);


            }
        }
        catch(Exception ex)
        {
           
        }

    }
}

This class would extract the body of the SMS and decrypt it using AES. After a successful decryption, its just call to the MainActivity to show the decrypted message.
Following is the Implementation of the AES Cryptography class.
Note that Im using a static AES Key which is hard coded here. This is not a very good security practice. Instead, We need to store the key securely in the device if we are going to use the Symmetric encryption. I would discuss this in a separate post and this is enough for the time being and for learning purposes.
   
public class PriyalBroacast extends BroadcastReceiver
{
public class AESEncrypt {
    private static Key key=null;
    private static Cipher cipher = null;

    private static String algorithm = "AES";
    private static byte[] keyValue=new byte[] {'0','2','3','4','5','6','7','8','9','1','2','3','4','5','6','7'};//

    public AESEncrypt(int size) throws NoSuchAlgorithmException, NoSuchPaddingException {
        //Generate a key
        try {
            if (key == null) {
                KeyGenerator generator = KeyGenerator.getInstance("AES");
                generator.init(size);
                key = generateKey();//generator.generateKey();
            }
            if (cipher == null) cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        }
        catch(Exception e)
        {}
    }

    public byte[] encrypt(String msg) throws InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException{
        // encryption pass
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(msg.getBytes());
    }

    public byte[] decrypt(byte[] cipherText) throws InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException{
        // decryption pass
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    private static Key generateKey() throws Exception
    {
        Key key = new SecretKeySpec(keyValue, algorithm);
        return key;
    }
}

Finally the Main Activity class and the simple UI.
   
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent sms_intent=getIntent();
        Bundle b=sms_intent.getExtras();
        TextView tv=(TextView)findViewById(R.id.txtview);
        if(b!=null){

            tv.setText(b.getString("mySms"));
        }

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Following UI would show the decrypted SMS
   
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.example.smsreceiver.MainActivity" >

    <TextView
        android:id="@+id/txtview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="5"
        android:singleLine="false"
        android:textSize="20sp"
        />
</RelativeLayout>


If we examine the SMS Inbox in the emulator. We can clearly see the encrypted messages.

You can Download the source code from this location. 

Send Encrypted SMS using Android

You may need to send a secure SMS to your friend over the GSM network. Following is a Tutorial of how you can build Secure SMS messenger using Android.

You can find the How we can receive these secure SMS from this link.

First and foremost, we need to configure the Manifest file with correct permissions.
   
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.priya.sendsms_mis023" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="23"/>
    <uses-permission
        android:name="android.permission.SEND_SMS" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


The most important part is acquire correct permission using
android:name="android.permission.SEND_SMS"

Next, we will take a look at the UI(View) part of the application. It is very simple and all you need to do is add couple of Edit text views and a button to send the encrypted SMS.
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="Enter Message" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView android:text="Enter Phone Number" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:id="@+id/textView2" />


    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editTextNumber"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/button"
        android:layout_below="@+id/editTextNumber"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


</RelativeLayout>




Next , we will take a look at how we can do the Encryption part. So I came up with a separate class for this using AES.
public class AESEncrypt {
    private static Key key=null;
    private static Cipher cipher = null;

    private static String algorithm = "AES";
    private static byte[] keyValue=new byte[] {'0','2','3','4','5','6','7','8','9','1','2','3','4','5','6','7'};//

    public AESEncrypt(int size) throws NoSuchAlgorithmException, NoSuchPaddingException {
        //Generate a key
        try {
            if (key == null) {

                key = generateKey();
            }
            if (cipher == null) cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        }
        catch(Exception e)
        {}
    }

    public byte[] encrypt(String msg) throws InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException{
        // encryption pass
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(msg.getBytes());
    }

    public byte[] decrypt(byte[] cipherText) throws InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException{
        // decryption pass
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    private static Key generateKey() throws Exception
    {
        Key key = new SecretKeySpec(keyValue, algorithm);
        return key;
    }
}


Note that Im using a static AES Key which is hard coded here. This is not a very good security practice. Instead, We need to store the key securely in the device if we are going to use the Symmetric encryption. I would discuss this in a separate post and this is enough for the time being and for learning purposes.
encrypt and decrypt methods in this class itself in order perform all cryptography operations.
The generateKey() function would generate the reuired key based on the initial keyValue and the encryption algorithm which AES in this instance.

Finally, lets examine the main Activity class.
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button = (Button) findViewById(R.id.button);
        final EditText tvMessage=(EditText)findViewById(R.id.editText);
        final EditText tvNumber=(EditText)findViewById(R.id.editTextNumber);
        final String SENT = "SMS_SENT";
        final String DELIVERED = "SMS_DELIVERED";

        final PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

        final PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);


        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));


        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                try {
                    String msg = tvMessage.getText().toString();
                    String phoneNumber = tvNumber.getText().toString();
                    AESEncrypt aes = new AESEncrypt(256);
                    String base64 = Base64.encodeToString(aes.encrypt(msg), Base64.DEFAULT);
                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(phoneNumber, null, base64, sentPI, deliveredPI);

                }
                catch(Exception ex)
                {}
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


I used the smsManager class to send the Message across the network. This is the simplest SMS sender in Android. There are two BroadcastReceivers where it can track what is actually happens to the SMS ending process once user clicks the send button.

Following is the Final Screenshot of the application.



Note : If you are sending the SMS to another emulator running on your desktop, you need to specify the port number of that emulator as the phone number. To get a specific port number for the emulator use Android Device Monitor tool.

You can Download the source code from this location.