Building a Lync bot using C#

Standard

Long back I wrote an article on creating a language translation bot using Skype and C#, since Microsoft stopped Skype COM API, and I am using lync more than Skype, I thought of writing the same implementation using lync.

The implementation is pretty same, you have to get the instance of the lync instance first, attach event handlers, translate and return the text back. To make this post simple, I am not including the translation logic, I am reversing the text and sending back to the sender.

You need to install the Lync SDK to start using the lync APIs, which you can download from here. You need to add reference of Microsoft.Lync.Model and Microsoft.Lync.Utilities DLLs.

Lync References

Lync References

And here is the code snippet.

private LyncClient _lyncClient;
private ConversationManager _conversationManager;

_lyncClient = LyncClient.GetClient();
_conversationManager = _lyncClient.ConversationManager;
_conversationManager.ConversationAdded += ConversationAdded;

private void ConversationAdded(object sender, ConversationManagerEventArgs e)
{
    var conversation = e.Conversation;
    conversation.ParticipantAdded += ParticipantAdded;
}

private void ParticipantAdded(object sender, ParticipantCollectionChangedEventArgs e)
{
    var participant = e.Participant;
    if (participant.IsSelf)
    {
        return;
    }

    var instantMessageModality = 
        e.Participant.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;
    instantMessageModality.InstantMessageReceived += InstantMessageReceived;
}

private void InstantMessageReceived(object sender, MessageSentEventArgs e)
{
    var text = e.Text.Replace(Environment.NewLine, string.Empty);
    (sender as InstantMessageModality).BeginSendMessage(Reverse(text), null, null);
}

Reverse method reverses the text and send back to the user using BeginSendMessage method. You can extend the bot MEF and custom plugins.

Happy Programming :)

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. :)

HTML5 Application Cache and Azure websites

Standard

Today I faced any issue with HTML5 Application Cache (I will post about HTML5 Application Cache later), I deployed an HTML5 application to azure website, but I was getting error like this

Application Cache Error event: Manifest fetch failed (404)

Application Cache Error event: Manifest fetch failed (404)

Application Cache Error event: Manifest fetch failed (404)

This issue was due to the MIME type mapping was missing. Since it is website, developers don’t have direct control over the IIS. Here is the fix, using Web.Config file.

<system.webServer>
  <staticContent>
    <remove fileExtension=".appcache" />
    <mimeMap fileExtension=".appcache" 
              mimeType="text/cache-manifest" />
  </staticContent>
</system.webServer>

Sometimes we will get this issue while running in IIS Express as well.

Happy Programming :)

How to identify static class using reflection

Standard

Today someone asked me, how to find static class from list of types. I was against the implementation he was doing, but still I couldn’t find how to find static class. Later I did some research and I found like you need to look for IsAbstract and IsSealed properties of the type.

Here is source code, which identify the static class from the list of available types in the assembly.

class Program
{
    static void Main(string[] args)
    {
        var types = Assembly.GetExecutingAssembly().GetTypes();
        types.Where(x => x.IsAbstract && x.IsSealed).ToList()
            .ForEach(Console.WriteLine);
    }
}

static class StaticClass { }

sealed class SealedClass { }

interface Interface { }

class NormalClass { }

abstract class AbstractClass { }

If you run the above code, it will print the StaticClass name.

Happy Programming :)