Monthly Archives: May 2015

Create a Barcode Scanner App in just 3 Minutes with Xamarin.Forms

So few weeks back my boss tasked me to implement a barcode scanning feature in one of our enterprise mobile apps which we were building using Xamarin Cross Platform. I got freaked out, as I have never implemented anything related to barcode scanning, not even in my 3 years of Windows Phone dev experience 😛 ! I was worrying whether it would get much messier when it comes to Cross Platform development. 😦

But luckily I was able to implement the task under 15 mins, thanks to the awesomeness of Xamarin. I came across this epic library called ACR Barcodes Plugin for Xamarin Forms, which allowed me to easily implement the code bar code scanning and reading feature.

So with that experience, now I’m gonna show you how you could build a Barcode Scanner App in just 3 Minutes.. 😀 Prepare to be mind blown ! 😉

First create a Xamarin.Forms project (PCL project) solution in Visual Studio and add the  ACR Barcodes Plugin using nuget package manager.

Simple implementing in your PCL…

Create a new class in your PCL project called Page_BarcodeScanner. And replace that Class code with the following code.

class Page_BarcodeScanner : ContentPage
{
	public Page_BarcodeScanner() 
	{
		Button btnScan = new Button
		{
			Text = "Scan Barcode",
			HorizontalOptions = LayoutOptions.FillAndExpand,
		};

		btnScan.Clicked += async (a, b)   => 
		{
			Launch_BarcodeSearch();
		};

		this.Content = new StackLayout
		{
			Children = 
			{
				btnScan,
			},
		};
	}

	#region Scan Barcode
	
	async void Launch_BarcodeSearch()
	{
		var result = await BarCodes.Instance.Read();
		if (!result.Success)
		{
			await this.DisplayAlert("Sorry ! Scan Failed ! ", "Sorry ! Failed to read the Barcode !", "OK");                
		}
		else
		{
			var msg = String.Format("Barcode Format : {0} \n Barcode Value : {1}", result.Format, result.Code);
			await this.DisplayAlert("Scan Successful !", msg, "OK");
		}
	}

	#endregion
}

 

Now resolve the necessary imports… 😉 And you just created the Bar code scanner code. So let’s set this page to be executed in the App.cs file. Open up the App.cs code file in the PCL project and replace its App() method with the following.

public App()
{
	// The root page of your application
	MainPage = new Page_BarcodeScanner();
}

 

There you go, but wait… Just a little bit more configuring to be done. 😉

Now we have to set the camera access permission and initiate the library on Android/ iOS and WinPhone projects. Nothing to worry its pretty simple.

Setting up on Android..

In your Android project, replace the OnCreate method in the MainActivity.cs code file with the following. This init()  call will initialize the library for the application.

protected override void OnCreate(Bundle bundle)
{
	base.OnCreate(bundle);

	global::Xamarin.Forms.Forms.Init(this, bundle);
	BarCodes.Init(() => (Activity)Forms.Context);
	LoadApplication(new App());
}

 

Now we need to set the permission for the app to access the Camera on the device, so double click on Properies -> select tab  Android Manifest -> Tick on CAMERA permission.

androidconfig

That’s it ! Now you can even set your Android project as the default project and run the application successfully.. 😉  or else you could go ahead with the rest of the configuration on iOS and WinPhone.. 😀

Setting up on iOS…

In you iOS app, replace the FinishedLaunching() method in the AppDelegate.cs code file with the following code, in order to initialize the library for the usage of the application.

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	global::Xamarin.Forms.Forms.Init();
	BarCodes.Init();
	LoadApplication(new App());

	return base.FinishedLaunching(app, options);
}

 

That’s it, oh and not to worry you don’t have to set the permission on the iOS project. 😉

Setting up on Windows Phone…

Finally on Windows Phone Project (WinPhone) replace the MainPage() constructor in the MainPage.xaml.cs file with the following code,

public MainPage()
{
	InitializeComponent();
	SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;

	global::Xamarin.Forms.Forms.Init();
	BarCodes.Init();
	LoadApplication(new EasyBarcodeReaderApp.App());
}

 

Now let’s set the camera permission on Windows Phone as follows…

Expand Properties -> Double click on WMAppManifest.xml -> Go to Capabilities tab -> Tick on ID_CAP_ISV_CAMERA permission

winphonemanifest

Finally thats it ! 😀 Now you can build the whole project and run the app in any selected platform as you wish… 😀

TADAAAAAAAA ! 😀

Below are some screenshots I took after I deployed in my Windows Phone device. 🙂 Now its all up to you to make any necessary improvements or implement this in any of your awesome apps as you wish. 😉

wp_ss_20150520_0002 wp_ss_20150520_0003 wp_ss_20150520_0005

Keep up the awesomeness ! ^_^

Easily implement Data Storage Service in Xamarin.Forms using PCL Storage

It was kind of unfortunate that there is no built in Data Storage mechanism in Xamarin Forms. I was a hardcore Windows Phone developer before I moved into Xamarin Forms, whereas this was such an irritating factor for me and specially, few months back there weren’t any proper library or tutorials available for caching data in the app. The only suited option was to implement a dependency service, which I was quite bored of.

Few months back I needed to cache some data in an app, whereas this string array list will be downloaded from a web service, then saved it in the application cache and then reloaded whenever the app is opened by the user. I was developing a cross platform app based on Xamarin.Forms along with an attached PCL project.
After an extensive search I came across PCL Storage library, it was still in beta level at that time, but me being unable to find any other better option, decided to go ahead with it as it was very easy to implement.

Download PCL Storage on nuget – http://www.nuget.org/packages/pclstorage

Read about PCL on Xamarin Components Library, Capture

It was really easy and simple to implement that I used it for almost all the data caching tasks. Today PCL Storage has evolved very well along with some new features too. So I thought of sharing the implementation I used with PCL Storage back then with you all, in case if any of you came across my situation. You can easily, straightaway use the code I’m posting here in your Xamarin.Forms PCL projects and call the methods to get your job done without a hassle.

This includes Saving, Reading and Deleting data from your application cache.

public class DataStorageService
{
/// <summary>
/// Saving Values to the Storage...
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Key"></param>
/// <param name="ValueToSave"></param>
/// <returns></returns>
public async Task Save_Value<T>(String Key, T ValueToSave)
{
	XDocument doc = new XDocument();
	using (var writer = doc.CreateWriter())
	{
		var serializer = new XmlSerializer(typeof(T));
		serializer.Serialize(writer, ValueToSave);
	}

	IFolder rootFolder = FileSystem.Current.LocalStorage;
	IFolder folder = await rootFolder.CreateFolderAsync("Cache",
		CreationCollisionOption.OpenIfExists);
	IFile file = await folder.CreateFileAsync(Key + ".txt",
		CreationCollisionOption.ReplaceExisting);

	await file.WriteAllTextAsync(doc.ToString());
}

/// <summary>
/// Reading Values from the Storage...
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Key"></param>
/// <returns></returns>
public async Task<T> Get_Value<T>(String Key)
{
	IFolder rootFolder = FileSystem.Current.LocalStorage;
	IFolder folder = await rootFolder.CreateFolderAsync("Cache",
		CreationCollisionOption.OpenIfExists);

	ExistenceCheckResult isFileExisting = await folder.CheckExistsAsync(Key + ".txt");

	if (!isFileExisting.ToString().Equals("NotFound"))
	{
		try
		{
			IFile file = await folder.CreateFileAsync(Key + ".txt",
			CreationCollisionOption.OpenIfExists);

			String languageString = await file.ReadAllTextAsync();

			XmlSerializer oXmlSerializer = new XmlSerializer(typeof(T));
			return (T)oXmlSerializer.Deserialize(new StringReader(languageString));
		}
		catch (Exception ex)
		{
			return default(T);
		}
	}

	return default(T);
}

/// <summary>
/// Delete any value from the Storage...
/// </summary>
/// <param name="Key"></param>
public async void Delete_Value(String Key)
{
	IFolder rootFolder = FileSystem.Current.LocalStorage;
	IFolder folder = await rootFolder.CreateFolderAsync("Cache",
		CreationCollisionOption.OpenIfExists);

	ExistenceCheckResult isFileExisting = await folder.CheckExistsAsync(Key + ".txt");

	if (!isFileExisting.ToString().Equals("NotFound"))
	{
		try
		{
			IFile file = await folder.CreateFileAsync(Key + ".txt",
			CreationCollisionOption.OpenIfExists);

			await file.DeleteAsync();
		}
		catch (Exception ex)
		{

		}
	}
}
}

 

This implementation has asynchronous method calls, therefore you can call these methods to get your job done and you won’t have anything to worry about UI lagging.

Here is how you could call this awesomely simple DataStorageService,

DataStorageService storageService = new DataStorageService();


Dictionary<string, object> TESTDATALIST = new Dictionary<string, object>();
TESTDATALIST.Add("KEY1", 123);
TESTDATALIST.Add("KEY2", "Hello");

await storageService.Save_Value<List<String>>("TESTKEY", TESTDATALIST);

MyCustomClass _obj = new MyCustomClass();
_obj.String1 = "Hello World";

await storageService.Save_Value<MyCustomClass>("MYOBJECTKEY", _obj);

 

Please be noted, I have created this DataStorageService class only for the purpose of saving primitive and custom data types, not for File types, which you could use for caching data lists, properties, app configurations and so on.

However PCL Storage does have great capability of creating files and folders in your cache and letting you very easily manage them. 😀

Now you may go Rock your apps with Xamarin.Forms ! 😉

How to make POST & GET calls to an ASP.NET RESTful Web Service in Xamarin.Forms

So you are a Xamarin Forms developer ? Well I’m pretty sure this may come in much handy to you… 🙂

Ever wanted to call an ASP.NET RESTful Web Service method from your Xamarin.Forms project, specially when you have a Xamarin.Forms PCL Project ? Well heck yeah I did… 😉 So here is the code I used which I hope it might come in handy do you as well.

Extra Ingredients you may need –

Json.NET Library – For Serializing and Deserializing  data

Microsoft Async Library – For making Async web calls from your PCL project

Make sure you install those libraries (use Nuget Package Manager would be easier) in your Xamarin.Forms Solution (all four of projects – Portable (PCL), Android, iOS and WinPhone). And you will be good to go… 😉

GET Request Method..

Below is the GET request method you could use to call any GET Methods in your ASP.NET RESTful web service.

public async Task<string> MakeGetRequest(string url)
{
	var request = HttpWebRequest.Create(url);

	HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;

	if (response.StatusCode == HttpStatusCode.OK)
	{
		using (StreamReader reader = new StreamReader(response.GetResponseStream()))
		{
			var content = reader.ReadToEnd();
			if (string.IsNullOrWhiteSpace(content))
			{
				return response.StatusCode + "Response contained an empty body...";
			}
			else
			{
				return content;
			}
		}
	}
	else
	{
		return response.StatusCode.ToString();
	}
}

 

Now if you need to deserialize any response you get from the above method call, then you may use the following simple method.. 😉

Deserialize any response from the Web Method call…
public object DeserializeContent<T>(String stringToDeserialize)
{
	DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<T>));
	MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(stringToDeserialize));
	return (List<T>)ser.ReadObject(stream);
}
POST Request Method..

Use this method to make any POST Method calls to your ASP.NET RESTful web service.

public async Task<string> MakePostRequest(string url, string serializedDataString, bool isJson = true)
{
	HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
	if (isJson)
		request.ContentType = "application/json";
	else
		request.ContentType = "application/x-www-form-urlencoded";

	request.Method = "POST";
	var stream = await request.GetRequestStreamAsync();
	using (var writer = new StreamWriter(stream))
	{
		writer.Write(serializedDataString);
		writer.Flush();
		writer.Dispose();
	}

	var response = await request.GetResponseAsync();
	var respStream = response.GetResponseStream();

	using (StreamReader sr = new StreamReader(respStream))
	{
		return sr.ReadToEnd();
	}
}

 

Now if you are in need of Serializing any data that is needed to be passed into the above POST method call, you can use the following simple method which is written using JSON.NET,

Serialize any data to be passed through the POST Web method call..
public String SerializeContent(Object objectToSerialize) 
{
	return JsonConvert.SerializeObject(objectToSerialize);
}

 

TADAAAA ! 😀 There you go, hope it was helpful for any of you awesome Xamarin Developers… ^_^

CHEERS !

So I just bought a new Sony Xperia Z3 Compact from Sri Lanka

After almost 3 years of awesomeness with my Nokia Lumia 820, it had come to a point that I needed to buy a new smartphone. 😀 I really enjoyed my time with Lumia 820, but to be honest since last year I was kind of getting bored of it. And its started having a few hardware issues, such as random network disconnecting, and the camera photos were getting blurred and so on. 😦 So it was high time to switch after almost 3 years… 😀

Love at First Sight… 😉

This time I went for Sony, which had been my favorite Smartphone brand since long time back. I always loved their amazing design, build quality and specially awesome features. 😉 I was never a fan of enormous screen sized smartphones, which in my opinion completely ruins the definition of a mobile phone. So I was looking for a small screen sized phone, and fortunately I found out about Sony Xperia Z3 Compact which is the compact model of Xperia Z3 ! 😀
I literally fell in love with this phone since the first sight of it. So I did some in depth research about this phone before deciding I was gonna buy it.

Phobia of Precautions… 😦

And very disappointingly some users of Xperia Z3 and Z3 Compact models has complained about some ‘Self cracking screen issue‘ which got me very skeptical. I went through so many user forums, Sony forums, XDA forums regarding this issue and there were complains from a lot of people and they were saying that Sony doesn’t cover this in warranty, but however in some News report Sony had agreed that there was some defected stock has been released by accident. But all in all I somehow decided to buy this phone, as there were a lot more users who had reported saying they weren’t having such an issue, which was bit of a relief.

Final decision was taken… 😀

So I straightened up my mind, wishing for the best, I decided to buy this awesome smartphone, Sony Xperia Z3 Compact … 😉

xperia-z3-compact-white-1240x840-f40248bb3132354ba48c58041e244284[1]

 Deciding on a Mobile Phone Shop to buy in Sri Lanka…

So when I stepped outside the house to buy this phone, I decided to buy this from a well known reputed mobile phone shop, rather than going for the lowest price from a small shop, specially because of the above ‘Self cracking screen issue‘ that some Xperia Z3C users were having. By the time I was looking for this phone it cost around Rs. 57,000 – Rs. 59,000 so obviously not much of a difference whether you buy from a small shop or a bigger shop. After visiting a few popular shops around Colombo I found out that none of the shops in Sri Lanka would cover such an issue (Self cracking screen issue) with the warranty, everyone was saying if we are able to prove that it’s a manufacturer fault, only then they would repair it. So I realized there’s no point of worrying about the warranty as every single shop here offers the same crappy warranty, I somehow bought it from Dialcom in Sri Lanka for Rs. 59,900 after a few of my friends’ recommendation. (which actually drained over half of my bank account 😛 )

So here it is, the thing of Beauty and Awesomeness…

WP_20150510_07_10_28_Pro

From the moment of unpacking it, it was a thing of wonder… 😉

WP_20150510_16_14_30_Pro WP_20150509_19_28_02_Pro WP_20150510_16_14_46_Pro

 

WP_20150510_16_15_10_Pro

WP_20150510_16_15_13_Pro

Such a beautiful slim and light design… with uncompromised performance.. 😀

WP_20150510_16_15_55_Pro

WP_20150510_16_15_28_Pro

WP_20150510_16_16_39_Pro WP_20150510_16_17_32_Pro WP_20150510_16_18_11_Pro

From the moment you unlock that screen, is like entering into a whole new world of beauty.. 😀 the screen, is epical indeed with its TRILUMINOS Display and X-Reality Engine, which truly brings an amazing display…

WP_20150510_16_18_18_Pro

What’s in the Box… :O

Now this is what you get with the whole box…

WP_20150510_16_19_08_Pro

WP_20150510_16_20_02_Pro WP_20150510_16_19_24_Pro

I never expected such a high quality headset with the phone.. 🙂 oh well, Thank you Sony ! Except for that it’s just the charger and the USB cable you get in the box.

WP_20150510_16_29_44_Pro

It was a truly surprise with the performance in such a compact device, Quad-core 2.5 GHz Krait 400 Processor and GPU, Adreno 330 seems to be paying up over the expectations…

WP_20150510_16_29_53_Pro WP_20150510_16_30_10_Pro WP_20150510_16_30_20_Pro

In some reviews they had mentioned the sound quality is not that good in this device, but for me with those front dual speakers, it gives an awesome experience for watching movies and videos…

One of the best things about this awesome smartphone is that it fits so perfectly in hand, specially for someone like myself having a comparably small palm.. 😛
It gives a truly premium feel of a mobile device when you hold this in your hand, durable tempered glass panels on front and back sides, along with the round comfortable edges give a real amazing feeling…

WP_20150510_16_30_48_Pro

A defect or not ? 😦

So I was playing around with the phone for a while, holding it with both hands 😛 , well you know the excitement you get when you first use your new mobile phone, whereas you hold it very carefully worrying every second whether your would drop it… 😉

Anyhow after a while I realized that the Sim Card cover flap kept slowly open, every single time I close the flap it kept on popping open very slowly. The most annoying thing was it slowly pops open after 20 mins every single time I closed it.

Below is a close up picture I took for this issue…

Closing the Sim Card flapWP_20150511_09_20_31_Pro

After 20 Mins… WP_20150511_09_51_14_Pro

Another side-close up of before and after 20 mins…

WP_20150511_09_20_20_Pro

WP_20150511_09_51_08_Pro

I was sick worried about this issue, I thought it would get fixed after sometime , but it didn’t. Then also it hit me that when I first opened the box I saw that this same flap had popped out, but I didn’t take it to much consideration as I had just opened the box and it popped out only after 20 mins. I was wondering whether this phone is also one of those defected phones that Sony had release…

Thankfully, it was fixed… 😀

So the next day I took it to Dialcom, they checked it and cleaned the cover flap with some liquid, which surprisingly fixed it. They said that this happens to most of the Xperia models when they are right out of the factory, and it’s not a big issue whereas it only occurs due to some oil liquid being contacted with the flap during the manufacturing.

So keep in mind, if you are buying this phone, when you first open up the box and any of the Sim card or SD card cover flaps are popped out open, then make sure to inform them and get the flaps cleaned up. So that you won’t go through the same burden I went through…

Oh well now it works perfectly… 🙂 Thanks Dialcom for saving me from a heart attack. But I’m still a bit skeptical whereas this is also one from the defected stock Sony has released. Therefore I will keep a careful watch and update this post.

Conclusion

Now that was my entire experience with before and after buying this phone… Yes ! I’m literally in love with this phone, and I gotta tell you this is one of the best smartphones I have ever experienced.

If you are like me, who doesn’t prefer bigass screen phones, then this is definitely the Smartphone you should go for… pretty sure you will not regret it.. 😉
CHEERS ! 😀

Easily add Code Snippets to your Free WordPress blog’s posts

Sometime back when I was writing a blog post, I suddenly got the need to add some Code Snippets to my blog post and I wanted to give it the real ‘code look’ which you get in IDEs. Unfortunately I couldn’t find anything within the WordPress settings. So as usual I praised google,  but I couldn’t find anything properly related to the ‘free’ version of the WordPress blogs. But somehow after going through so many websites and forums, I finally found a better solution. So here it is,

http://hilite.me/

Its pretty much easy to use this and specially your code looks really nice and there’s a lot customizations you could do using this tool. Lemme show you how,

Step 1 – Copy and Paste your Code to http://hilite.me/
Step 2 – Select Programming Language and Style. You could even edit the CSS as you wish.. 😀

Capture

 Step 3 – Click on Highlight to Generate your Code Preview and HTML snippet…

Untitled1

 Step 4 – Copy the HTML Snippet… ( Ctrl + A & Ctrl + C ) 😛

Untitled1

Step 5 – Paste (Ctrl + V) the HTML Snippet in your Blog post’s Text tab… 😉

Untitled1

Aaand thats it ! You may get a pretty looking code snippet as below… 😉

namespace YourAppNamespace
{
    public class ClassAwesome
    {
        String GetAwesomeness();
    }
}

 

Stay Awesome folks… ^_^ 😀

How to easily get Device IP Address in Xamarin.Forms using DependencyService

So I have been working on an Enterprise level cross platform mobility project since last year, whereas I have been initially using pure Xamarin.Forms cross platform for the entire project.
And recently my boss gave me a requirement of retrieving the IP Address of the mobile device where the user has installed the App. So I straightaway looked for libraries which I could use just to retrieve the IP address, but unfortunately I couldn’t find, even though I came across this Mobile Service Plugins for Xamarin.Forms which actually didn’t work properly in case of retrieving IP address when I implemented it. So while the clock was ticking I decided to write the code from scratch and successfully implemented the feature, tested out in all three mobile platforms in just 30 mins. 😀 (yeeeei 😛 )

When I was writing the code, I couldn’t find any proper tutorial for accessing the network services and retrieving the IP address, which was kinda disappointing. So I thought of sharing the code I wrote with you fellow awesome Xamarin Developers. (I’m gonna assume that you are already aware of DependencyService in Xamarin.Forms platform 😉 )

This piece of code which acts as the interface for the IPAddressManager goes in your PCL project.

namespace YourAppNamespace.Services
{
    public interface IIPAddressManager
    {
        String GetIPAddress();
    }
}

 

This is the code for your Windows Phone project,

[assembly: Dependency(typeof(YourAppNamespace.WinPhone.WinPhone.DependencyServices.IPAddressManager))]

namespace YourAppNamespace.WinPhone.WinPhone.DependencyServices
{
    class IPAddressManager : IIPAddressManager
    {
        public string GetIPAddress()
        {
            try
            {
                List<string> IpAddress = new List<string>();
                var Hosts = Windows.Networking.Connectivity.NetworkInformation.GetHostNames().ToList();
                foreach (var Host in Hosts)
                {
                    string IP = Host.DisplayName;
                    IpAddress.Add(IP);
                }

                IPAddress address = IPAddress.Parse(IpAddress.Last());

                return address.ToString();
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}

 

This is the code for your iOS project,

[assembly: Dependency(typeof(YourAppNamespace.iOSUnified.iOS.DependencyServices.IPAddressManager))]

namespace YourAppNamespace.iOSUnified.iOS.DependencyServices
{
    class IPAddressManager : IIPAddressManager
    {
        public string GetIPAddress()
        {
            String ipAddress = "";

            foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                    netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
                    {
                        if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            ipAddress = addrInfo.Address.ToString();

                        }
                    }
                }
            }

            return ipAddress;
        }
    }
}

 

And finally this is the code for your Android project,

[assembly: Dependency(typeof(YourAppNamespace.Android.Android.DependencyServices.IPAddressManager))]

namespace YourAppNamespace.Android.Android.DependencyServices
{
    class IPAddressManager : IIPAddressManager
    {
        public string GetIPAddress()
        {
            IPAddress[] adresses = Dns.GetHostAddresses(Dns.GetHostName());

            if (adresses !=null && adresses[0] != null)
            {
                return adresses[0].ToString();
            }
            else
            {
                return null;
            }
        }
    }
}

 

Well well thats it. Now go ahead and call that GetIPAddress() method in wherever you want and retrieve the IP address of the mobile device where your apps is installed in. 😉

// Retrieving IP Address in Runtime...

string ipaddress = DependencyService.Get<IIPAddressManager>().GetIPAddress();

 

Oh btw when you compile and run the code, make sure the mobile device is connected to the Internet so that the mobile device will sure be assigned with an IP Address. 😉

Have fun, fellow awesome Xamarin geeks ! 😀