Tuesday, December 8, 2020

Angular 10

 Angular 10

https://www.youtube.com/watch?v=9CVZks6U0ZY&list=PL8p2I9GklV45JZerGMvw5JVxPSxCg8VPv



http://osol-tutorials.blogspot.com/2020/12/10-httpswww.html


https://www.youtube.com/watch?v=9CVZks6U0ZY&list=PL8p2I9GklV45JZerGMvw5JVxPSxCg8VPv


install commandline for angular


npm install -g @angular/cli


OR


npm install --global @angular/cli@next


Create new project

===================


ng new angularProjectName


cd angularProjectName


Initiate server associated with Angular

========================================


ng serve


Site will be available at

http://localhost:4200  (after a few compilation steps)



TO CREATE PRODUCTION VERSION

=============================

ng build


will create files in 

dist/projectName folder


use with --prod argument for final version

ng build --prod



make sure to change <base href= appropriately


POINTS TO PONDER

=================


https://www.youtube.com/watch?v=q4fBJtnbqk8&list=PL8p2I9GklV45JZerGMvw5JVxPSxCg8VPv&index=3



1.package.json (scripts like ng serve, ng build,ng lint etc . dependencies, dev dependencies)

2.node_modules folder

3.src folder (development files to be saved here)

4.environments folder(development/test/production configuations file are save here, environment.prod.ts, environment.ts)

5.assets folder (fonts, images etc)

6.index.html

7.main.js

8.style.css

9.app folder (app.module.ts, app.component.ts,app-routing.module.ts). influences content of <app-root></app-root> tag via app.component.html

10. modules (eg:user)

11. components: a module is made of multiple components( eg:user login,registration,)



FILES

=====

1. editorconfig ( for editors like vscode/adom/sublime)

2. karma.config (Karma is a testing automation tool(like phpunit?) created by the Angular JS team at Google. The first step for using Karma is to install Karma. Karma is installed via npm (which is a package manager used for easy installation of modules on a local machine).)

3. package.lock.json

4. tslint

5. typescript files

6. e2e folder (end to end configuration)



INTERPOLATION

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

https://www.youtube.com/watch?v=2-cekKLSpsk&list=PL8p2I9GklV45JZerGMvw5JVxPSxCg8VPv&index=5


variables are set in src/app/app.component.ts

 inside export class AppComponent{varName ='val';}

 used in app.component.html as {{varName}} in index.html

 

 

 

 ABOUT COMPONENT

 ================

 1. 4 files

default component is 'app', which is saved in src/app folder

app.component.html

app.component.ts

app.component.spec.ts (unit test cases)

app.component.css

there are 2 other files in default installation, which is not part of component

app.routing.module.ts

app.module.ts

 2. Edit component

in app.component.ts

@Component({

selector:"app-root", // <app-root></app-root> will show content of this component

templateUrl:'app.component.html',

styleUrls:['app.component.css'],

})

 3. make new component

 

command line

ng g c componnentName

g for generate

c gor component

MODULES:

============


Groups components, directives pipes and services that are related

**pipes: helps to get data from services, modify it etc


PS: Module and Model are different



files of module in default module 'app'

app.routing.module.ts

app.module.ts

@NgModule({

declarations:[

AppComponent // all components which is part of this module

],

imports:[ // list of other modules to be used

BrowserModule,

AppRountingModule

],

providers:[],

bootstrap:[AppComponent] // what component is to be automatically loaded 

})

export class AppModule{

}

CREATING NEW MODULES

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

 ng g m newModuleName

 

will create a folder newModuleName inside src/app  and a file src/app/newModuleName/newModuleName.module.ts

content of newmodulename.module.ts is

@NgModule({

  declarations: [],

  imports: [

CommonModule

  ]

})

export class UserModule { }

CREATE COMPONENT FOR THE Module

ng g c user/login

declartion in user.module.ts  changes to 

declarations: [LoginComponent],

add the followin inside @NgModule

,

  exports:[

LoginComponent

  ]

  

  

  to use the components of this module,

add in app.module.ts

import {UserModule} from ./user/user.module

and 

UserModule in 'imports' (of app.module.ts) 

MATERIALIZE CSS WITH ANGULAR

https://stackoverflow.com/questions/48007665/how-to-use-materialize-css-with-angular



FUNCTION

=========


button should be defined in component html

and function should be defined in ts file


define function in component class as 


getName(): void{

    console.log("hello Sreekanth");

  }

  

  call on button click as 

  

  <button (click)="getName()">Get My Name</button>

  

  with parameter

  <button (click)="getName('toney',testVarDefinedInComponentClass)">Get My Name</button>

  

  

  EVENTS

  =======

  

  <input #id2getThisTextBox type="text" (keyup)="eventTest(id2getThisTextBox.value)" />

  

  for specific buttons use keyp.enter/keyup.space etc

  <input #id2getThisTextBox type="text" (keyup.enter)="eventTest(id2getThisTextBox.value)"  (keyup.space)="eventTest('onspace')" />

  

  GETTING INPUT BOX VALUE AND REFLECTING IT IN PAGE

  ==================================================

  step 1

  =======

  in component html

  <input type="text" (keyup)="eventTest($event.target.value)" />

  

  step  2

  ========

  define in component ts

  currentVal ="";

  

  and in eventTest function

  this.currentVal = arguments[0];

  

  step 3

  =======

  in component html(again)

  {{currentVal}}

  

  in component html

  

  

  

  PROPERTY BINDING (to an html element, & difference between binding and interpolation)

  =================

  https://www.youtube.com/watch?v=_uY-FOPem0E&list=PL8p2I9GklV45JZerGMvw5JVxPSxCg8VPv&index=11

  

  interpolation sample

  {{currentVal}} 

  binding sample

<input type="text" [value]="currentVal" />



CONDIDITIONS

===============

ng-template [ngIf]="currentVal !='red'"


SWITCH CASE

==============

  

  

Typescript

TYPE SCRIPT
-----------
http://osol-tutorials.blogspot.com/2020/12/typescript.html

https://www.youtube.com/watch?v=2pZmKW9-I_k&list=PL4cUxeGkcC9gUgr39Q_yD6v-bSyMwKPUI

https://www.youtube.com/watch?v=2pZmKW9-I_k

https://github.com/iamshaunjp/typescript-tutorial

npm install -g typescript

C:\Users\user\AppData\Roaming\npm\tsserver -> C:\Users\user\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\user\AppData\Roaming\npm\tsc -> C:\Users\user\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ typescript@4.1.2
added 1 package from 1 contributor in 34.334s


Compile .ts to js
tsc  tsFileName.ts jsFileName.js 

if .ts file is to be compiled to js file of same name , no need to explicitly state js file name

WATCH PARAMAETER
tsc  tsFileName.ts -w

tsc will watch for saving changes  in tsFileName.js and automatically compile to js

explicit types 

eg:
let strTyoeVar:string;

array

let strArrayVar:string[];

Object
let objVar:object;

Specific Type
let specificTypeObjVar:{
name:streing,
age:number
}



union types (mixed)

let mixedVar:(string|number);
let mixedArrayVar:(string|number)[] = [] ;




DYNAMIC TYPE
let dynamicTypeVar:any;
let dynamicTypeArrayVar:any[];
let dynamicTypeObjVar:{name:any,age:any};


Differentiating source TS and JS in seperate files

save .js in src/ts folder and js in public/js folder


first call

tsc --init

will create tscconfig.json
then edit 
tscconfig.json

outDir:"./public/js",
rootDir:"./src/ts",

refer https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

so that

 in src/ts folder will compile js to public/js folder
 
 by simply calling
 
 tsc

Wednesday, November 25, 2020

Laravel

https://osol-tutorials.blogspot.com/2020/11/laravel.html

URL:

http://localhost/pjt/laravel/php7/example/server.php

or

http://localhost/pjt/laravel/php7/example/public


path: D:\projects\laravel\php7_with5.4\example


http://sreelp/pjt/MyContributions/osolcontributions/quickfileexlorer/


Good tutorial at :https://www.webtrickshome.com/category/laravel

check info about various paths there


for laravel 7 

https://laravel.com/docs/7.x/installation

https://www.webhostface.com/kb/knowledgebase/install-laravel-windows/


COMPOSER COMMANDLINE ARGUMENTS:https://getcomposer.org/doc/03-cli.md


        composer create-project --prefer-dist laravel/laravel example


             --ignore-platform-reqs

             if only old version is installed

        php key:generate      (do it if it is not run as last step in laravel installation)

            

            

            php artisan key:generate

            Application key [base64:ATRDLHorCFpqaLr83arYBau718w6zXv/m0UU1e1Jwno=] set successfully.

            (REF: https://laravel.com/docs/4.2)


        Get Version:

            cd /D D:\projects\laravel\php7\example

            php artisan --version

                    Laravel Framework 5.4.36


    When using multiple versions of php , care full , check before you install

       ECHO %PATH%

            C:\wamp64\bin\php\php5.6.31;


       or php -v

            PHP 7.4.9 (cli) (built: Aug  4 2020 11:52:41) ( ZTS Visual C++ 2017 x64 )


            This PC >>right click -> properties >> Advanced system settings >> Environment variables


            Under "system variables" select "path" click edit

                change

                    C:\wamp64\bin\php\php5.6.31

                    TO

                    C:\wamp64_4_php7\bin\php\php7.4.9



            after that if you install

                Installing laravel/laravel (v8.4.3)



front end

        edit APP_URL=http://localhost in .env

        files are in public folder

        server.php in root folder may used as starting point

        copy .htaccess in pubic_html folder to root folder 




        create folder named "frontend" in public folder, create css, js, images in it

            save index.html in  resources/views  as frontend/index.blade.php

            in routes/web.php      change return view('welcome');      to 'frontend.index'


            change href, src and action to {{url('public_html/frontend/,,,')}} eg:<a href="{{ url('/login') }}">


            in forms , add 2 hidden input fields 

                1. _token value="{{csrf_token()}}     (cross site request forgery)

                2. tbl value= "{{encrypt('tbl_name')}}


                these fields are checked in controller c



backend

        edit .env and set the following appropriately after creating a database

        DB_DATABASE=homestead

        DB_USERNAME=homestead

        DB_PASSWORD=secret


        in command line


                Model

                    php artisan make:model table_name


                        creates  2 classes 

                                class in app/Providers/table_name.php, set table name and primary key in it

                                class in database\migrations folder check sample 2014_10_12_000000_create_users_table.php

                            add table create commands in 'up' method


                        run in command line

                    php artisan migrate

                            will create table in database as we set in 'up' method supra


                Controller

                    php artisan make:controller crudController.php

                        creates crudController.php in app/Http/Controllers/Auth folder


                    copy index.php to resources/views as backend/index.blade.php

                        change href, src and action supra, in forms add 2 hidden field supra

                        

                            REF:https://www.webtrickshome.com/laravel/laravel-blades

                        start with 

                        @extends('backend.app') 


                        @section('content')

                            html contents here

                        @end

                     in routes/web.php  add


                        Route::get('adminpanel', function () {

                            return view('backend.index');

                        });


                        or if controller is to be used

                        Route::get('addpost', 'ControllerName@editpost');

                        or

                        Route::post('editpost/{id}', 'ControllerName@editpost');


                        with a corresponding method in the controller

                            public function editpost($id)

                            {

                                $data = DB::table('tbl_posts')->where('pid',"=",$id)->first();

                                $cats = DB::table('tbl_cats')->get();

                                return view('backend.index',array("data" =>$data,"cats"=>$cats)); 

                            } 

                            

                            in that


                            in view file access data as

                            @foreach($cats as $cat)

                             <option  value="{{$cat->field_name}}"

                            @endforeach



                    for trimming

                        {!! str_limit($data->details,50) !!}

                    for pagination 

                        $cats = DB::table('tbl_cats')->get()->paginate(10);


                        access pagination links as

                            {{$cats->links()}}

                    for date 

                        {{date('D,m-d-Y')}}



                    

            CSS Framework

                Laravel also comes pre-configured for Bootstrap 3 and 4 - Which you can opt-out of course. 

                But you will need to redesign some defined layouts, such as the Pagination for example, 

                which comes with classes for Bootstrap.                    


                To do that you can do:


                php artisan vendor:publish --tag=laravel-pagination


                This command will create all the views for the pagination in your views folder.


                You can also see this and more about the pagination if you visit: https://laravel.com/docs/5.6/pagination 




         Misc

            https://www.webtrickshome.com/laravel/laravel-functioning


            https://dev.to/kingsconsult/laravel-8-auth-registration-and-login-32jl

            better one

            https://therichpost.com/laravel-8-login-registration-working-tutorial/

            composer require laravel/ui

                    ......

                    Package manifest generated successfully.

                    72 packages you are using are looking for funding.

                    Use the `composer fund` command to find out more!

            php artisan ui vue --auth

                Vue scaffolding installed successfully.

                Please run "npm install && npm run dev" to compile your fresh scaffolding.

                Authentication scaffolding generated successfully.


            npm install


            npm run dev


            php artisan serve



                    D:\projects\laravel\php7_with5.4\example>php artisan serve

                    Laravel development server started: <http://127.0.0.1:8000>

                    [Fri Nov 27 13:13:37 2020] PHP 7.4.9 Development Server (http://127.0.0.1:8000) started

                

                with diiferent port 

                php artisan serve --port=8082


                You can stop Laravel Development server anytime by pressing ctrl+c key from keyboard.


                check the working on browser



Errors

php artisan migrate


    In D:\projects\laravel\php7_with5.4\example\vendor\laravel\framework\src\Illuminate\Database\Connection.php

        Access denied for user 'homestead'@'localhost' (using password: YES) (SQL: select * from inf

        ormation_schema.tables where table_schema = homestead and table_name = migrations)




        

        In D:\projects\laravel\php7_with5.4\example\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php line 68:


            SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)


                   

            

   SOLUTION:         

            simplest possible step is to close command line window ,open another one and excute this


                   

            IF IT DOESNT WORK   

                check .env and set appropriately


                DB_CONNECTION=mysql

                DB_HOST=localhost

                DB_PORT=3306

                DB_DATABASE=laravel_auth_test

                DB_USERNAME=root

                DB_PASSWORD=''

                   

                    Well it uses config\database.php but it references env() which is explained here: http://laravel.com/docs/5.1/installation#environment-configuration


                    You need to run these two commands

                            

                            php artisan config:clear

                            php artisan cache:clear

                            php artisan config:cache

                            php artisan view:clear



same command 

another error

php artisan migrate

Migration table created successfully.

Migrating: 2014_10_12_000000_create_users_table


   Illuminate\Database\QueryException


  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))


  at D:\projects\laravel\php7\example\vendor\laravel\framework\src\Illuminate\Database\Connection.php:671

    667▕         // If an exception occurs when attempting to run a query, we'll format the error

    668▕         // message to include the bindings with SQL, which will make this exception a

    669▕         // lot more helpful to the developer instead of just the database's errors.

    670▕         catch (Exception $e) {

  ➜ 671▕             throw new QueryException(

    672▕                 $query, $this->prepareBindings($bindings), $e

    673▕             );

    674▕         }

    675▕


  1   D:\projects\laravel\php7\example\vendor\laravel\framework\src\Illuminate\Database\Connection.php:464

      PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes")


  2   D:\projects\laravel\php7\example\vendor\laravel\framework\src\Illuminate\Database\Connection.php:464

      PDOStatement::execute()




SOLUTION :     

         ADD BELOW CODE INSIDE YOUR APP/PROVIDERS/APPSERVICEPROVIDER.PHP FILE AND THIS CODE WILL RESOLVE YOUR ERROR WHICH WILL COME ON MIGRATE TIME:

         drop tables created also


         ...

            use Illuminate\Support\Facades\Schema;

            ...

            class AppServiceProvider extends ServiceProvider

            {

                

                ...

                public function boot()

                {

                    ...

                    Schema::defaultStringLength(191);

                }

            }



404 error for http://localhost/pjt/laravel/php7/example/public/login            


        add bellow line in .htaccess

    RewriteBase /pjt/laravel/php7/example/public/

Thursday, May 17, 2018

dreamweaver cc onload javascript error

dreamweaver cc onload javascript error

https://www.dmxzone.com/go/16740/clearing-dreamweaver-s-cache/
C:\Users\<username>\AppData\Roaming\Adobe\Dreamweaver CC 2018\<language>\Configuration
C:\Users\Dell\AppData\Roaming\Adobe\Dreamweaver CC 2018\en_US\Configuration

delete WinFileCache-XXXXXXXX.dat

to view hidden files
https://answers.microsoft.com/en-us/windows/forum/windows_10-files-winpc/how-to-access-appdata-folder/2194e37a-a36c-443d-8dc0-0b505f5bbb8e


Click on “View”.
Check the box “Hidden items”

Monday, April 30, 2018

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certif

https://stackoverflow.com/questions/26148701/file-get-contents-ssl-operation-failed-with-code-1-and-more

$arrContextOptions=array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
);  

$response = file_get_contents("https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json", false, stream_context_create($arrContextOptions));

echo $response;

Thursday, January 18, 2018

Wordpress Plugin Creation

Step1(make the plugin appear in admin panel

//developed based on https://code.tutsplus.com/tutorials/create-a-custom-wordpress-plugin-from-scratch--net-2668
a. create a plugin file
b.add the follwing code on top

<?php
    /*
    Plugin Name: Plugin name as to be displayed in admin panel
    Plugin URI: http://www.outsource-online.net
    Description: Plugin for (description as to be shown in admin panel )
    Author: Sreekanth Dayanand
    Version: 1.0
    Author URI: http://www.outsource-online.net
    */
?>

Step 2(create an admin page and a menu item for it)

a.use the 'action_hook' 'admin_menu'
//list of action_hooks https://codex.wordpress.org/Plugin_API/Action_Reference
add_action('admin_menu', 'osol_plugin_actions' /* call back function */);

OR if it a class method

add_action( 'admin_menu', array( $classObj, 'osol_plugin_admin_menu' ) );

b. and the call back function

function osol_plugin_admin_menu()
{
//add_options_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '' )
add_options_page("OSOL Plugin Config", "OSOL Plugin Config", 1, "osol_plugin_config_main", "config_main");
}//function osol_plugin_admin_menu()

c. add the call back function
public function configMain()
{
require_once(RETSOW_GSMLS_VIEWS_FOLDER.DS.'admin'.DS.'config_main.php');
}//private function configMain()

d.Activate the plugin(VERY IMPORTANT)

Step 3 (adding frontend pages)

//https://wordpress.stackexchange.com/questions/3396/create-custom-page-templates-with-plugins
add_filter( 'page_template', 'wpa3396_page_template' );// only available for 'pages' added from admin panel
function wpa3396_page_template( $page_template )
{
    if ( is_page( 'new-page-test' ) )
{
        $page_template = dirname( __FILE__ ) . '/custom-page-template.php';
    }
    return $page_template;
}

Step 4 (programaticaly change title, meta etc)

//https://stackoverflow.com/questions/772510/wordpress-filter-to-modify-final-html-output
function callback($buffer) {
  //modify buffer here, and then return the updated code
  preg_match("/<title>([^<]*)<\/title>/",$buffer,$match);
$new_title = "Buffer test".$match[1];

$buffer = preg_replace("/<title>([^<]+)<\/title>/","<title>$new_title</title>",$buffer);
  return str_replace('___RESTWSO_REPLACABLE___', "buffer replace test",$buffer);
}

function buffer_start() { ob_start("callback"); }

function buffer_end() { ob_end_flush(); }

add_action('after_setup_theme', 'buffer_start');
add_action('wp_footer', 'buffer_end');

Tuesday, January 16, 2018

Monday, January 15, 2018

type html in blogspot

Jquery Modal in Joomla 3

PHP
JHtml::_('jquery.framework');// load jquery first
JHTML::_('bootstrap.framework');



Javascript:
function bsModalHTMLundefined)
        {
            var bsWindowHTML = '<div id="bsdialog" class="modal fade" tabindex="-1" role="dialog">';
            bsWindowHTML = bsWindowHTML + '  <div class="modal-dialog">';
            bsWindowHTML = bsWindowHTML + '    <div class="modal-content">';
            bsWindowHTML = bsWindowHTML + '      <div class="modal-header">';
            bsWindowHTML = bsWindowHTML + '        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>';
            bsWindowHTML = bsWindowHTML + '        <h4 class="modal-title"></h4>';
            bsWindowHTML = bsWindowHTML + '      </div>';
            bsWindowHTML = bsWindowHTML + '      <div class="modal-body">';
            bsWindowHTML = bsWindowHTML + ' ';
            bsWindowHTML = bsWindowHTML + '      </div>';
            bsWindowHTML = bsWindowHTML + '      <div class="modal-footer">';
            bsWindowHTML = bsWindowHTML + '        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
            bsWindowHTML = bsWindowHTML + '      </div>';
            bsWindowHTML = bsWindowHTML + '    </div><!-- /.modal-content -->';
            bsWindowHTML = bsWindowHTML + '  </div><!-- /.modal-dialog -->';
            bsWindowHTML = bsWindowHTML + '</div><!-- /.modal -->';
            return bsWindowHTML;
        }//function bsModalHTMLundefined)
 function showJqueryDialog(dialogParams)
        {
            //code from http://www.iamrohit.in/create-dynamic-content-popup-using-bootstrap-modal-and-jquery/
            //css details https://www.w3schools.com/bootstrap/bootstrap_modal.asp
            //a simpler modal window is https://www.w3schools.com/howto/howto_css_modals.asp
            //jQuery("#bsdialog").remove();
            if(jQuery("#bsdialog").length == 0)jQuery(bsModalHTML()).appendTo('body'); 
            jQuery(".modal .modal-title").html(dialogParams.title);
            jQuery(".modal .modal-body").html(dialogParams.html);
             //left,width,margin-left
             jQuery("#bsdialog").css("width",'auto');
             jQuery("#bsdialog").css("display",'block');//adjust with content width
             jQuery("#bsdialog").css("left",(jQuery(window).width() - jQuery("#bsdialog").width())/2);
             jQuery("#bsdialog").css("marginLeft",'auto');
             jQuery("#bsdialog .modal-body").css("maxHeight",'none');//fit to height
       
            jQuery(".modal").modal("show");
        
        }//function showJqueryDialog()     

Pause Windows 10 update downloading and restarting it

As Into Windows points out, Windows 10 doesn’t give you an easy way to pause downloads in the Settings app directly. Instead, follow these steps:

Right-click the Start Menu and select Command Prompt (Admin).
Enter net stop wuauserv
Enter net stop bits
Enter net stop dosvc
Close the Command Prompt window.
Each command may take a few seconds to complete. If you want to reverse the process and resume downloads, follow these steps:

Right-click the Start Menu and select Command Prompt (Admin).
Enter net start wuauserv
Enter net start bits
Enter net start dosvc
Close the Command Prompt window.

You can also enabled the Metered Connection feature in Windows 10 to try to dissuade Microsoft from pushing large updates to your computer. However, this command line method is the most direct way to stop all the downloads.
Reference:
https://lifehacker.com/pause-windows-10-updates-easily-from-the-command-line-1786614642

mysql error 1366 : Incorrect decimal value: '' for column


You have strict sql mode enabled, and you try to pass an empty string ('') as value for decimal fields in the insert. Empty string is an invalid value for a numeric field and in strict sql mode mysql generates an error if you try to insert an invalid data into a column, rather than providing a warning and use the default value (0 for numeric columns) of the particular column's data type:
Strict mode controls how MySQL handles invalid or missing values in data-change statements such as INSERT or UPDATE. A value can be invalid for several reasons. For example, it might have the wrong data type for the column, or it might be out of range. A value is missing when a new row to be inserted does not contain a value for a non-NULL column that has no explicit DEFAULT clause in its definition. (For a NULL column, NULL is inserted if the value is missing.) Strict mode also affects DDL statements such as CREATE TABLE.
If strict mode is not in effect, MySQL inserts adjusted values for invalid or missing values and produces warnings (see Section 13.7.5.40, “SHOW WARNINGS Syntax”). In strict mode, you can produce this behavior by using INSERT IGNORE or UPDATE IGNORE.
Remove the strict sql mode for the session before starting the import:
SET SESSION sql_mode = ''


 Reference:
https://stackoverflow.com/questions/35037288/incorrect-decimal-integer-value-mysql

Friday, January 31, 2014

Codeignitor

http://ellislab.com/codeigniter/user-guide/installation/index.html

Installation Instructions

CodeIgniter is installed in four steps:
  1. Unzip the package.
  2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
  3. Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
  4. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
If you wish to increase security by hiding the location of your CodeIgniter files you can rename the system and application folders to something more private. If you do rename them, you must open your main index.php file and set the $system_folder and $application_folder variables at the top of the file with the new name you've chosen.
For the best security, both the system and any application folders should be placed above web root so that they are not directly accessible via a browser. By default, .htaccess files are included in each folder to help prevent direct access, but it is best to remove them from public access entirely in case the web server configuration changes or doesn't abide by the .htaccess.
After moving them, open your main index.php file and set the $system_folder and $application_folder variables, preferably with a full path, e.g. '/www/MyUser/system'.
One additional measure to take in production environments is to disable PHP error reporting and any other development-only functionality. In CodeIgniter, this can be done by setting the ENVIRONMENT constant, which is more fully described on the security page.
That's it!

removing index.php to make SEF URLs using .htaccess

http://stackoverflow.com/questions/10688236/when-i-tried-to-remove-index-php-from-codeigniter-url-i-get-redirect-to-domain

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt|assets/)
RewriteRule ^(.*)$ /index.php/$1 [L]
 

Thursday, January 23, 2014

YII framework tutorial for beginers

To create a YII base site
go to the folder where you want to create it
and run the following command
"YIIROOT_PATH\framework\yiic" webapp webAccessible
generates a site stub inside webAccessible folder
PS: YIIROOT_PATH\framework need not be web accessible

first login is
demo:demo
and
admin:admin

config files are in

protected\config folder of the stub
set DataBase details in protected/config/main.php
'db'=>array(
PS:comment default which is sqlite and uncomment the one below it for MYSQL
Gii tool
=======
edit protected\config\main.php
uncomment 3 lines pertaining to gii
set a password
edit 'ipFilters' carefully with the server name you use
http://www.yiiframework.com/doc/api/1.1/GiiModule#ipFilters-detail

or use localhost to use gii

http://localhost/YII_SITE_PATH/index.php?r=gii
pw:Crud password
CRUD files created by Gii will be array("protected".DS."controllers".DS."CRUD_NAMEController.php",
========= "protected".DS."models".DS."CRUD_NAME.php",
"protected".DS."views".DS."CRUD_NAME" /*this is folder*/);


Additionally the following files are created
protected\runtime\gii-1.1.14\CrudCode.php
protected\runtime\gii-1.1.14\ModelCode.php

Changing Field types(eg:text to drop down ) in CRUD forms
============================================
http://jmmurphy.blogspot.in/2013/05/using-yii-model-relations.html
http://stackoverflow.com/questions/17264317/need-help-to-create-crud-screen-with-dropdown-relation-using-yii-framework
Altering crud forms for multiple models in one go
======================================
http://www.yiiframework.com/wiki/384/creating-and-updating-model-and-its-related-models-in-one-form-inc-image/
this also contain example of transaction management $trans = Yii::app()->db->beginTransaction(); $trans->commit(); and $trans->rollback();

Module files created by GII will be in the folder
===================
protected\modules\MODULE_NAME\
they are created based on the templates in framework\gii\generators\module\templates\default.
additionally the file 'protected\runtime\gii-1.1.14\ModuleCode.php' is also created

Modules can be created without gii tool also though not necessary
http://www.linkedin.com/groups/how-create-modules-in-yii-1483367.S.156442090

Setting Module paramenters in protected/config/main.php
http://www.yiiframework.com/doc/guide/1.1/pt/basics.module

http://localhost/YII_SITE_PATH/index.php?r=greeting/index
or
http://YII_SITE/index.php/greeting/index
or even
=======
http://YII_SITE/greeting/index

after creating/editing .htaccess and protected/config/main.php

'urlFormat'=>'path',
'showScriptName'=>false,
//'caseSensitive'=>false, //NEVER SET THIS THIS WILL NOT LET MODULES LOAD

(should also enable mod_rewrite pache module for this to work)
as mentioned in
http://www.yiiframework.com/wiki/214/url-hide-index-php/

contollerId/ActionId
protected/controllers/GreetingController.php
protected/views/greeting/index.php



pass variable from controller to view by altering controller code from
=========================================================
$this->render('index);
to
$this->render('index',array('content' => $this->message));

and use $content variable in view file

you can use $this->message directly in view file as well

using database
--------------------------

http://vimeo.com/18448007

edit protected/config/main.php
comment
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
uncomment the 'db' config of MYSQL below setting database details correctly

gii Model generator
=================
generates
models\Message.php where Message is the name of the model specified in 'Model generator' form

to use message from database
$message = Message::model()->findByPK(4);
$this->message = $message->content;
CRUD Generator
==================
use model name made with "Model Generator" and a suitable controller name

Make user login from db
==================
http://danaluther.blogspot.in/2010/03/yii-authentication-via-database.html (also mentions how to use CRDU in command line,check my addendum also )
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth

Add additional admin users
============================
$auth=Yii::app()->authManager;
//if not already added run the following comment just once
//$role = $auth->createRole('admin', 'administrator');
$record=User::model()->findByAttributes(array('username'=>$username));//Check http://www.yiiframework.com/doc/api/1.1/CActiveRecord for all search functions available for User::model()
$userId = $record->id;
$auth->assign('admin',$userId);
Assigning Biz rule for role 'mcqadder' and checking in script
============================================
return in_array('mcqadder',array_keys(Yii::app()->authManager->getAuthAssignments(Yii::app()->user->id)));

Yii::app()->user->checkAccess('mcqadder')

Usefull functions to get parameter URL etc
=======================================
//Yii::app()->request->getQuery($key, $defaultValue) and getPost() with the same parameters.
//Yii::app()->controller->id and Yii::app()->controller->action->id
//ie(Yii::app()->request->url);
Create YII site url with params
=======================
Yii::app()->createUrl('faq/index', array('cid' => 'asas'))
Redirect
============
Yii::app()->request->redirect(Yii::app()->user->returnUrl);
Login and logut with code
===================
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth#login-and-logout
leave login for a certain period using Cookie
==================================
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth#cookie-based-login

to change site name
==================
edit protected/config/main.php
change 'name' =>

to set title and meta dynamically
==============================
use the following code in ControllerAction
$this->pageTitle = 'New Title';

Yii::app()->clientScript->registerMetaTag('foo, bar', 'keywords');
Yii::app()->clientScript->registerMetaTag('foodescription, bardescription', 'description');
to set default meta values set them in protected/controllers/SiteController.php
Edit overall layout
===============
http://www.yiiframework.com/wiki/249/understanding-the-view-rendering-flow/
edit protected/views/layouts/main.php
Change Contact email
==================
'adminEmail' in protected/config/main.php
Change remove//Default Logins
==========================
http://stackoverflow.com/questions/10772615/yii-framework-remove-demo-admin-accounts
under protected/components you'll find UserIdentity.php, the users and their passwords will be declared in the authenticate function using an array.

To modify top menu
==================
edit protected\views\layouts\main.php
to ad external link or open in target_blank
array('label'=>'Gii', 'url'=>'http://SiteURL','linkOptions'=>array('target'=>'_blank')),

Useful Extensions
===============
GIIX to create CRUD forrelationsal tables
----------------------------------------------------------
http://www.yiiframework.com/extension/giix
https://github.com/rcoelho/giix
https://github.com/rcoelho/giix/blob/master/INSTALL

Running Queries
==============
http://sonsonz.wordpress.com/2011/05/05/executing-sql-statements/
Load Javascript
============
http://www.yiiframework.com/wiki/572/how-to-include-javascript-css/
Events and behaviors
===================
http://www.yiiframework.com/wiki/44/
Admin panel Basics
========================
http://www.yiiframework.com/wiki/33/
another method with yii behavior feature
http://www.yiiframework.com/wiki/63/organize-directories-for-applications-with-front-end-and-back-end-using-webapplicationend-behavior

Auth permissions
===================
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth
http://www.benjaminlhaas.com/blog/installing-yii-users-and-rights-5-steps