Dieses Blog durchsuchen

Sonntag, 31. Juli 2016

typescript: create first typesave javascript functions, interfaces and classes

If you want to program typesafe javascript,  you can use microsofts "typescript". Its a so called "superset ontop of javascript" to extend it for serveral things like:

- interfaces
- abstract classes
and types

Typescript can do that for you. Sounds nice, but in real life there are some problems,

You cant use typescript in the browser, because most of the browser doesnt support it. So you need to compile typescript into plain javascript, wich then can be included or required like any other script.

So you need a compiler. You can use node.js and his packagemanager to install typescript and its compiler. Further you can use gulp or broccoli to compile the ts to javascript.

We want to use node.js on ubuntu. Windows and Mac users installations are similiar to that.

1) install node.js
apt-get install nodejs

ln -s /usr/bin/nodejs /usr/bin/node


2) install npm
apt-get install npm

3) install typescript globaly on your machine
npm install -g typescript


I suggest to use an IDE with typescript support.
In my case I have used Microsofts VS Code. Its platformindependend and has a lot of plugins.


To install it on linux you can use my last post:
magento2-tuts.blogspot.de/2016/07/vs-code-microsoft-editor-on-ubuntu-1604.html

In the plugin manager of vscode type "typescript" in the searchfield and install at least one of the plugins.

Lets start coding:
Create a file named "myFirstTypeSafeFunction.ts" and write following ts code

As you can see we have created a function named myFirstTyoeSafeFunction() with a parameter person from type string.

Thats great, because in javascript this typehinting from type string would cause an error.

At next we have to compile the .ts file into a .js file.

Switch to your terminal in the folder where you have saved your .ts file and type:
tsc myFirstTypeSafeFunction.ts

After that a file myFirstTypeSafeFunction.js was generated with the javascript code to the .ts code.


Lets create an Interface in typescript. 

 
this is really cool. So now you are able to write some kind of better oop code in javascript by using interfaces.


At next we want to use the interface in a class construct.

Lets setup a class implementing an interface in javascript.
Thats awsome, isnt it. As you can see, you can simply pass an object from type IHuman to a constructor of a class, like in PHP , Java, C# or other Type based language. If you want to see, what Microsoft is making of yout typescript, you can open the corresponding .js files an have a look in the generated code, At the end typescript will help you writing better javascript code.

Samstag, 30. Juli 2016

Angular 2: create first project

Here is what I have done to create my first projectskelleton on ubuntu 16.04:

1) Install node.js
apt-get install nodejs

2) create a symlink to make node available on console.
ln -s /usr/bin/nodejs /usr/bin/node

3) install npm
sudo apt-get install npm


4) install typescript
sudo npm install -g typescript


5) install angular-cli
sudo npm install -g angular-cli
 
6) Create new App
cd into your directory
sudo ng new first-app

cd into your first-app dir
sudo npm install


7) install typings
npm install typings --global 
npm run postinstall

Run server
sudo ng serve

browse localhost:
http://localhost:4200/





linux: /usr/bin/env: »node“: Datei oder Verzeichnis nicht gefunden

To fix that un linux , just hit follwing commandline:

sudo ln -s /usr/bin/nodejs /usr/bin/node


VS Code Microsoft Editor on Ubuntu 16.04

Today I want to give VS Code Editor (Visual Studio Code Editor) a try to start a Angular2 Corse. This editor has a huge build in plugin support for thounsands of applications.

To install it on Ubuntu:

1) Download 
https://code.visualstudio.com/Docs/?dv=linux64_deb

2) install it as normal user
sudo dpkg -i <file>.deb
 
3) Run
code
 
 
thats it.
 
 
 

Sonntag, 24. Juli 2016

Install PyCharm Python IDE on ubuntu 14/15

 
 
add following repository 
 
sudo add-apt-repository ppa:mystic-mirage/pycharm
 
 
Update your system
 
sudo apt-get update 
 
 
Install cummunity version of pycharm 
sudo apt-get install pycharm-community 

Samstag, 23. Juli 2016

Mein Tag in München zum Amoklauf. Wacht auf. Wir müssen unsere Gesellschaft umbauen!


Der Gewaltexzess in München und wie das SEK den Bahnhof stürmte


Wie ich es erlebt habe.

Da es der bisher seltsamste und aufregenste Tag in meinem bisherigen Berufsleben war, möchte ich ihn heute mit Euch teilen.

Das war eigentlich der perfekte Tag, auf den ich mich lange vorbereitet hatte und dessen Ende ich einfach nur feiern wollte. Sichtlich glücklich trat ich nach meinem beruflichen Erfolg den Weg nach Hause (Frankfurt Main) an. "Noch ne Stunde Zeit, bis der Zug fährt. ich brauch jetzt ein Bier". Ich setze mich an einen Tisch draussen vor dem "Losteria" direkt am Hauptbahnhof und trank mein Bier. Plötzlich fuhr ständig Polizei mit Blaulicht vorbei, was ich jedoch nicht weiter beachtete. Erst der Kellner wies mich darauf hin, dass es eine Schiesserei mit angeblich 15 Toten gab. Ich war in dem Moment völlig unfähig zu realisieren, was los ist. Ich dachte nur an meinen neuen Job und den Umzug.



Ein paar Minuten später begann es zu regnen und ich musste mich reinsetzen.
Ich setzte mich an einen kleinen runden Holztisch am Eingang des Restaurantes


Das ist der Tisch, an dem ich sass, nach dem ich wegen des Regens rein bin.

An diesem Ferneher über der Kasse verfolgte ich das Geschehen. Man sieht den Reporter vor Ort und das Infolaufband.


Die Situation war absolut surreal. Um mich herum aßen und tranken die Leute und ich trank in Seelenruhe mein Wasser und ertappte mich bei Gedanken wie
"In 20 Minuten geht mein Zug, ich bin eh gleich hier weg" und "Och das Olympiazentrum ist weit weg, dass betrifft mich nicht".

Die Leute um mich herum tranken und aßen,  waren aber sichtlich beunruhigt und tauschten nervöse Blicke aus.

Bis es geschah. Aus dem Nichts rannten Leute ins Restaurant und schriehen wie am Spiess "Raus hier, alle Raus".  Unverzüglich brach Panik aus. Die Leute standen auf und rannten los. Völlig unkontrolliert. Teller flogen von den Tischen, Stühle und Tische fielen um. Die Menschen in dem Lokal stürmten in Richtung Bahnhofsinnenhof, was in dieser Situation nicht hätte dümmer sein können, da der Müncher Bahnhof einem Labyrint gleicht. In Panik läuft bekannlichermaßen alles schief.

Da ich an dem runden Tisch direkt am Eingang saß, wurde ich von den flüchtenden Menschen mitgerissen. Irgendwie schaffte ich es meine Laptoptasche und meine Umhängetasche zu greifen und mit der Richtung der flüchtenden Menschen zu fliehen. Mein Handy musste ich liegen lassen.

Die Masse schob sich in Richtung Schliessfächer im Bahnhofsinneren. Einige versuchten sich darin zu verstecken. Das war jedoch eine schlechte Idee. Aus dem Irrgarten gabs keinen Ausweg wenn Attentäter hierher fänden.

Ständig gingen mir die Horrormeldungen aus Culombine und Ütoya durch den Kopf,  in denen Menschen in Fallen wie dieser erschossen wurden, weil sie nicht rauskamen.

Leute, die sich da verstecken wollten sprachen arabisch. Ich konnte Ihnen nicht sagen, dass es da keinen Ausweg gab.


Foto wurde am nächsten Tag aufgenommen

Am Ende des Schliessfachganges war der Ausgang zum Innenbereich der Einkaufsgänge im Bahnhofsinneren. Ich bewegte mich vollbepackt mit Laptopbag und Reisetasche in Richtung Bahnhofinnenhof.
Am Ausgang angekommen hörte ich laute männliche Schreie "Alles raus, sofort raus". Dann sah ich 2 Polizisten, den Gang herunterkommen mit dem Schnellfeuergewehr im Anschlag. Beide auf einer Höhe den engen Gang fixierend mit der Waffe von links nach rechts schweckend.

Es war also die Polizei, die den Bahnhof stürmte.

In Richtung Ausgang zu gehen traute ich mich nicht, da ich vermutete die Angreifer würden von da reinkommen. Also suchte ich Schutz, in dem ich in die Gänge nach Rechts abbog.




In einem  verlassenen Schnell-Restaurant, in dem noch der Fernseher und die Kafeemaschine lief, fand ich einen hohen Tresen, hinter dem ich Schutz vermutete und versteckte mich einige Minuten dort.
Tresen, hinter dem ich mich versteckt habe.


Nach einer Weile, als es scheinbar etwas ruhiger wurde, stand ich hinter dem Tresen auf und sah weitere Polizisten mit Sturmgewehr an dem Schnellrestaurant vorbeigehen. Ich fühlte mich sichererer und ging aus dem Schnellrestaurant. Am Ausgang bewegte ich mich im Rücken der Polizisten.

Einer der Polizisten bemerkte mich und drehte sich blitzschnell um und richtete sein Sturmgewehr auf mich. Jetz wurde mir klar wie Ernst so eine Situation werden kann.

Ich ging zurück zu dem Lokal wo ich war. Und tatsächlich  fand ich mein Handy auf dem Tisch an dem ich sass.

Ich nahm es und ging zügig zum Ausgang und raus aus dem Bahnhof. Draussen kamen gerade ca 5 Sixpacks vom SEK an und ca 10 schwer bewaffnete voll vermummte SEK- Polizisten  formierten sich. Vor dem Bahnhof wimmelte es vor Schaulustigen. Als Erstes räumte das SEK den Bahnhofsvorplatz, dann stürmten Sie den Bahnhof.


Als ich erfuhr, dass an diesem Abend nun kein Zug mehr nach Hause fuhr beschloss ich im Eden Hotel, gegenbüber vom Hauptbahnhof, einzuchecken und die Nacht im sicheren 5ten Stock zu verbringen und ersteinmal Informationen über den Hergang zu sammeln.
Ich bin bei der Suche nach Infos auf das Video der ARD gestossen, die den vermutlichen Attentäter, den man später erschossen unweit des Tatortes auffand,  auf dem Dach des Olympiazentrums im Streit mit einem Münchner Anwohner eines benachbarten Wohnhauses zeigt.



Einen islamistisch,  geplanten Anschlag schliesse ich aus, genauso wie ich ausschliesse, dass es sich um mehrere Täter handelte.
Die Vollsperrung Münchens und das Zusammenziehen aller bayrischen Polizeikrafte war ein Standard Schutzmechanismus, um einen Flächenbrand zu vermeiden.

Erst werden die öffentlichen Plätze geräumt, die Verkehrszentren kontrolliert und abgeriegelt und dann die Massen aufgelöst.

Das klappte sehr gut und wir können trotz der 8 Toten, die auch durch die Polizei niemals zu verthindern gewesen wäre, stolz auf unsere Polizei sein. Sie haben die Situation trotz der langen chaotischen Lagen in den Griff bekommen und am Abend die Sicherheit mit starker Präsenz bis in die Morgenstunden wiederhergestellt.

Ich spreche Ihnen hiermit meine Besondere Achtung aus.


Das Alles zeigt jedoch, wie wichtig es ist, dass wit ENDLICH eine Gesellschaft schaffen müssen, die in der Lage ist, die Problem, die aus der laufenden Globalisierung, den andauernden Kriegen die die  Flüchtlingstöme und Migrationsbewegungen verursachen langfristig in den Griff bekommen müssen und allen Menschen eine Basis geben müssen, in denen niemand isoliert und in Gettos abgeschoben werden kann. Wir müssen den Menschen eine Chance geben, sich zu entwickeln und nicht in Irrenhäsern mit Psychopharmaka vollzustopfen, weil sie "verhaltensauffällig" sind.

Das alles ist ein Zeichen fehlgeschlagener gesellschaftllicher Integration. Auch wenn dieses Wort schon sehr abgenutzt wird.

Wenn wir es nicht schaffen, die Gesellschaft schnell und effizient durchlässig und flexibel zu machen und unser Bildungssystem und den Arbeitsmarkt rasch an die sich schnell ändernden Verhältnisse anzupassen und ein reaktionsschnellers Asylrecht auf die Beine zu stellen, werden wir uns , wie es mein lieber Bruder Sascha sagt "An die Bilder in Zukunft gewöhnen müssen".

Die Politik und die Menschen müssen alles tun, um diesen verhärenden Problemen etwas entgegensetzen zu können.
 
Wir müssen Zustände wie in Frankreich verhindern und unsere Gesellschaft nicht zu einem Einlaufbecken zukünftiger Gettos machen, die uns um die Ohren fliegen. Wir brauchen ein Asylrecht, das die Menschen in Arbeit bringt und bei Nichteignung rasch abschiebt. Wir brauchen einen Arbeitsmarkt, der das leisten kann. Wir brauchen Geld für Integration, Bildung und kulturellen Ausstausch, keine Sklavengetthos von Migranten und Kriegsopfer und abgegrenzte Subkulturen als Herd genau solcher Amokläufe und Gewaltexzessen.

Die Migranten und Ihre Kinder brauchen Chancen, keine Vorurteile.
Erst wenn wir dieses Problem gelöst haben, sind wir nicht mehr anfällig für die Wahnvorstellungen religiöser Irrer wie Erdiógan und dem IS. Und unsere Integrationen sind stabil und die Menschen wissen was sie an unserem Land und Ihren Menschen so schätzen.

Gebt den Menschen eine Bedeutung, sodass sie sich keine Bedeutung mehr im Radikalismus suchen müssen. Das ist alles was solche Situationen wie am 22.ten Juli in München verhindern kann!

Geht auf einander zu und lernt Euch schätzen, statt Euch geringzuschätzen und auszugrenzen.


Ich möchte mein Beileid den trauernden Angehörigen der Opfer ausdrücken.

Bye












Sonntag, 17. Juli 2016

symfony 3: create a unittest for an api controller

In one of my last post
http://magento2-tuts.blogspot.de/2016/07/symfony3-create-restful-api-controller.html , we have created a restful api controller.

Now we want to write a unittest to test this controller.


install phpunit:
apt-get install phpunit

configure phpunit.xml
-in your projectroot there is a file phpunit.xml.dist Rename it to phpunit.xml
- open the file and add your BundleDirectory to the directory object

In my case i had to add the src/Check/BlogBundle/Test/ directory

Now we can add a controllerTest.

Lets say, we want to test, that the service throws 500 if we try to POST an empty user to the database:  

Run your test:
open your terminal in your projectroot and type: phpunit -c phpunit.xml

Thats all your testresults are found in the console.

symfony 3: use custom repositories instead of entities

Its allways a good idea, not to use entitiyobject like $user= new User();

Symfony allows to implement the repositorypattern. Its well documented and a good way, to extend the entities without to couple the entityclass and the manager

In the next example I want to show you not only to implement the repository. I have implemented an AbstractRepository and a repositoryInterface too to setup an extendable abstract repositorymechanismto


1) first thing to do is creating a folder "Entities" in your Bundle
2) Save a File called "UserRepository.php"
3) Save a FIle EntityRepositoryAbstract.php
4) Save a File IEntityRepository.php

My abstract repository implements 2 methods to make saving objects easier, when requests come from an api controller

At next we implement the interface:

At next we implement a UserRepository. This Class is empty for now. Because the current save implementation can be used abstract
To make this work, we have to tell the entity, that it has to use our new repositories. This can be done by setting the right annotations.
Here is my entityclas. As you can see we have extended the Anntotation ORM\ENTITY with the link to our new repository
* @ORM\Entity(repositoryClass="Check\BlogBundle\Repositories\UserRepository")

At next you have to delete all genereated .orm files under src//Resoucres/config/doctrine and clear your appcache,otherwise it want work.
At last we can use our new UserRepository like that in a controller. This apicontroller takes a request and saves the body as a new user directly via calling a save() method in our new repository

Samstag, 16. Juli 2016

symfony3: create a restful api controller

We want to implement a basic api controller and a client to test it.

create a controller in your bundle.
Save it to AppBundle/controllers/Api/UserController.php
edit you routing under app/config/routing.yml and add the app_api part

At that point the api controller is available unter "localhost:8000/api/user"

But we wan to write a short testfile, to test our api with gusszle.

add guzzle to your composer composer 
cmd->require eightpoints/guzzle-bundle

This loads guzzle.

Create a file named test.php in your project root
open a terminal an hit the file:
php test.php

You will get your controller response directly.

symfony3 : add password confirmation field to a password field

in most of the cases its a good idea to let the user confirm is password to prevent uneeded password support.

symfony2 has an own PasswordType in his formpackage.

Include the needed namespaces:
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;

add the PassWordType to your form


symfony 3) formating an emailfield

If you want to format your email textfield you can simply add the EmailType to the formbuilder. in your FormType

Just include the namespace before usage: 
use Symfony\Component\Form\Extension\Core\Type\EmailType;



If you want some more configuration you can user the manual:
http://symfony.com/doc/current/reference/forms/types/email.html

All FieldType are found here:
http://symfony.com/doc/current/reference/forms/types.html

symfony 3 manyToOne Relation / foreignkeys in doctrine2

If you have multiple table related to one table, lets say via a userid you can tell symfony to do the job for you by generating enties for you.

You can also do this by yourself by editing the entities.
this is the database with all the many2one relations 


At next we generate our entityclasses Posts, Replies and User
Have a look on the annotations of the userid in the related classes replies and post. In both cases the userid is tagged like that:
This annotation tells doctrine to relate the userid to the column "id" in the usertable



mysql: add / editing a foreign key after database was created

This task is simple but offten needed.

If you have created a databasetable and you forgot the foreignkeys, you can simply add it later via altering table.

Add a foreignkey


This key references the userid from users to a tupel in table posts. If a user gets deleted or updated the post will be deleted to0.

Deleting a foreign key

asdasd

Sonntag, 10. Juli 2016

Symfony 3.1 Add a encrypted passwordfield to your entity, controller and Form

If you have a passwordfield in your database you have to encrypt the passwordbefpre you can save it.

this task is pretty straight forward in symfony 3.1

Once you have created your entity (f. i BlogBundle\Entity\Users)
You have to implement the core security user  interface  to make the entity compatible to the encoder class. See my class to understand the mechanism:


Implement interfacemethods
You have to implement the last 2 methods (see class above) to fullfill the contract.

Modify security:
open app/config/security and add encoder like this:

clear cache after that

Add encoder to your user-controller


Add password and password confirmation field to your crud form

thats it

Install symphon2 on linux, create a project with database, crudforms and twittter bootstrap

 Today we want to create a simple blogapplication with symfony (3.1)

LEVEL: PHP Advanced / Symfony2 Novice

This blog will have 3 features
- Users (add, delete, edit, login)
- Posts (add, delete, edit)
- Replies (add, delete, edit)


You need to have PHP 5 or 7 and Mysql Server running


Install Symfony
$ sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony
$ sudo chmod a+x /usr/bin/local/symfony


Create App 
php bin/console new blog 3.1

Create Bundle
php bin/console generate:bundle
- call it BlogBundle


Edit databaseconfiguration
open parameters.yml in config folder and edit databaseaccess

Create a database
php bin/console doctrine:database create
- call it blog

open a mysql client (fy mysql-workbench)

create needed tables

CREATE TABLE `replies` (
  `id` int(11) NOT NULL,
  `userid` int(11) DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `content` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `firstname` varchar(255) DEFAULT NULL,
  `lastame` varchar(255) DEFAULT NULL,
  `username` varchar(50) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `isDeleted` tinyint(4) DEFAULT NULL,  `isActive` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `blog`.`posts` (
  `id` INT NOT NULL COMMENT '',
  `userid` INT NULL COMMENT '',
  `title` VARCHAR(255) NULL COMMENT '',
  `content` TEXT NULL COMMENT '',
  `isDeleted` TINYINT NULL COMMENT '',  `isActive` TINYINT NULL COMMENT '',
  PRIMARY KEY (`id`)  COMMENT '');

create entities from database:
php bin/console doctrine:mapping:import --force BlogBundle xml
php bin/console doctrine:mapping:convert annotation ./src
php bin/console doctrine:generate:entities BlogBundle 
 
 
Install twitter boodstrap crud bundle 
composer require triton/crud-generator
Add it to the AppKernel.php class:
new Lexik\Bundle\FormFilterBundle\LexikFormFilterBundle(), new Triton\Bundle\CrudBundle\TritonCrudBundle(), 
 
Optionally for the bootstrap theme, add this to your app/config/config.yml
twig:
    form_themes:
    - 'bootstrap_3_layout.html.twig' 

 
generate crud controllers with twitter bootstrap look and feel 
php bin/console triton:generate:crud
 
 
  














Samstag, 2. Juli 2016

Install magento via commandline on a linux machine

1) Install composer on your machine


at the moment you have to have installed php 7.0.2 minumum
if you do not have a lamp stack installed, follow this very good guide
https://www.howtoforge.com/tutorial/install-apache-with-php-and-mysql-on-ubuntu-16-04-lamp/

add a mysql user with needed rights
GRANT ALL on *.* to 'peter'@'localhost' identified by 'yoursecretpassword';


install needed php extensions
apt-get install php7.0-gd php7.0-xml php7.0-mcrypt php7.0-curl php7.0-intl php7.0-mbstring php7.0-zip php7.0-mysql

 
get composer
follow https://getcomposer.org/download/

Create project with composer
2)composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition /var/www/html/magento2

this downloads and installs magento2 under /var/www/magento2

Username / Password repo.magnto.com
during the installation your are ask for username and password to repo.magento.org

You have to create an account on https://marketplace.magento.com and create access keys.
After you have created private and public key, you have to use the public key as username and the privatekey as the password


make cli executable
cd /var/www/magento2 && chmod +x bin/magento

Database
create a database named magento2

navigate to installdir
cd /var/www/magento2

set accessrights (all for the first time)
chmod -R 777 *

execute installcommand
bin/magento setup:install --base-url=http://magento2.localhost/pub/ --language=en_US --backend-frontname=admin --db-host=localhost --db-name=magento2 --db-user=root --db-password=DBPASSWORD --admin-email=max@mustermann.de --admin-user=youradmin --admin-password=PASSWORD --admin-firstname=Max --admin-lastname=Mustermann

add sampledata and activate additional modules
bin/magento sampledata:deploy 
bin/magento setup:upgrade

you will be asked for username and password again. user your pubkey as username and private key as password 

enable devoloper-mode to see all php problems and get more information during runtime
bin/magento deploy:mode:set developer

deploy static content, otherwise styles are missing
bin/magento setup:static-content:deploy 


add domain to your /etc/hosts
nano etc/hosts
127.0.0.1 magento2-shop.local 

add apache-vhost entry to your installation
keep sure, you link into the pubditectory, otherwise the css files arent found






this article is based on:
http://alanstorm.com/magento-2-frontend-files-serving

and 

https://www.integer-net.de/magento-2-installation/