Friday, November 18, 2016

[IOS Swift] - using UIImagePickerController

Hello everyone,

   This presentation covers the UIImagePickerController and all the features that we can take on Images for IOS coding. Please, watch this video(below), if you want the code, please send me an e-mail.

Link:
https://youtu.be/Zre0K2Bd5Vk

Or Video:



Happy Coding,
Thiago Leoncio.

Tuesday, November 15, 2016

[IOS Swift] NSUnknownKeyException, reason: [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key string


Hello everyone,

I just would like to write about these kind of inexplicable exceptions that are very common when we merge code in IOS:

Example1:
2016-11-15 04:46:28.168 Paging_Swift[15793:407011] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x7ffdb9512510> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key btnClickMe.'
*** First throw call stack:

Example2:
2016-11-15 05:16:58.366 Paging_Swift[16020:422108] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x7fea38c2ee50> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key imageView.'


In order to fix this such inexplicable exceptions, you must understand - they are often a result of an unclean xib file. Open the xib in xcode, select File's Owner and click on the "Connection Inspector" (upper right arrow), to see all outlets at once. Look for !s which indicates a missing outlet.

So, if you go to your storyboard and the ViewController outlets that you are working on, you will probably find some of them with the '!' signal. Like this:




In this particular case, the specific a controller scene came from a different project, it was renamed as brand new viewController. In this case and for other cases that comes with this exception you can go in two different directions. Here they are:


  •  Rebuild the outlets.
  • Just change the class Name in the reference of this new project. Like this: to ViewControllerImage



After change it, you are going to see all the outlets working properly as below.


I hope it helps and happy coding,
Thiago Leoncio.





Saturday, October 8, 2016

Error 404: java.io.FileNotFoundException: SRVE0190E: File not found: /j_security_check

Hello everyone,


 Today I would like to share with you one error that took 2 days to get it fixed.


Running WebSphere over a RAD eclipse environment I've configured all the details related of JDBC connection, libraries needed for the project and so on.




But it fails in LDAP piece giving an error once I try to login in my application:

Error 404: java.io.FileNotFoundException: SRVE0190E: File not found: /j_security_check




Here it's what I had in my WebSphere configured at that time for Ldap:



The problem is: when you have an LDAP authentication available for you application that's using  WebSphere 8.5, it needs as well a security enable configuration, using a valid userID and password for LDAP purposes. So, you must configure this click two times in your WebSphere App Server in the Eclipse RAD server tab.



So, once you configure it properly your app should be generating the /j_security_check file. And your Admin Console should be login only with a valid ldap_user and password as below:




I hope it helps and fix your ldap/app issues.



happy coding!!
Thiago Leoncio.


How to use waffle library for JNA (Java Native Access)

Hello everyone,


I would like to show you guys how to use waffle library for JNA (Java Native Access).

So, coding time...

[Source Code]

package thiago.leoncio;

import com.sun.jna.platform.win32.Sspi;
import com.sun.jna.platform.win32.Sspi.SecBufferDesc;

import waffle.windows.auth.IWindowsSecurityContext;
import waffle.windows.auth.impl.WindowsAuthProviderImpl;
import waffle.windows.auth.impl.WindowsSecurityContextImpl;

/**
 * @author THiago
 * @Date 10/08/2016
 * @Description: How to get details from current machine.
 * @libs for JNA(jna.jar;jna-min.jar;jna-platform.jar;guava-18.0.jar;waffle-jna-1.8.0.jar)
 */

public class Authenticator {

public static void main(String args[]) {

IWindowsSecurityContext clientContext = WindowsSecurityContextImpl.getCurrent( "Negotiate", "localhost" );

// create an auth provider and a security context for the client
// on the server
WindowsAuthProviderImpl provider = new WindowsAuthProviderImpl();
IWindowsSecurityContext serverContext = null;

do {  

    if (serverContext != null) {
        byte[] tokenForTheClientOnTheServer = serverContext.getToken();
     SecBufferDesc continueToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, tokenForTheClientOnTheServer);
        clientContext.initialize(clientContext.getHandle(), continueToken, "localhost");
    }

    byte[] tokenForTheServerOnTheClient = clientContext.getToken();
    serverContext = provider.acceptSecurityToken("server-connection", tokenForTheServerOnTheClient, "Negotiate");

} while (clientContext.isContinue());

// client is, only by exchanging byte[] arrays
System.out.println(serverContext.getIdentity().getFqn());
}
}

[Output]
networkName\userID


as I explained in previous blog:
"
On top of JNA exists a library called Waffle which encapsulates all functionality you need to implement user authentication. Get from GitHub at https://github.com/dblock/waffle and also on Maven central. To download the jar files get from here: https://github.com/dblock/waffle/releases/download/Waffle-1.8.0/Waffle.1.8.zip
"

Please, see this JNA and Waffle article also:
http://phonecoding.com/2016/06/how-to-get-details-from-current-machine.html

Happy coding..
Thiago Leoncio.

Saturday, October 1, 2016

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/cache/CacheBuilder on WindowsAuthProviderImpl class


Hey guys,


Recently I was working with JNA using Waffle to get the user details, and at same time creating a token on client side, in order to create a trust relationship between the targets.. Then i got this issue that I would like to share how to fix:

On top of JNA exists a library called Waffle which encapsulates all functionality you need to implement user authentication. Get from GitHub at https://github.com/dblock/waffle and also on Maven central. To download the jar files get from here: https://github.com/dblock/waffle/releases/download/Waffle-1.8.0/Waffle.1.8.zip



Using waffle project I got this error recently:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/cache/CacheBuilder
at waffle.windows.auth.impl.WindowsAuthProviderImpl.<init>(WindowsAuthProviderImpl.java:68)
at waffle.windows.auth.impl.WindowsAuthProviderImpl.<init>(WindowsAuthProviderImpl.java:58)
at thiago.leoncio.Authenticator.main(Authenticator.java:19)
Caused by: java.lang.ClassNotFoundException: com.google.common.cache.CacheBuilder
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 3 more


To fix this you must add the library that has all google classes. It's name is guava-18.0.jar  and of course the waffle one: waffle-jna-1.8.0.jar


Please, check this JNA and Waffle article also:  http://phonecoding.com/2016/10/how-to-use-waffle-library-for-jna-java.html


I hope this helps,
Thiago Leoncio.

Saturday, September 17, 2016

How to setup Apache Invy dependencies in Eclipse

Hello everyone,

     I am here today to share with you how to setup Apache InveDE and these great features that comes with with Ivy.

First of all I would like to explain you what are the benefits of using Apache Ivy on you projects:

 Apache Ivy born from Apache Ant project. It born to resolve project dependencies and the time consuming to find what are the project dependencies every time you load it on a different place. In some way I would say that it competes with Apache Maven, but they differ on the distribution. Maven is a complete build tool, whereas Ivy is focused only on managing transitive dependencies. So, is some way I would say that the beauty of Ivy is that you can use the feature with any build process you already have in your company. So, Ivy has an external XML file that defines project dependencies as well as the list of resources necessary to build a project. Ivy then resolves it and downloads resources from an artifact repository. The last one can be either a private repository or one publicly available on the Internet.


Second of all I will provide you the steps to make it happen in Eclipse IDE, so let's rock it on!

First Step:



    1. On Eclipse: add the IvyDE update site. Following these steps (Note that for Eclipse 3.4 it may be different than what I am showing you today):
    2. Eclipse-Open the update manager tool: Help > Software Updates > Find and Install...
    3. On the popup window, select Search for features to install, and click Next
    4. Click on New Remote Site... to add new url.
    5. Name: the way you want, but I will suggets something related of Ivy to not forget it
    6. URL: http://www.apache.org/dist/ant/ivyde/updatesite
    7. Click OK
    8. A new entry "Ivy site update" will appear in the list of update sites

  • Configuring the Ivy IDE plugin
    1. In order to move forward, please have created Ivy files in the eclipse project if you are setting up a new project or they are not included in the your project already.                                
    2. Add the libraries related of Ivy, running the add library feature, and the library called 'IvyDe Managed Dependencies'. 
    3. Have configured the library to use the files created in step1.  
    4. If you don't see the dependencies by any reason, you can always add it manually click on 'resolve dependencies' feature.

           


   Once you are done with these steps above, you are ready to start coding and working with Ivy on your Eclipse new project. Please remember that you can use any build tool with Ivy libraries.


I hope it helps you, if so share with others. See you on next topic.
Thiago




Saturday, August 20, 2016

How to use JAXB for Unmarshalling

Hello everyone,

Today, I would like to show you how to read and XML using JAXB library.

0-Make sure your project has the library
1- We need to create the object for JAXBContext.
2- We need also to create Unmarshaller objects that will be used to unmarshal method loading the content of the file.




package thiagolguimaraes;

/**
 * @author Thiago leoncio
 *
 *This is JAXB Unmarshalling Example: Converting XML into Object
 *
 *The steps to convert XML document in the java object are:
 *
 *Create POJO or bind the schema and generate the classes
 *Create the JAXBContext object
 *Create the Unmarshaller objects
 *Call the unmarshal method
 *Use getter methods of POJO to access the data
 *
 */
import java.io.File;
import java.util.List;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
 
public class XmlToObject {
    public static void main(String[] args) {
 
     try {
 
        File file = new File("src\\thiagolguimaraes\\question.xml");
       
       
        //Create the JAXBContext object
        JAXBContext jaxbContext = JAXBContext.newInstance(Retrieve.class);
        //Create the Unmarshaller objects
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        //Use getter methods of POJO to access the data
        Retrieve que= (Retrieve) jaxbUnmarshaller.unmarshal(file);
         
        System.out.println(que.getId()+" "+que.getRetrievename());
        System.out.println("Responses:");
        List<Response> list=que.getResponses();
        for(Response ans:list)
          System.out.println(ans.getId()+" "+ans.getResponsename()+"  "+ans.getPostedby());
 
      } catch (JAXBException e) {
        e.printStackTrace();
      }
 
    }
}

---------------------------------------------------------------------------------------------------
/**
 *
 */
package thiagolguimaraes;

/**
 * @author Thiago Leoncio
 *
 */
import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
public class Retrieve {
private int id;
private String questionname;
private List<Response> answers;
public Retrieve() {}
public Retrieve(int id, String questionname, List<Response> answers) {
    super();
    this.id = id;
    this.questionname = questionname;
    this.answers = answers;
}
@XmlAttribute
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
@XmlElement
public String getRetrievename() {
    return questionname;
}
public void setRetrievename(String questionname) {
    this.questionname = questionname;
}
@XmlElement
public List<Response> getResponses() {
    return answers;
}
public void setResponses(List<Response> answers) {
    this.answers = answers;
}
}

---------------------------------------------------------------------------------------------------

/**
 *
 */
package thiagolguimaraes;

/**
 * @author Thiago Leoncio
 *
 */
public class Response {
private int id;
private String answername;
private String postedby;
public Response() {}
public Response(int id, String answername, String postedby) {
    super();
    this.id = id;
    this.answername = answername;
    this.postedby = postedby;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getResponsename() {
    return answername;
}
public void setResponsename(String answername) {
    this.answername = answername;
}
public String getPostedby() {
    return postedby;
}
public void setPostedby(String postedby) {
    this.postedby = postedby;
}
 
}



Happy coding,
Thiago Leoncio.

Saturday, August 6, 2016

How to read a XML file from jar in Java



Hello everyone,


I would like to show you how to find/read a file that comes from a jar(compressed file) and provide the content of this.


Structure of folders and files I have:
File.jar
-->under File.jar there is a folder called zipThiagoFolder that has the xml file named xmlFileNameInJarFile.xml


Source code:

/**
 *
 */
package thiago.leoncio;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.IOUtils;

/**
 * @author Thiago Leoncio
 * @date 08062016
 * Description: provide the details on how to read a XML file from jar or compressed file in Java
 *
 */
public class FindXmlContentInCompressedFile {

/**
* @param args
*/
public static void main(String args[]) {
//relativePath is the file that you are searching inside of the Jar/zip file.
   String relativeFilePath = "zipThiagoFolder/xmlFileNameInJarFile.xml";
   //The zip path is where the compressed files is.
   String zipFilePath = "C:\\codes\\TesterProject\\src\\thiago\\leoncio\\File.jar";
   String contents = readZipFile(zipFilePath,relativeFilePath);
   System.out.println(contents);
}

public static String readZipFile(String zipFilePath, String relativeFilePath) {
   try {
       ZipFile zipFile = new ZipFile(zipFilePath);
       Enumeration<? extends ZipEntry> e = zipFile.entries();
       while (e.hasMoreElements()) {
        System.out.println("[LOG] While it's getting the elements on XML content");
           ZipEntry entry = (ZipEntry) e.nextElement();
         
           // if the entry is not directory and matches relative file then extract it
           if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
            System.out.println("[LOG] Relative Path:"+relativeFilePath);
               BufferedInputStream bis = new BufferedInputStream(
                       zipFile.getInputStream(entry));
               // Read the file
                   // With Apache Commons I/O
               System.out.println("[LOG] Converting in String file using Apache lib[commons-io-2.5.jar] for fileContentsStr var");
                String fileContentsStr = IOUtils.toString(bis, "UTF-8");

                   // With Guava
               //String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
               // close the input stream.
               bis.close();
               return fileContentsStr;
           } else {
               continue;
           }
       }
   } catch (IOException e) {
       e.printStackTrace();
   }
   return null;
}

}


Expected output:

[LOG] While it's getting the elements on XML content
[LOG] While it's getting the elements on XML content
[LOG] Relative Path:zipThiagoFolder/xmlFileNameInJarFile.xml
[LOG] Converting in String file using Apache lib[commons-io-2.5.jar] for fileContentsStr var
<References xmlns="http://xmlns.oracle.com/adf/jndi">
  <Reference name="thiago" className="oracle.jdeveloper.db.adapter.DatabaseProvider" credentialStoreKey="thiago"
             xmlns="">
    <Factory className="oracle.jdevimpl.db.adapter.DatabaseProviderFactory1212"/>
    <RefAddresses>
      <StringRefAddr addrType="oraDriverType">
        <Contents>thin</Contents>
      </StringRefAddr>
      <StringRefAddr addrType="hostname">
        <Contents>clusterd-RacThiagoleoncio</Contents>
      </StringRefAddr>
      <SecureRefAddr addrType="password"/>
      <StringRefAddr addrType="subtype">
        <Contents>oraJDBC</Contents>
      </StringRefAddr>
      <StringRefAddr addrType="port">
        <Contents>3099</Contents>
      </StringRefAddr>
      <StringRefAddr addrType="serviceName">
        <Contents>SIDTESTThiagoLeoncioEnvironment</Contents>
      </StringRefAddr>
      <StringRefAddr addrType="user">
        <Contents>ThiagoLeoncioUser</Contents>
      </StringRefAddr>
    </RefAddresses>
  </Reference>
</References>



Happy coding,
Thiago Leoncio.

Saturday, July 2, 2016

Simple and useful example of exceptions handling in Java

hello Folks,

[Java - Coding time]


  • Exceptions handling code example. It's always helpful having these code' handy.


[Source Code]

/**
 *
 */
package thiago.leoncio;

/**
 * @author Thiago
 * @Date 07/02/2016
 */
public class ExceptionExample {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

try {
int num1 = 30, num2 = 0;
int output = num1 / num2;
System.out.println("Result = " + output);
} catch (ArithmeticException e) {
System.out.println("[PhoneCoding.com-INFO LOG] Arithmetic Exception: You can't divide an integer by 0");
}
try {
int a[] = new int[10];
// Array has only 10 elements
a[11] = 9;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("[PhoneCoding.com-INFO LOG] ArrayIndexOutOfBounds");
}
try {
int num = Integer.parseInt("XYZ");
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("[PhoneCoding.com-INFO LOG] Number format exception occurred");
}
try {
String str = "easysteps2buildwebsite";
System.out.println(str.length());
;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("[PhoneCoding.com-INFO LOG] StringIndexOutOfBoundsException!!");
}

try{
String str=null;
System.out.println (str.length());
}catch(NullPointerException e){
System.out.println("[PhoneCoding.com-INFO LOG] NullPointerException..");
}


}

}


Happy, very happy coding,
--Thiago Leoncio



Saturday, June 25, 2016

How to set up Icons that displays differently amid iOS and Android devices


Hello folks,

We've already mentioned how great and powerful Ionic framework is. But it has several useful functions such as ionic.Platform.isAndroid(), ionic.Platform.isIOS(),  and ionic.Platform.isWindowsPhone()
that might be extremely helpful to you use within your code to detect which icon to use. That's a great feature that we can not skip and the reason why I've created this article just for that.

An example of this is:

var iconThiagoLeoncio;

if (ionic.Platform.isAndroid()) {
  iconThiagoLeoncio = 'ion-android-arrow-back';
} else if (ionic.Platform.isIOS()) {
  iconThiagoLeoncio = 'ion-ios-arrow-back';
} else {
  iconThiagoLeoncio = 'ion-android-arrow-back';
}


In practice, I am going to to do a simpler check. If it is Android, use the Android icon, otherwise use IOS. This won’t work as neatly if you want to specify ionic.Platform.isWindowsPhone() ,
 however so far Ionicons have no Windows Phone specific icons so I am using Android icons as standard coding project:


var iconThiagoLeoncio = ionic.Platform.isIOS() ? 'ion-ios-arrow-back' : 'ion-android-arrow-back';


When this is in objects by itself, I am going to use regularly, I am turning the object into a directive which contains this logic specifically.
For example, a custom back button (replace starter with the global app name you use for your modules in such):

angular.module('starter.directives', [])
    .directive('backbutton', [function () {
        return {
            restrict: 'E',
            replace: true,
            scope: false,
            template: '<button class="button icon button-clear"></button>',

            compile: function (element, attrs) {
                var iconThiagoLeoncio = ionic.Platform.isIOS() ? 'ion-ios-arrow-back' : 'ion-android-arrow-back';
                angular.element(element[0]).addClass(iconThiagoLeoncio);
            }
        };
    }])


This code above creates the the element below:


<backbutton ng-click="goBack()"></backbutton>

With that in mind and in your code you can reuse across many different apps and we can keep this in sych(updated) with any new changes in your location.

Very important to mention in here:
There is a back button element in Ionic, however we are creating our own simpler version for some situations, for example a custom modal windows in your project.
Keep in mind this great example just works for any other button and icons you might want to use as well.

Another IONIC article on my blog:  Ionic How to get started with Ionic

happy coding,
Thiago Leoncio

Saturday, June 18, 2016

Error Oracle Database 12c installation for IAM Oracle


Hello my friends,


If you run into the error "error invoking target irman ioracle of makefile" while trying to install Oracle Database, and the log shows a missing ljavavm12 library, you might need to copy the java library like so:



cp /opt/oracle/product/12.1.0/dbhome_2/javavm/jdk/jdk6/lib/libjavavm12.a /opt/oracle/product/12.1.0/dbhome_2/lib/


I hope it helps,
Thiago Guimaraes

Saturday, June 4, 2016

How to get details from current machine in java using JNA(Java Native Access)

hello Folks,

[Java - Coding time]


  • How to get details from current machine in java.

More about JNA:

Java Native Access (JNA)

To use Windows and the domain controller for authentication, we can use native Windows APIs. To call those APIs in Java, we can use the Java Native Access (JNA) library, which you can find on GitHub at https://github.com/twall/jna and on Maven central:

[Libs]


[Source Code]


/**
 *
 */
package thiago.leoncio;

import java.net.UnknownHostException;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.Advapi32Util.Account;

/**
 * @author THiago
 * @Date 06/04/2016
 * @Description: How to get details from current machine.
 * @libs for JNA(jna.jar;jna-min.jar;jna-platform.jar)
 */
public class MachineDetails {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

System.getProperty("user.name"); //platform independent
java.net.InetAddress localMachine = null;
try {
localMachine = java.net.InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hostname of local machine: " + localMachine.getHostName());
System.out.println("UserName logged on your machine:" +System.getProperty("user.name"));
System.out.println("=========== Java Native Access (JNA) details ===========");
for(Account account: Advapi32Util.getCurrentUserGroups()){
       System.out.println(account.fqn);
    }

}

}




[Output]:
Hostname of local machine: TLEONCIO_LAPTOP
UserName logged on your machine: tleo73638
=========== Java Native Access (JNA) details ===========
WST\domain users
Everyone
BUILTIN\Administrators
BUILTIN\Users
NT AUTHORITY\INTERACTIVE
CONSOLE LOGON
NT AUTHORITY\Authenticated Users
NT AUTHORITY\This Organization
..

Please, see this JNA and Waffle article also:  http://phonecoding.com/2016/10/how-to-use-waffle-library-for-jna-java.html



happy coding,
--Thiago

Sunday, May 1, 2016

Sencha - More about Sencha Touch 2 Framework

Hello everyone,

   As I did mention last weekend, this weekend I am going to show you how to run your app using Sencha Touch Framework. Sencha Touch is a user interface (UI) JavaScript library, or we can say a framework, specifically built for the Mobile Web. You can use it to develop user interfaces for mobile web applications that look and feel like native applications on supported mobile devices. That's the beauty of it.

Sencha Touch is fully based on web standards such as HTML5, CSS3 and JavaScript.  The magnificent  of Sencha Touch is this framework enable developers to quickly and easily create HTML5 based mobile apps that work on Android, iOS, Windows, Tizen and BlackBerry devices, and produce a native-app-like experience inside a browser.

So, today I'm gonna show you the step-by-step to run Sencha via browser or via Apache Cordova, if you will.

Let' move it on:

Step 1: Go to https://www.sencha.com/ and download your Sencha Touch Framework as below:

You Should get a folder like this. The release that I am using is touch-2.4.2.



Step 2: I do recommend you to download the Sencha Cmd library, install and add in in your .bash_profile to make it easy to execute Sencha commands as I'm gonna show here today.

Go to https://www.sencha.com/products/extjs/cmd-download/ and download it to you machine.


Step 3: Install Sencha Cmd as it's showed below and check if there is any upgrade pending doing the commands I am showing on the next pictures. Eg: Sencha upgrade --check










Step4: Here it's the good and easy part to launch your Sencha App - Go to your App folder -Run these 3 commands to make your app a Sencha app:

sencha generate app -ext MyApp /path/to/MyApp


Note:If your app is not upgraded for the latest sencha version you should get this issue below when running generate command. The solution is just run as It shows below sencha app upgrade command.


sencha -sdk /path/to/ext generate app MyApp /path/to/MyApp

sencha app build


Then run sencha diag show  to see what sencha framework can get from your app that was already built based on Sencha.



Step 5: Now you should be able to launch your app running sencha app run command.
You should be able to get your app running over your browser, eg: http://localhost:1841/yourapp



NOTE: If you get any issue on running part of your app, just run sencha app watch command as below.





Now, that you have your Sencha app running fine, I want to tell you the good thing. We can run it from Apache cordova as well. So, let's see how it goes:

Step7 - Run the command sencha cordova init to initialize cordova folder over your sencha app project folder.



You will see that you have a folder for cordova inside of your app folder as I am showing below:


So, Apache Cordova requires you to add the platform that you want to launch your emulator. In this example is IOS. Note: You must run cordova platform add ios under the cordova folder that was created during sencha cordova initialization.


Don't forget to replace the files in cordova to make it part of your previous sencha app, eg:index.html and others.



type: cordova run


then have fun using cordova emulator. If you get stuck with cordova, you can see more about it on my previous blog related of cordova last year:



Happy coding,
Thiago Leoncio.



Saturday, April 2, 2016

IOS - Maintaining a Block in Memory

IOS - Maintaining a Block in Memory

In Objective-C extension/block specification - "All Blocks are constructed to be Objective-C objects regardless of whether the Objective-C runtime is operational in the program or not. ", and they have the same memory layout. This consists primarily of its captured variables. Specifically for blocks the actual code is not stored in the memory but in a different part of the memory(text) with the rest of the executable code on your app.
When a block is created, the data associated with it are stored in the stack, including variables in its scope that it has taken a snapshot of. (The stack is a temporary memory that, in the form of a stack frame for the currently executing C function, stores information needed for executing that function--function parameters, local variables, and control information.)
When objective-c block goes out of scope, this memory ‘in place’ is subject to reallocation and then the block will be no longer valid.
If a block is used in the parameter of a method that is synchronous--that is, the code calling the block waits for the method to perform its computations before going on--there is no problem. The block will continue to be in scope, and its stack frame will still be there and available to the method being called.
If the method is asynchronous, however, the call of the method only starts its computation, which continues after the return of the method--there is a potential problem. The memory for the block may be overwritten before the code in the block executes. To avoid this problem it is common practice for an asynchronous method to copy the block from the stack to the heap by performing a copy operation. (The heap is the much larger and more permanent memory that contains segments of memory that the program can request.)
If it is otherwise desired to execute the block outside the scope it was created in, the block also needs to be copied to heap memory.

So, now let's see a block copy:

A block can be copied by sending a copy message to the block.

    void (^simplestThiagoBlock) (void);
    simplestBlock = ^{
         NSLog(@"Hi, I'm a Thiago’s block.");
 
    };
    [simplestThiagoBlock copy];

Please, understand that copying the block to the heap makes it subject to reference counting. If manual reference counting is used, the block should be released when no longer needed. So, keep this in mind in future.
In general, it is rare that you will need to copy a block. The first copy will move the block from the stack to the heap. Successive copies do nothing then only increasing the retain count. If you need to make an actual copy of a block, better you will need to recreate it.

Happy coding,
Thiago Leoncio.

Sunday, March 27, 2016

IONIC - How to get started with Ionic Framework

Hello everyone,

Today I am gonna show you how to start coding, emulating and having fun with this such great mobile app framework called Ionic. I've been using it 'for fun' since 2014 and it's an useful tool if you want to code as JavaScript instead of other native languages such as Objective-C and Java. In my case I play with both, so, it's really up to you whether or not use it. This weekend I am going to provide you more about it. I hope you enjoy it.

1- First have your Node.js installed on your computer. The current version working with Ionic is Node 4. Node 5, according to the Ionic site at this date, is not yet available for Ionic. Check the site related of Ionic here - http://ionicframework.com/docs/

I have the version 4.4.1 as you can see below on my Mac




2- Make sure you install or have it installed before you start the Apache Cordova Framework that works with Ionic. My current version of Cordova is 6.1.0 as you can see below.


3- I did install my Ionic 1.7.14 version.



4- Starting a project:
ionic start thiagoleoncioApp tabs

4.1- As you can see, it is going to ask if you want to register for push notifications or not.
I would recommend you say yes, as it helps you during your coding to have this option/feature available.


If you type y above, it will give you the option to register your notifications over Ionic site:


NOTE: You probably have noticed that I typed ionic start + my projectname+ tabs.



Here, in this start command we have option to start as blank,tabs or sidemenu. So, if you go with sidemenu your project will start with something similar to this.



5- Now you can run your Ionic project with these commands:
$ cd thiagoleoncioApp --> GO to your project folder created when you started it.
$ ionic platform add ios  --> Add in your platform IOS or Android or another mobile emulator you want to it.



$ ionic build ios

...



$ ionic emulate ios 

COMMON ISSUE: If you are running IOS emulator and you did not install yet iso-sim project you are probably gonna get an issue like this:

ios-sim was not found. Please download, build and install version 3.0.0 or greater from https://github.com/phonegap/ios-sim into your path. Or 'npm install -g ios-sim' using node.js: http://nodejs.org
Error: /Users/tguimaraes/thiagoleoncioApp/platforms/ios/cordova/run: Command failed with exit code 2


So, make sure you run the command - npm install -g ios-sim before emulate it in your Mac.

6- So now, emulating it:
...


7- Here it is your project structure created to develop in IOS using Cordova Ionic Framework.



 Just change the code or whatever you would like and move it on!





Next weekend, I am going to show you guys how to develop using Sencha Touch.

Another great article related of Ionic: How to set up Icons that displays differently amid iOS and Android devices

I hope it helps and happy coding!
Thiago Leoncio.