Remove Debug / Binaries from GitHub

I am pretty new to GitHub platform and one of the first mistakes I did earlier on was to commit (unknowingly) the Debug Folders and all its binaries. It was later on i found ways to add ‘gitignore’ files, but no matter what i did, the debug files continued to be reflected in the change list.

The solution was though easy one, I had to run the following command to clear the Git Cache, and then stage-commit again. That cleans up all the mess.

git rm -r . --cached

Unit Test for Methods that Call Web API

HttpClient helps you interact with your Rest API’s through its asynchronous methods such as GetAsync. But on a TDD environment, it could become a challenge on how you could write Unit Test cases for a method that invokes the API via GetAsync and ensure that your call successfully invokes the API (considering your API sits in another server and calling it your unit tests would not be ideal). The way I approached this by creating a self hosted API within the Unit Test Project and make the Test Method calls to the API.

The first step was to use Open Web Interface for .Net (or OWIN) to self host an API. Microsoft has put on an extremely useful link for the purpose. Following become by code to configure the API.

 public class WebApiStartup
 {
 // This code configures Web API. The Startup class is specified as a type
 // parameter in the WebApp.Start method.
 public void Configuration(IAppBuilder appBuilder)
 {
 // Configure Web API for self-host. 
 HttpConfiguration config = new HttpConfiguration();
 config.Routes.MapHttpRoute(
 name: "DefaultApi",
 routeTemplate: "api/{controller}/{id}",
 defaults: new { id = RouteParameter.Optional }
 );

 appBuilder.UseWebApi(config);
 }
 }
 The Next Step is go ahead and create the Test Controller, which would be hosting all your api methods.
 [RoutePrefix("api/user")]
public class UserController : ApiController
{
[HttpGet]
[Route("")]
public bool NoParamBooleanResponse()
{
return true;
}
}

Finally, its time to go ahead and write the Test Methods.

 private const string _BaseAddress = "http://localhost:9388/";

[TestMethod]
public async Task CallNoParamAPI_ServerRunning_GetResponseTrue()
{

#region Arrange

var resourceURL = "api/user/SingleParamBooleanResponse";
var restHelper = new RestHelper(_BaseAddress);
bool result;
#endregion

#region Act
using (WebApp.Start<WebApiStartup>(_BaseAddress))
{
result = await restHelper.ExecuteAsync<bool>(resourceURL,HttpMethod.Get);
}
#endregion

#region Assert
Assert.IsTrue(result);
#endregion

}

In the above example, my  restHelper.ExecuteAsync() method invokes the GetAsync Method of HttpClient.

Serialize Deserialize NameValueCollection

Don’t ask me why one cannot Serialize/Deserialize a NameValueCollection, but the workaround for the same is based on conversion to dictionary. I ended up writing extension methods to NameValueCollection for serializing and deserializing the collection.

public static string JSONSerialize(this NameValueCollection _nvc)
{
return JsonConvert.SerializeObject(_nvc.AllKeys.ToDictionary(k => k, k =>_nvc.GetValues(k)));
}
public static void JSONDeserialize(this NameValueCollection _nvc,string _serializedString)
{
var deserializedobject = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(_serializedString);
foreach (var strCol in deserializedobject.Values)
foreach (var str in strCol)
_nvc.Add(deserializedobject.FirstOrDefault(x => x.Value.Contains(str)).Key, str);
}

Simple Timer for Xamarin Forms using Device Timer

While developing your application in Xamarin that requires a Timer, you have the option to use the Device Timer. However, one of the first caveat your would notice is that while Device Class has a Device.StartTimer method, it does not exposes a Stop method, leaving it to your own class to handle it.

I started by writing an interface for my proposed Timer Class ( in my case a Countdown timer), so that I could use it for mocking for the sake of my Unit Tests. This is how my interface looked like.

public class TimerEventArgs:EventArgs
{
public TimeSpan TimeRemaining { get; set; }
}

public interface ICountdownTimer
{
void Start(TimeSpan CountdownTime);
void Stop();

event EventHandler<TimerEventArgs> Ticked;
event EventHandler Completed;
event EventHandler Aborted;
}
 
Following is how the implementation looked like.
public class CountdownTimer : ICountdownTimer
{
#region Private Variable
private bool _Stopped = false;
private TimeSpan _Second = new TimeSpan(0, 0, 1);

private readonly TimeSpan _Interval;
private TimeSpan _TimeRemaining;

private EventHandler _TickedEvent;
private EventHandler _CompletedEvent;
private EventHandler _AbortedEvent;
#endregion

#region Ctor
public CountdownTimer()
{
_Interval = _Second;
}
#endregion

#region ICountdownTimer

event EventHandler ICountdownTimer.Ticked
{
add { _TickedEvent += value; }
remove { _TickedEvent -= value;}
}

event EventHandler ICountdownTimer.Completed
{
add { _CompletedEvent += value; }
remove { _CompletedEvent -= value;}
}

event EventHandler ICountdownTimer.Aborted
{
add { _AbortedEvent += value; }
remove { _AbortedEvent -= value;}
}

public void Start(TimeSpan CountdownTime)
{
_TimeRemaining = CountdownTime;
_Stopped = false;

Device.StartTimer(_Interval, () =>
{
if (this._Stopped)
{
_AbortedEvent?.Invoke(this, EventArgs.Empty);
return false;
}

_TimeRemaining-= _Second;
_TickedEvent?.Invoke(this,new TimerEventArgs { TimeRemaining = _TimeRemaining });

_Stopped = _TimeRemaining.Duration() == TimeSpan.Zero;

if (_Stopped)
_CompletedEvent?.Invoke(this, EventArgs.Empty);

return !_Stopped;
});
}

public void Stop()
{
_Stopped = true;
}
#endregion

Device Information in XF PCL

Today am going to retrieve Phone Device Information in an Android Device with Xamarin Form PCL. Lets start by implementing the interface required for the DependencyService

public interface IPhoneInfoService
 {
 string GetDevicePhoneNumber();
 string GetDeviceID();
 string SIMOperatorName();
 string SIMSerialNumber();
 }
We will now move over the Droid Project and implement the IPhoneInfoService for the project.
class PhoneInfoService : IPhoneInfoService
{
TelephonyManager m_TeleMgr;
public PhoneInfoService()
{
m_TeleMgr = Application.Context.GetSystemService(Context.TelephonyService) as TelephonyManager;
}
#region IPhoneInfoService
public string GetDeviceID()
{
return m_TeleMgr.DeviceId;
}
public string GetDevicePhoneNumber()
{

return m_TeleMgr.Line1Number;
}
public string SIMOperatorName()
{
return m_TeleMgr.SimOperatorName;
}
public string SIMSerialNumber()
{
return m_TeleMgr.SimSerialNumber;
}
#endregion
}

Do not forget to decorate your implementation class with Dependency Attribute

[assembly: Xamarin.Forms.Dependency(typeof(PhoneInfoService))]
Finally, it is time to use the method. We will move to PCL project and (for the sake of this example), use it in the contructor of our MainViewModel.cs.
public MainPageViewModel(IPhoneInfoService PhoneInfoService)
{
m_PhoneInfoService = PhoneInfoService;
string ID = m_PhoneInfoService.GetDeviceID();
}

Note that we have used Dependency Injection by overriding the default Constructor and passing the IPhoneInfoService. Make sure you have READ_PHONE_STATE permission set via the manifest. That’s it.