RestSharp Oauth 2.0

My Forex News app (WP8) has been released. Yeay for that! Currently working on my next app. In the meantime, I am in the process of creating an API wrapper for Pocket/Read It Later for C#. Initially I implemented all the Oauth 2.0 manually using WebClient class, but figured out that was the easy part. As I need to GET data (Json) thru data, then I would need to implement Json serializer/deserializer. My initial thought is to use Newton Json, but then it would make more sense if I just leverage on RestSharp. Then I do not need to implement the Oauth process (although I have coded mine, going to scrap those) and let it manage the serialization/deserialization.

The lack of documentation of RestSharp is really annoying. I couldn’t find anything related to Oauth 2.0 implementation. But after trial and error these below code should work to get the request_token. And the rest of the process should be pretty trivial.

        private const string BaseUri = "https://getpocket.com";
        private const string ConsumerKey = "your-consumer-key-from-Pocket";

        private void Login_OnClick(object sender, RoutedEventArgs e)
        {
            var client = new RestClient(BaseUri);
            // Although the API specifies /v3/oauth/request, it gives out 406 Error if no .php extension
            // Request thru Fiddler works fine without the extension
            var request = new RestRequest("/v3/oauth/request.php", Method.POST);

            // Option 1: Use the SimpleAuthenticator
            client.Authenticator = new SimpleAuthenticator("consumer_key", ConsumerKey, "redirect_uri", "http://www.google.com");

            // Option 2: Use the application/json
            // This is the most flexible option. Mostly useful to POST data to server
            request.AddHeader("Host", "getpocket.com");
            request.AddHeader("Content-Type", "application/json; charset=UTF-8");
            request.AddHeader("X-Accept", "application/json");
            request.RequestFormat = DataFormat.Json;
            var jsonObj = new { consumer_key = ConsumerKey, redirect_uri = "http://www.google.com" };
            request.AddBody(jsonObj);

            // Option 3: Use application/x-www-url-encoded
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("consumer_key", ConsumerKey);
            request.AddParameter("redirect_uri", "http://www.google.com");

            client.ExecuteAsync(request, response => Response.Text = response.ContentType + " " + response.Content);
        }

So just pick and choose whatever option you want to use. I would prefer Option 2 and 3. Option 1 is very simplistic but good enough to do the initial authentication process and the rest should be done by Option 2 and 3.

App updates

Had a good productive day writing codes for my upcoming WP8 app. I managed to implement one of the free feature for the app, which is the reminder. I also updated the settings page so user can opt-in/out for the reminder. One problem with the WP8 reminder is that it has this limitation of maximum 50 reminders per app, which is fair for to maintain good performance of the phone. Since in a week, there might be time where there are more than 50 events per week, thus I cannot make the app to set more than 50 reminders.

My first workaround is to try implement the background task. I would let it run maybe once a week, to retrieve latest data and set reminder. The former part can be done, but the latter part can’t be done through background task. WP8 has restricted certain API when running background task. So, there is no other option to do it unless I updated the tile to let the user know (manual intervention) or maybe do push notification, but then I would have to use Azure or other service for push notification. Currently, I choose not to do anything, meaning that if the user doesn’t run the app at least once a week, then no notification/reminder.

Other than that, I just did some cosmetic changes (added icon etc) and re-write some part of the code to improve the performance and for better maintainability.

JavaScript – LinkedList

Recently, I am toying around with JS in order to learn more about it. So I thought of implementing a simple LinkedList. I also implemented the Revealing Module Pattern.

Here is my code:

function LinkedList() {
	var head = null,
		tail = null;
	var count = 0;

	var add = function add(data)
	{
		// Create the new node
		var node = {
				data: data,
				next: null
		};
		// Check if list is empty
		if(head == null)
		{
			head = node;
			tail = node;
			node.next = null;
		}
		// If node is not empty
		else
		{
			var current = tail;
			current.next = node;
			tail = node;
			node.next = null;
		}
		count++;
	};

	var remove = function remove(data)
	{
		// if first item
		if(head.data == data)
		{
			head = head.next;
			count--;
		}
		// if not first item
		else
		{
			var current = head;
			while(current != null)
			{
				if(current.next.data == data) 
				{ 
					if(current.next.next == null) tail = current; 
					current.next = current.next.next;
					count--;
					return;
				}
				current = current.next;
			}
		}
	};

	return {
		Add: add,
		Remove: remove,
	};
}

var list = new LinkedList();
list.Add("A");
list.Add("B");
list.Add("C");
list.Add("D");
list.Add("E"); //count 5
list.Remove("B"); // count 4

It is pretty self-explanatory or google could help.
One thing to note here, which I still haven’t figure out why is that count doesn’t change after I remove it. I commented the line which involve that part. I figured it has something to do with the closure concept in JS, but I haven’t figure out a work around yet.A friend helped to figure this one out, apparently I return out from the method before calling the count--. Nothing to do with closure. I double checked my code again, found it to be erroneous, I fixed it although it is ugly as hell. Will try to figure using recursion when I have time as suggested by a friend.

The LinkedList itself is pretty basic. You could add more to it like AddAfter etc. I think it could also be improved, maybe adding prev property which track the previous node to make traversing easier.

Edit:
http://stackoverflow.com/questions/9672084/expose-private-variables-in-revealing-module-pattern
I believe this should solve the problem.

WP8 – Almost there!

Still working on the app on my free time. It still have a lot of features that need to be implemented. But recently managed to put in settings page. Currently trying to implement the reminder feature.

BTW, market is terribly slow today. Don’t see any good opportunity in EU, but was looking at GU and AU just now. AU reached the area I wanted, but the reaction has not been that good yet. So I’m still on the sideline watching for further clue.

What’s your cup?

Few weeks back, I had an interesting meetup with a friend. We discussed about entrepreneurship, codes, life etc. Along the way there is one part that really make me really think about what is having life.

Each of us is given a cup or a glass, whatever container that you like. But the sizes are all different. This is the measure of our life fulfillment. When the glass is filled up, we feel content. No matter how much you pour water to the cup, if it is already full, it will spill and the volume remains the same. You doesn’t feel any additional satisfaction. This is also the reason why, when you talk to other people with different wavelength as yours (or here with different cup size), there seems to be a disconnect/gap to understand their why. Some people might have a small cup, and they get pretty content with their life quickly. Good for them, but you might be different. Unfortunately, most people will abandon their cup and leave it empty for their rest of life.

This is true in life and it is true I think in my pursuit of happiness. This analogy raised further questions – lots of them. How do you measure your cup? With what do you need to fill it in? How fast/slow do you need to fill it?

But all those questions relate back to one thing in my personal view, it’s doing something you think that matters. I know what it is for me. But I am stuck with a different question – Do I have enough courage to let my cup to be filled? I think it is the only question that matters because if I can answer this, action certainly follows.

I personally know few people who managed to lift a jug and slowly fill their cups – they all have found their courage. For me, I am still looking for my answer and hopefully it is not too late.

Theme-ing WP8 apps!

It doesn’t really that hard as I thought it is. Well initially I thought it was easy but few Google searches here and there return with no good result. I tried overriding the ThemeResources.xaml but it doesn’t work. Apparently it worked last time due to bug in WP7. Mango fixed that.

So I found this tutorial, which is really helpful. Step 1 fixed my problem.

Here is the sneak peek of my coming app. Still a lot to do. My plan is to release it for free with premium features upgradable through in-store purchase.

FX News

Back trading!

I haven’t post anything in a while, since I haven’t been able to trade lately and not really in the mood for it. Today, I took a crack at it. Got in at a right time, and most importantly got out at the right time. It is a scalp trade thus looking for the 1-minute chart with the view of bigger time frame.

On the hindsight though, I think my entry is a bit aggressive, the much conservative entry is the break of 3103 after we have confirmation of some real flow, great momentum to the downside. But of course the entry will a bit lower by few pips, and for scalp trade that matters. That’s the only trade for the day, back to creating other stuff 😀

eum1

Challenge #1

Last night, I spent my whole time trying to actually implement DataTrigger for TextBlock. Well, the answer is simple it is not supported in Windows Phone 8. What a bummer.

My problem is simple, I need to hide some TextBlock if the text is empty. I bind some property to the Text property of TextBlock so I need to check if the data is empty. I could just create another property in the model itself such as IsStringEmpty which return a Visibility. That should work but I want to separate the view with model.

So I resorted to using converter. I’ll post the code later on.
So this is what I have for my converter

public class IsEmptyStringToVisibility : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value.ToString().Length != 0) ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

and this is in the XAML

<TextBlock Grid.Row="1" Grid.Column="1" Foreground="Crimson" Text="{Binding Forecast, StringFormat='{}From {0}'}" Visibility="{Binding Forecast, Converter={StaticResource StringToVisibilityConverter}}" />

So it worked out pretty well, and I managed to keep the Model clean from View.

Missed opportunity!

2013-02-05_2150

Ok, I’m so sorry Mr. Market that I haven’t been paying attention to you since the past few weeks. I was out of country for work. Managed to finally catch up with market.

Look like I still haven’t lost my touch yet 🙂 grateful for that.

Was only watching/waiting for this just now. I haven’t managed to gone through other pairs yet, so only concentrating on Euro/Dollar. I’m waiting for the demand to be flushed, or if it catches some buyers there I’m waiting some sort of spike etc. But the first scenario happened, and I was busy coding my app. *sigh*

So lets wait for other opportunity. As at writing now, Gbp/Jpy has a nice distribution of short that played nicely.

 

Testing code!

namespace FXNewsAlert.ViewModels
{
    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}