Tag Archives: Xamarin PCL

Wanna easily create an awesome dummy data set ? ;)

So probably you are one of those developers who is looking for a dummy or fake data set for you application development, testing or populate a set of good-looking screenshots for your application ? Yep ! I have been there… 😉

This is something almost every developer had gone through in their lifetime, and most of the time they end up going through the burden of writing a whole bunch of scripts from scratch to populate the data set and so on…

Well, my story…

Sometime back I had the same exact requirement, where I wanted to populated a bunch of fake data for testing out one of my C# dot net applications, not just a few amount, but in big chunks, a whole bunch of dummy emails, address, names and so on. I was actually going to write a bunch of scripts to populate those data by myself, but I got lucky 😉

Behold…

Yes lucky enough I came across this awesome tiny library called Faker.NET Portable Edition ! 😀 So I thought of sharing about it and give it a shout out as it’s a truly great library for easily populating dummy data sets.

capture17

And you can check it out on nuget right here –
https://www.nuget.org/packages/Faker.Net.Portable

Faker.Net.Portable

This is by far one of the easiest and lightest libraries I have used for populating dummy data. This is actually based on the Ruby Faker gem (http://faker.rubyforge.org/) library according to their documentation. It fully supports the below versions of dot net, thereby goes on saying yes you could obviously use this for your Xamarin Forms projects just like I used to.

  • .NET framework 4.0,
  • Silverlight 5.0,
  • Windows 8,
  • Windows Phone 8.1,
  • Windows Phone Silverlight 8,
  • Xamarin.Android,
  • Xamarin.iOS,
  • Xamarin.iOS (Classic),
  • Mono 3.2.8

It’s very much lightweight as well so it wouldn’t be any burden for your application’s compilation size and also it’s pretty fast. 😉

You could check out their documentation and github repo right here –
https://github.com/AdmiringWorm/Faker.NET.Portable

capture19

And trust me it’s super easy to implement, simply add it from nuget or through DLLs to your project and start calling the methods right away… 😀 Some of its awesome uses are as follows,

Names – Create dummy names, not just names with random letters but actual real-human-readable names. You could even separate First Names, Last Names, Middles Names and so on.
https://github.com/AdmiringWorm/Faker.NET.Portable#names

Address– Yep, same goes for addresses as well, streets, cities, states, Zip codes, and even Latitudes and Longitudes… 🙂
https://github.com/AdmiringWorm/Faker.NET.Portable#addresses

Phone numbers – Not just some random numbers, but actual real-like phone numbers with actual area codes and so on.
https://github.com/AdmiringWorm/Faker.NET.Portable#phone-numbers

Company – Let’s you create Company names, Suffixes, Logos (yep with actual images), even fake motos with real words…
https://github.com/AdmiringWorm/Faker.NET.Portable#company

Avatar – Yes that is right actual dummy images, with defined sizes, and image formats of your choice… 😉 A very useful option for displaying profiles, contact lists and so on.
https://github.com/AdmiringWorm/Faker.NET.Portable#avatar

Business – Need to populate Business related data ? Credit card numbers ? expire dates ? You got it !
https://github.com/AdmiringWorm/Faker.NET.Portable#business

Internet – Let’s you easily populate almost all the internet related data such as, domain names, emails, MAC addresses, IPV4 IPV6 Addresses…
https://github.com/AdmiringWorm/Faker.NET.Portable#internet

Lorem Ipsum – Oh yeah, you are going to love this, no need to worry about populating large paragraphs with random words, you could do it very much easily with this library
https://github.com/AdmiringWorm/Faker.NET.Portable#lorem-ipsum

App – Need any dummy App Names ? Authors ? Version numbers to be generated ? Oh well not worry… A simple one method call away!
https://github.com/AdmiringWorm/Faker.NET.Portable#lorem-ipsum

So that’s it fellas, and I wanted to show you some insight to it from the VS Object Browser, and see how impressive it is from down below… 🙂

capture18

Almost all the types of dummy data you need to populate, right here, and not just random ones that doesn’t make any sense, but absolutely real-like dummy content for your applications.. 😀

I felt like this library hasn’t gotten enough coverage, therefore I thought of writing a small blog post giving credits for this and the developers of it. And most of all let this heard for the fellow developers out there, for I hope I may have saved your burden of populating dummy data for your awesome applications… 😉

Cheers folks ! Stay Awesome ! 😀

Advertisements

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 !