React Promised Component

Problem Statement: A component, that natively support showing components when a promise is pending, fails or succeeds. And provides a retry capability.

 

 

While working with React, I came across many cool things (that are provided by React and the community). As I moved further into the space, for my application, I found out that in a very basic kind of application there are times when one has to call alot of APIs and showing something depends upon the result of that call.

So, imagine a page having quite many components, all handling different logics from various parts of the application. I wanted an image to be shown when a promise to the API completes and in case it doesn’t complete, I want a retry button to be shown instead.

Similar could be the case for the list of data, for a web view or may be the whole screen (using this name in context of react native).

I went through many pains of having redux in place to do the state management for me in case things fail or succeed. Initially I felt like its awesome! But as the time passed, I figured out that its a lot of trouble to maintain states for each component on the screen or probably most of them. I needed a way to separate this logic from the other things I was doing in the App. I just felt that it is a tedious task and could be done on a pattern, as I can see a pattern being formed there.

Lately, going through the problem, I was reading about higher order components of React. They were something awesome, but before I realized the pattern, they were just another thing to be provided by React itself.

After boggling my head around this problem, I felt that HOC can really solve the mess I am into, and why not give it a try. Amazingly it did all I wanted, with a touch of simplicity.

Moving further, I created yeoman generator for this kind of Component and named it React-Promised-Component, as it responds on promise states with different components.

If you are going around the same problem and want a simple solution, please do checkout what I did on a github repo. The packages are already available on npm and the generator is live as well. I would highly appreciate if you can review the code and share your thoughts on it.

If you are with me till here, Thank you very much for your time, and you are awesome ;)

Advertisements

Chartboost integration in Cocos2dx game

Recently i created a library called EasyNDK (https://github.com/aajiwani/EasyNDK-for-cocos2dx). I was very happy when my code got live, to me it made complete sense, but i guess that wasn’t the case for all the developers out there. Integrating their own SDKs or using 3rd party SDKs wasn’t easy using my code as it seems to be. So, i thought to create a simple tutorial for the most common and pretty easy SDK that is available in both iOS and Android, known as Chartboost (https://www.chartboost.com).

Lets see how easy is the process to integrate it using EasyNDK to have a single code base in C++ and integrate it with Android(Java) and iOS(Objective-C).

1.) Go to Chart boost’s website to create an account or to already use one. (https://www.chartboost.com/)

2.) Download their SDK for the required platform

3.) Create the required application with settings under your account from your dashboard. (https://dashboard.chartboost.com/)

4.) For EasyNDK to work as expected, lets make a receiver held responsible from the native side (Java / Obj-C) to receive messages from C++ and execute them on the native platforms. Here are the steps to be taken.

  • For iOS, in RootViewController.mm

    #include "IOSNDKHelper.h"

    Add this line of code in init method of your RootViewController

    [IOSNDKHelper SetNDKReciever:self];

  • For Android, in your MainActivity.java


    import org.json.JSONException;
    import org.json.JSONObject;
    import com.easyndk.classes.AndroidNDKHelper;

    Add this line of code in onCreate method of your MainActivity

    AndroidNDKHelper.SetNDKReciever(this);

5.) Lets integrate the SDKs with the help of guide available on Chart boost’s site. Please note do not write the Interstitial on the applicationDelegate in iOS or in onCreate method of your activity in Android. I will later show how we will write the showInterstitial method in both platforms. Else than that follow every step that is written under the help sections.

6.) This is the time where our EasyNDK will work, for simplicity in the attached example i am working with the basic hello world project of Cocos2dx, i will simply add a pin button on the left hand side of the close button that is already provided in the example. On tapping it, the showInterstitial method will start working, lets see how.

Step 1.) In your class file (C++) where you want to see the chart boost button, add a button and attach a callback function to it, for here i am doing it in HelloWorldScene.cpp

  • Includes


    #include "NDKHelper.h"
    #include
    using namespace std;

  • Adding a button to the menu in the scene


    // Chartboost button to load interstitial
    CCMenuItemImage *pChartBoostItem = CCMenuItemImage::create(
    "sample_pin.png",
    "sample_pin.png",
    this,
    menu_selector(HelloWorld::chartboostInterstitialCallback) );

    // Adjust Chartboost button
    pChartBoostItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 80, 20) );

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, pChartBoostItem, NULL);

  • Adding the call back that will respond to the button click and will forward message to the native language accordingly, using EasyNDK helper.


    void HelloWorld::chartboostInterstitialCallback(CCObject* pSender)
    {
    // If you want to load interstitial in your desired platform
    // Simply message the platform to do it for you
    // Like this
    SendMessageWithParams(string("LoadInterstitial"), NULL);
    }

That is all from the C++ side, we can now successfully call the Interstitial method from any platform using the same code. Lets implement the handler on both the platform and see the magic happening.

Step 2.)Adding the message handler on both the platforms, using only the ones that are required. Be sure to name the methods(Java) or messages(Objective-C) to be of the same string as you passed from C++. For here i have passed LoadInterstitial as the string from C++ hence i will implement the method with the same name.

  • For iOS, in RootViewController file, as we have attached the receiver to be RootViewController, add this code.


    - (void) LoadInterstitial:(NSObject *)prms
    {
    // Show an interstitial
    [[Chartboost sharedChartboost] showInterstitial];
    }

  • For Android, in MainActivity file, as we have attached the receiver to be MainActivity, add this code.


    public void LoadInterstitial(JSONObject prms)
    {
    // Show an interstitial
    this.cb.showInterstitial();
    }

7.) This is it, we have successfully integrated Chart boost SDK on both Android and iOS with a single code base in C++. Similarly you can connect any SDK you like that is already available on the native platform to work with Cocos2dx.

For the ease and saving time, i am adding sample projects for both iOS and Android with Chart boost already included, so that you can download and test the application if you haven’t understood from the above tutorial. Here are the links to the required downloads.

EasyNDK
EasyNDK Wiki Link
Chart Boost sample iOS project
Chart Boost sample Android project

Thanks for reading the post.

NDK with Cocos2dx made easy

Whenever i worked on Cocos2dx(http://www.cocos2d-x.org), a framework for making 2d games for free, I always thought how would i integrate the 3rd party SDKs into my game. After loads of search and messing up with code, i found out that to do that i need to jump into the languages that the platform provides to connect it easily, or to rewrite the whole thing again on C++ to make sense to the code i am using.

Even writing in different platforms wasn’t that easy when you have to deal with C++ as a core language and jump into the other language to perform some tasks and get back to where you were to make game running smooth. I scratched my head alot of times just to make sure things are working as they should be and most of my time was spent to test the code and linking between languages. After some efforts i was able to run my game as well as get it integrated with some frameworks and 3rd party SDKs on iOS specifically. The time had come to get done with the same game on android platform. My whole code was running, everything was flawless until i found that none of my integration code would work on Android as it was on iOS. It was a sad day for me to find that out, my code was creating un-necessary bugs, stupid errors and most of all includes errors. Finally i managed to work around here and there and on bits to make it work correctly on Android. Done thing!

But from there i thought, why not to create a library on which i can simply pass a message to the language above C++ that is my native platform that is Java or Objective-C and keep my C++ code clean to run on other platforms too that Cocos2dx is supporting or might be supporting. Hence i create something known as EasyNDK.

With this library i can connect to the native platform with minimalistic work to be done and the benefit was as the code was written in the native language any thing that can be done in the native could be done through this mechanism, hence any 3rd party SDK or any work that has to be done on Java or Obj-C could be done here. I my self integrated many libraries using this library. Finally i launched the library on Github for the world to use it and comment over it. Be a part of the users or even testers if you wish to. Let me know about any changes or any improvements that could be done to the library, i will be more than welcome to serve you with my best.

Thanks for reading and giving me your time. Below is the link to Github and the Wiki page i created on Cocos2dx.

Github Code Base : https://github.com/aajiwani/EasyNDK-for-cocos2dx

Wiki Page : http://cocos2d-x.org/projects/cocos2d-x/wiki/EasyNDK

Easy CURL for PHP

Hello all the readers,

This time its about PHP. Yes PHP ! Last project on which i was working on was on PHP. Quite many MySQL in it and quite many web requests. When it came to web requests, the only thing that was in my mind was CURL. That a good to use way to make web requests. As i was working quite after a long time on PHP, didn’t remember much of its library. Went to php.net and searched through the whole libraries and some tutorials to follow to make dummy requests to servers. It was kinda messy. I searched through net to find some wrappers for the CURL in PHP. But ! wasn’t able to find any good OOP based wrapper for CURL in PHP.

Many wrappers were there, and some were really good. But mostly all of them dealt with the underlying curl resource of PHP. Actually that was the problem, remembering all those constants was a pain for me (and i guess for many others). So i thought for a way out of this problem. MAKE MY OWN WRAPPER CLASS.

My goals were quite clear, i have to write such a wrapper that can give the strength of underlying yet be a simple one. So that the pain part can be removed. More over the result should be parsed and fetch in a properties way so that i don’t have to much working on the result to just get out the cookies or headers from it.

Getting inspiration from C# WebRequest class. I tried to create the PHP’s curl class. Please take out your time to view the Examples given with the code. And comment if you like and if you found anything missing or not properly done please report. I would be waiting for the comments.

Thanks.

Link to the Code Repository : Easy CURL for PHP

C# style WebClient for Android

In last several months, i have been working on multiple mobile devices, like iPhone, WinPhone, Android and Palm Pre. I have came to a conclusion after making apps for these devices, that internet is quite a must in each application almost. And all platforms do support the web in quite an awesome way. Although i have tried every basic thing to run web in the device, but i found C#/.NET does it in a natural way that is more intuitive. It simply creates a WebClient and has call back style APIs, whenever any event is fired if we have attached any delegate for that event, that delegate is called. Thats quite AWESOME ! But while working on android i never found such thing in Java, that are delegates to call (Java 6).

And the HttpClient in android is although not a pain to call and work with, but its quite messy to just call a single url. I worked with it for many things, but was not satisfied. So after a while i was like tired of the HttpClient in android, so i tried to port the C# WebClient in android. For that i have to find a generic way that won’t make it even more pain to work with, i tried many things like Handlers and Threads (As it has to be thread safe), but they weren’t that good, the pain is still there. Needed to find a structure that is not verbose but works like a charm.

I came across AsyncTask in android, and it was an easy way to get rid of threads and was thread safe too. I liked it, and decided to make my WebClient a subclass of AsyncTask and it was quite nice to just create and object of this class and call a web page because it is a safe and easy way to handle threads, UI thread is not disturbed. Quite awesome, i found a way out to get out of the mess. But a thing that is left are delegates, else there is no use for it, because it won’t be a generic way to call the webpages.

I searched over net for any delegates thing i found, i found several ways. Two of them were Interface and Reflections (I know its costly). I thought if i would go for Interface any activity that will implement the interface can just have a single call back function to respond on any event WebClient would generate, that is cool but again there would be a mess in that single function that will implement it, there would be a whole lots of switch cases or if then else. Ah that would be bad again. Then the last option was Reflections API, i know, i know its costly. But the effectiveness is more costly than computing. So i decided to move on with Reflections API.

Method was the class that can do the stuff like delegates, but i wanted a better way to call them. So i decided to go for strings as the function name to pass instead of Method. So it makes the API look cool and easy to use, just pass the string as the name of the function, the Class in which this function exists, and if its an instance method pass the receivers instance else just null if the function is static. Well thats just how i made it, i have posted the whole source code on GITHUB, if you want it you may go there and have it, if you don’t want to get messy with code just download the jars and get started. More over i have added a README file over there that contains all the info you require to use the WebClient with examples. Hope you find it good and please comment in either cases if you like it or not.

I will be waiting impatiently for the comments. Thanks.

Link for GIT-HUB : WebClient for Android

Storage on Windows Phone 7

File storage an integral part of an application. One might think of saving a xml file with all the settings of the application in it to the local storage of the application. Its easy to do it on a windows application or console application but what if we want to do it on Windows Phone 7 … ? Its a question many people ask that where to store a file on applications storage in windows phone 7. The answer is Microsoft has provided each application with its storage space. A programmer can get the storage by a simple API call of getuserstorageforapplication and it will return the whole storage place that application has on phone for storing local files and cache materials may be. The storage on which this store is available is known as IsolatedStorageFile. One can access a file in a stream easily through it and as we know there are some great wrappers available in .Net to work with streams. Including the StreamReader and StreamWriter we commonly use. One can get stream from file storage by many mechanisms an easy and fast to access file storage in windows phone 7 has been illustrated. Its really simple how we can work with file storage in windows phone 7 see how i have simply performed read and write operations over a file.

Some basic explanation, the complete code can be found on this link


// This is how to get a storage place from the application, through IsolatedStorageFile class provided by .Net framework
var appStorage = IsolatedStorageFile.GetUserStoreForApplication());

// This is how we get a stream from the storage to work on, then we can easily pass the current stream to the stream wrappers provided in .Net framework already
IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Create, appStorage);

Do comment and wait for more blog posts in near future. Keep visiting the blog for more technical stuffs and news :)

Web Client and Windows Phone 7

While I was developing applications in windows phone 7, I came across many difficulties. Some are still unsolved some are solved. And the unsolved will be solved in near future :)

As Windows Phone is an upcoming platform in mobile industry, I selected it for developing many apps. And the development tools MS gives are really awesome and i think are far better than any other phone development :) (No offense).

One major problem I faced while I was making an app was how could I call a web page or how could I make any HTTP GET request in my application? This was a confusion for me. I knew how to do it in standard .Net framework but .Net framework available in Win Phone 7 is a subset of the original framework. So many approaches failed but I was unable to get what is the least possible effort I can make to do so.

After a long search and experiments, I finally found a neat way of doing it! This might be the simplest approach to call an HTTP resource in a Win Phone 7 app. Lets see how Web Client is useful in our case and write some code and then  I will try to explain how it works.

Lets call a RSS feed from Picasa web for our example and we will be able to see the whole XML from that feed in a TextBlock.

private void GetFeeds()

{

 string url = "http://picasaweb.google.com/data/feed/base/user/jos.brakband/albumid/5512094980648184513?alt=rss&kind=photo&hl=en_US";

 // A class in .Net framework to do the web stuff, without any mess :)

 WebClient webClient = new WebClient();

 // Event that will be called after successfully getting the page

 webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(FeedsDownloaded);

 // Two ways to get a url, one is simply call the url and wait for the result

 webClient.DownloadStringAsync(new Uri(url));

 // other is you can pass an object with it which will be available once url downloading is completed

 // webClient.DownloadStringAsync(new Uri(url), "Test String");

}

private void FeedsDownloaded(object sender, DownloadStringCompletedEventArgs e)

{

 string resultXml = e.Result;

 this.FeedXml.Text = resultXml;

 // You may get the passed test string by

 // String passedString = e.UserState as String;

}
See how simple is it to call any Web Resource using WebClient! There are more ways to do many other things like instead of a GET call what if we want to have a POST call or what if we want to download an image from this or what if I don’t want a string result but I need a IO Stream?
I will be writing many others posts on these topics. Stay tuned!
You can download above code here. Do comment if you have any question or suggestion.