Tuesday, July 26, 2016

NativeScript + Angular 2: How to fix TNSLabel error

When using NativeScript + Angular 2, some strange errors may occur as Angular 2 is in RC and has many issues yet. Therefore some strange errors occur.

I've encountered such error while running my app in iOS emulator:


CONSOLE ERROR file:///app/tns_modules/zone.js/dist/zone-node.js:419:27: Unhandled Promise rejection: Can't find variable: TNSLabel ; Zone: angular ; Task: Promise.then ; Value: ReferenceError: Can't find variable: TNSLabel

The fix is rather easy - just remove and add the iOS platform.

tns platform remove ios
tns platform add ios

 Run your app again and you're all set!

How to: Setup genymotion/genyshell commands in zsh

After you install Genymotion on MacOS, it's installed in the Applications folder. Unfortunately, the PATH variable is not set automatically, therefore running:
genymotion
or
genyshell
in the Terminal will result in an error.

In order to fix this, so that every time you open the Terminal or restart your PC, you need to setup your profile to export and add the correct paths to the $PATH variable. Here are the steps for zsh users:

  1. Open the zsh profile for editing: sudo vi ~/.zshrc
  2. Add the following lines at the end of the file, so that the genymotion paths for App and Shell are both added tot he $PATH on startup. In previous/next versions, the paths to the Genymotion.app and Shell may have changed so you can verify these.

          export GENYMOTION_APP=/Applications/Genymotion.app/Contents/MacOS
          export GENYMOTION_SHELL=/Applications/Genymotion\ Shell.app/Contents/MacOS/

          export PATH=$PATH:$GENYMOTION_APP
          export PATH=$PATH:$GENYMOTION_SHELL

      3. You can now test your setup by running source ~/.zshrc which will execute in the current terminal your updated profile script
      4. You can see the PATH contents with echo $PATH or try running genymotion and genyshell from terminal.

Happy scripting!

Monday, June 1, 2015

Java for C# developers: Access Modifiers

Access Modifiers

(Java for C# developers)


What is an access modifier?

An access modifier is a keyword, which specifies the visibility and the access to a member (field, method, property) or a class. Therefore, it defines the rules by which your API/classes can be used and utilized - what can be changed, what should never change, what is internal and should not be exposed to anyone but the maintainer of the library, etc.

Why is it important?

When exposing your application to the world (i.e. - your colleagues, your clients) you must take care of protecting your classes and make them more robust. Here are some common cases, where taking a wrong decision can hurt you in the long term:

  • If a method is public everyone will start using it. This means, that it's harder for you to later hide this method. You cannot change what it's doing and you have to supported it happily ever after. (Note: there are ways to start deprecating methods, but it takes time and effort for everyone)
  • If a variable is public everyone has access to it and can easily modify it. This can change the behavior and correctness of your application.
  • If a variable is protected all inheriting classes will have access to it. This means, you have to keep it in the base class, but gives you the availability to provide special access to classes inheriting the base class.

Comparison

In C# libraries are organized in namespaces and DLLs, whereas in Java they are organized in packages. We can assume that libraries/namespaces and packages are similar and compare the access modifier in this context.

Access modifiers are slightly different on classes and class member levels, so we'll compare them separately.

Class

Access C# Java
default Defaults to internal - access limited to current assembly Defaults to package-private - access limited to the package
private Access limited only to containing class. Used for nested classes. Access limited only to containing class. Used for nested classes.
public No restriction on the access. No restriction on the access.

Member
Access C# Java
default Defaults to private - access limited to current class Visible across the package, cannot be access from inheriting classes.
private Access limited to only current class. Access limited to only current class.
public No restriction on the access. No restriction on the access.
protected Visible in current and inheriting classes. Visible in current and inheriting classes.
internal Access limited to the current assembly. No such keyword. Similar to no modifier - i.e. package-private.


As you can see, C# and Java modifiers are not so different. They are almost equivalent and the same concepts are applied in both languages. Most notable difference is that the default member access is private in C# and package-private in Java, so if you're used to not writing access modifiers, you'd better start explicitly adding them to prevent code problems and protect your variables.

Rule of thumb

Set the most specific and limited access possible - don't expose more from your classes than you need to.

The rule of thumb in access modifiers is shared amongst all OOP languages. Expose just as much as required and protect everything else. This can give you the freedom to change the underlying implementation, data structures and rename fields/methods which are not visible. Don't allow easy break-in your functionality.

References:

Friday, May 15, 2015

Everlive API Swagger

Swagger

Swagger is now the defacto standard for documenting REST APIs - it's widely used, known and adopted. In most cases, you add comments and meta information to your APIs in your own code, and swagger can generate an API reference for it. It's not a static one though, not only you can see the definitions, parameters and etc. but you can even give it a try, which is awesome.

Everlive

If you're using the Telerik Backend Services (a.k.a. Everlive) you may find this little project quite useful. By entering your API Key and Master Key it dynamically generates a Swagger API definition for your Content Types in Everlive. Therefore, you can easily test out stuff - add items, query items, check boundary cases like errors and etc - the best part is that you can do this without writing a single line of code.

Swagger + Everlive

The project generates dynamically a Swagger definition for an Application in the Telerik Backend Services. By providing your API and Master Keys the service extracts your Application's Metadata and generates a Swagger Definition with all your Content Types and Fields. The auto-generated content is then displayed in the nice Swagger UI. 








Give it a try and let me know what you think.

Tuesday, October 28, 2014

Open Source + Me

Hi guys,

it's been a while - but as you see I've kept my 'letter-style' of writing. Just kidding.

Recently I've came out of my "comfort" zone at work, therefore I've made a big shift from the Microsoft/.NET/C# to open source - Node/Angular/Mongo DB technologies. Adopting to this new for me world was quite challenging and knowledge rewarding. Although not feeling very confident, I wanted to start contributing somehow to the Open Source community. Therefore, I've decided to extract 2 very simple and generic projects from my personal stuff.

Minimalistic: Node JS + Angular JS + Require JS

For the past months, I've been working on a great project, involving the so-called MEAN (Mongo DB + Express JS + Angular JS + Node JS) stack. Bootstrapping the application in the beginning seemed like the hardest part and involved a steep learning curve. What I needed and wanted:

  • Web Application with Angular JS
  • With Require JS to wire up the external dependencies
  • With a minimalistic Node JS server
  • All this as simple as possible, without any overhead
  • Run in 2-3 commands from the command line

What I found out there were many seed projects, with HTML 5 boilerplates, styles, heavy Node JS server implementations and etc. So, I've setup a minimalistic seed project, which has all the points above covered - nothing more, nothing less.

The project is located at GitHub here: https://github.com/yyosifov/angular-require-seed and is truly minimalistic and simple. 

Yet, this is an Angular JS web app wired up with Require JS and served by Node. I'll definitely use it whenever I need to setup an Angular JS web app. What can be added - Grunt/Gulp make files, sample tests with Karma and a little heavier Angular JS app with a Service, Module and one more route.

Arduino: Temperature Measurer

Another minimalistic project - a sample Temperature Measurer class, implemented in Node JS. What it does is measure a Temperature retrieving the data from an Arduino device and emit event with the gathered data. It can be easily plugged in any home/office automation project, as long as you've already have the required hardware (Arduino + Temp sensor). The sample application + temperature measurer is again hosted on GitHub: https://github.com/yyosifov/temperature-measurer. As simple as it gets, I've been using this for a while and haven't noticed any side effects, yet.

Conclusion

The open source world reveals a whole new range of opportunities. It's awesome that you can learn and get inspired from the code of so many smart guys. Now I'll just have to find out how some Open Source have become viral and popular, whereas others have never been downloaded/forked...

In a bottom line, what came to my mind is the following wordplay:

Some things never change and some things always change (like technology and trends).

Tuesday, April 8, 2014

Upstart - Syntax error: Bad fd number upstart

Debugging upstart scripts is hard and cumbersome. I've been writing some very simple and straight forward upstart configuration files. The problems began when I tried to start my service using one of them.

Undescriptive error messages

I've experienced two problems I didn't find anything on the internet about:
  • Errors in the service standard error output: : not foundfd/9: 3: /proc/self/fd/9:
  • Errors in /var/log/upstart/{service-name}/logSyntax error: Bad fd number upstart
What happened to be the problem wasn't the actual configuration files, but their formatting. I've been preparing the .conf files on Windows and have uploaded them on some Linux machines. What I haven't thought of was these hidden symbols, which are not visible by default - the line endings. 

Line endings

Windows uses '\r\n' or CRLF at the end of each line and Linux uses only '\n' or LF (Newline explained in Wikipedia). So,  my configuraton files were all with CRLF at the end of each line, which wasn't accepted by the Linux and Upstart respectively. Upstart failed to start my services and didn't give any descriptive errors. Changing CRLF to LF in the .conf file fixed these issues.

TIP: You can use vim -b filename to open a file name in binary mode, which shows all special characters in the file.

I hope this saves some hours someone out there.

Friday, January 24, 2014

Windows Powershell - Extract Json property values

Hi guys,

I've had to extract json property values, from a CSV document. Sounds bizarre, right? We've got the CSV file exported from a database, where a JSON was stored in one of the columns. As the JSON is not any close to native to relational database, we couldn't query the JSON column to extract data from it.

The problem

Can be restated as "How can you extract JSON property values from any text file" or even generalized "How to extract anything from a large file". Our requirement would be 'do this fast and easy in Windows environment and be able to process any text file'.

Sample data

We'll be using this short and simple json file for our example:


client.js
[
    {
        "firstName": "A",
        "clientId": 2
    },
    {
        "firstName": "B",
        "clientId": 14
    },
    {
        "firstName": "C",
        "clientId": 15
    },
    {
        "firstName": "D",
        "clientId": 3
    }
]

Decompose

Let's decompose the problem into few simple steps:


  • Searching through text is a complex operation. The most common approach would be to use Regular Expressions as they provide flexibility and support in practically any programming language.
    • The json language complies to several simple rules, so extracting from it would be easy. A regex for extracting the client id is: '"clientId": (?(\d+))'. It matches the "clientId" property name, then a colon :, then a new  named group starts, which expects a number (\d+).
  • Instant coding and execution leads us to some scripting language. The scripting language does not need compilation, creating new projects or anything alike which could slow us down.
    • We'll be using Powershell to execute the regular expression, as it's a common language for executing such activities on Windows.

Script

# set our client id regex, which can extract client id fields from the text
$clientIdRegex = '"clientId": (?(\d+))'

# search through the file with "select-string", providing our regex as a pattern and find all matches
# pipe the matches to a foreach, which traverses them and then pipe each match to a foreach which extracts
# the group clientid and get's its value.
select-string -Path .\clients.js -Pattern $clientIdRegex -AllMatches | ForEach-Object {$_.Matches } | ForEach-Object { $_.groups["clientid"].Value }

And that's the whole script - just two lines!

# If we need to output the values in a file, we need just to pipe the output into a file like this: | ForEach-Object { $_.groups["clientid"].Value } > output.txt

Note: In most powershell scripts, you would see the usage of the alias "%" instead of ForEach-Object. Here it's used to illustrate the idea.

In conclusion

Knowing script languages is powerful tool in our utility belt. They can facitilate actions which should be done only once and there's no need for a maintainable and robust solution. Plus, they are easily edited and executed.