Android – How to intercept SMS messages and prevent them from appearing in the Inbox

Standard

Android allows app developers to intercept SMS, here is the code snippet, which will help you to get the sms details and if you require you can stop them appearing in the inbox.

First you need to set the permission for the app to receive and process SMS. You can do this by modifing the AndroidManifest.xml file.

AndroidManifest.xml file

AndroidManifest.xml file

Source :

<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />

Now you need to write a BroadcastReceiver, which helps to process the SMS message.

[BroadcastReceiver (Enabled = true, Label = "SMS Receiver")]
public class SMSBroadcastReceiver : BroadcastReceiver
{
	public static readonly string IntentAction = "android.provider.Telephony.SMS_RECEIVED";

	public override void OnReceive (Context context, Intent intent)
	{
		try {
			if (intent.Action != IntentAction) {
				return;
			}

			var bundle = intent.Extras;

			if (bundle != null) {
				var pdus = (Java.Lang.Object[])bundle.Get ("pdus");
				var messages = new SmsMessage[pdus.Length];
				var stringBuilder = new StringBuilder ();
				for (int i = 0; i < messages.Length; i++) {
					messages [i] = SmsMessage.CreateFromPdu ((byte[])pdus [i]);
					stringBuilder.AppendFormat ("Message from  {0} here is the Content : {1}", 
						messages [i].OriginatingAddress.ToString (), messages [i].MessageBody.ToString ());
				}
				Toast.MakeText (context, stringBuilder.ToString (), ToastLength.Long).Show ();
				//Uncomment next line if you want to skip the inbox.
				//InvokeAbortBroadcast ();
			}
		} catch (Exception ex) {
			Toast.MakeText (context, ex.Message, ToastLength.Long).Show ();
		}
	}
}

And finally you need to register the BroadcastReceiver, you can do this like

RegisterReceiver (new SMSBroadcastReceiver(), new IntentFilter ("android.provider.Telephony.SMS_RECEIVED"));

You can use this technique to avoid SPAM messages by looking into the number or message content.

Note: You can verify this implementation using android emulator. You can find more details here – SMS Emulation

Happy Programming. :)

Creating user friendly strings for C# enums

Standard

Recently one of my colleague asked me question, he want to create a enum with string values. But C# doesn’t support string based enums, so here is the code snippet which will help you to associate string values to enums. This code is not using any custom attribute, instead it is using DescriptionAttribute class. Here is the enum, with the associated string values.

enum OrderStatus
{
    [Description("New Order")]
    NewOrder = 1,
    [Description("Order is processing")]
    Processing = 2,
    [Description("Order is shipped")]
    Shipped = 3
}

And here is the extension method, which returns the string value associated to the enum

public static class Extensions
{
    public static string Description(this Enum @enum)
    {
        var description = string.Empty;
        var fields = @enum.GetType().GetFields();
        foreach (var field in fields)
        {
            var descriptionAttribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (descriptionAttribute != null && 
field.Name.Equals(@enum.ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                description = descriptionAttribute.Description;
                break;
            }
        }

        return description;
    }
}

You can get the description from enum like this.

var orderStatus = OrderStatus.NewOrder;
Console.WriteLine(orderStatus.Description());

Happy Programming :)

Update : Based on the comment from NDVictory, source code modified to return the exact value, earlier it was always returning the first value. Thank you NDVictory

MVC5 Ajax form is not updating DIV but replacing the whole page instead

Standard

While working on MVC5 application, I faced this issue, I was using Ajax.BeginForm() and from controller, I was returning content result. But instead of updating the DIV, the content was opened in new Tab. Initially I thought it was due to some javascript error, but it was not working with Ajax.ActionLink also. Later I found it was due to missing “Microsoft.jQuery.Unobtrusive.Ajax” package. You can install this via NuGet.

NuGet package - Microsoft.jQuery.Unobtrusive.Ajax

NuGet package – Microsoft.jQuery.Unobtrusive.Ajax

And include it in the BundleConfig.cs.

bundles.Add(new ScriptBundle("~/bundles/jqueryunobtrusive").Include(
            "~/Scripts/jquery.unobtrusive*"));

And include the jqueryunobtrusive in _layout.cshtml file.

@Scripts.Render("~/bundles/jqueryunobtrusive")

It will resolve this issue.

Happy Programming :)

Load ASP.NET MVC partial views on link click

Standard

Some one asked me how we can load partial views on link click. Here is the snippet for the same.

Long version – Using JQuery

<script type="text/javascript">
$("#loadPartialView").click(function () {
    $.get('@Url.Action("LoadPartialView","Home")', {}, function (response) {
        $("#Display").html(response);
    });
});
</script>

And here is the small version using Ajax.ActionLink

@Ajax.ActionLink("Load Partial View", "LoadPartialView", "Home",
    new AjaxOptions() { UpdateTargetId = "Display" })

In the page, you need to add a DIV with Id attribute which got a value “Display”, partial view will be loaded to this DIV.

And here is the controller action

public ActionResult LoadPartialView()
{
    return PartialView("_PartialView");
}

Happy Programming :)