For smart Primates & ROBOTS (oh and ALIENS ).

Blogroll

Thursday, April 23, 2015

html html5 to Pdf

Generate PDF file of html html5 with div span tags. It really works on liquid layout also!
Try it now!





html html5 to Pdf
Download here:

Part-1 
Part-2
Part-3
Part-4
Part-5
Part-6
Part-7
Part-8
Part-9
Part-10
Part-11

Extract  all files Part-1 to Part-11 and paste all files in one folder and double click on
Html-Html5-to-PDF.exe
Share:

Wednesday, April 22, 2015

File open Dialogbox show error System Threading ThreadStateException

Problem:

I am wondering when you get the error 'System.Threading.ThreadStateException' while using OpenFileDialog in C# Winform application. So how to solve this?

First we see the error details, after that I will show you solution.
See the screenshot below.
System.Threading.ThreadStateException



















Error is:
"An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll
Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process."

Code is:

System.Windows.Forms.OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Select HTML/HTML5 file";
openFileDialog.InitialDirectory = "C:";
openFileDialog.Filter = "HTML files (*.html)|*.html|Flv files (*.htm)|*.htm";
openFileDialog.AutoUpgradeEnabled = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
String Chosen_File = openFileDialog.FileName;
       String inputExt = (Path.GetExtension(Chosen_File).ToLower());
       textBox1.Text = Chosen_File;
       textBox2.Text = Chosen_File + "_New" + inputExt;
}
It will show error on the line

if (openFileDialog.ShowDialog() == DialogResult.OK)


The full error code is:
=============================
System.Threading.ThreadStateException was unhandled
  HResult=-2146233056
  Message=Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.FileDialog.RunDialog(IntPtr hWndOwner)
       at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.CommonDialog.ShowDialog()
       at CoreRenderer.Form1.button3_Click(Object sender, EventArgs e) in d:\CurrentProject\WinForm\VS2013Testing\CS\CoreRenderer\CoreRenderer\Form1.cs:line 121
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at CoreRenderer.Program.Main() in d:\CurrentProject\WinForm\VS2013Testing\CS\CoreRenderer\CoreRenderer\Program.cs:line 21
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
=============================

Solution:

To overcome this problem you need to use Thread class. See below code that how to fix this error.

Example:

Create a method as below:
public void getfile() {
      System.Windows.Forms.OpenFileDialog openFileDialogAvi = new OpenFileDialog();
      openFileDialogAvi.Title = "Select HTML/HTML5 file";
      openFileDialogAvi.InitialDirectory = "C:";
      openFileDialogAvi.Filter = "HTML files (*.html)|*.html|Flv files (*.htm)|*.htm";
      openFileDialogAvi.AutoUpgradeEnabled = true;
      if (openFileDialogAvi.ShowDialog() == DialogResult.OK)
      {
         String Chosen_File = openFileDialogAvi.FileName;
         String inputExt = (Path.GetExtension(Chosen_File).ToLower());
         Invoke((MethodInvoker)delegate
         {
               textBox1.Text = Chosen_File;
               textBox2.Text = Chosen_File + "_New" + inputExt;
         });
      }
   }


On click button access the above method:

private void button2_Click(object sender, EventArgs e) {
       Thread threadGetFile = new Thread(new ThreadStart(getfile));
       threadGetFile.ApartmentState = ApartmentState.STA;
       threadGetFile.Start();         
}

Share:

Monday, April 20, 2015

How to use Response.Write in ASP.NET MVC 5

Problem:

How to use Response.Write in ASP.NET MVC 5

Solution:

See the below example:

Example:

   @{
        Response.Write("<br/>Emp First Name :");
    }


OR

  @("test")

Share:

Sunday, April 19, 2015

jquery ui dialog box show previous page before show new page's contents

Problem:

If you used jquery ui dialog box to show any dynamic page's contents then I am sure you have faced this problem. when you click first time it will work fine but the second time on click it will show previous page's contents and after  delay of 2 to 3 seconds it will show the contents of the url which you have supplied. this is the bug in jquery ui dialog box.
Consider below code:

<link rel="stylesheet" type="text/css" media="all" href="jquery-ui.css">

<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>

<a href="#" onclick="show_full(1);>View</a>

<script>
function show_full(q_id) {
    var url="show_q_a.php?serial="+new Date().getTime()+"&q_id="+q_id;                   
    $( "#dialog" ).dialog( {
                                autoOpen: false,
                                modal: true,
                                height: 550,
                                width:1000,
                                title: "Question and Answer"
    });
    $("#dialog").load(url);
    $( "#dialog" ).dialog( "open" );
</script>

Solution:

Use <div> and <iframe > tag to prevent the show previous  page problem. see below correct code as a example.

Example:

function show_full(q_id) {
    var url="show_q_a.php?serial="+new Date().getTime()+"&q_id="+q_id;   
    var $dialog = $('<div></div>')
               .html('<iframe style="border: 0px; " src="' + url+ '" width="100%" height="100%"></iframe>')
               .dialog({
                   autoOpen: false,
                   modal: true,
                   height: 550,
                   width: 1231,
                   title: "Question and Answer"
               });
    $dialog.dialog('open');
}
Share:

Friday, April 17, 2015

jquery ui datepicker automatically delete text from input field

Problem:

Did you worked with jquery ui date picker? when assigned a default value to text filed, jquery ui datepicker will automatically delete text from that textbox field. So how to stop it?

Solution:

It seems the bug in jquery ui datepicker which is automatically delete text from input field. to overcome this problem you need to write 22 lines of code as example below:

Example:

// assume that the $edit_diesel_date is already filled with date value.
// write this code very bootom of your page.
function dook() {  $("#diesel_date").val("<?php echo $edit_diesel_date;?>");     }
setTimeout("dook();", 500);
Share:

session destroyed after redirect in codeigniter

Problem:

Working CodeIgniter framework you can face the session problem. the problem is when you storing the values in session and redirect the page. then session destroyed automatically, it is loosing session data even you have properly loaded session library $this->load->library('session') in constructor.

see the below code:

public function myset() 
{
        $this->session->set_userdata('mydata', 'data');
        redirect('/', 'refresh');
}


function index()
{
          // loosing here data
          $mydata = $this->session->userdata('mydata');

}






Solution:

As we are seeing many new frameworks are coming today. but the Mother and base of all frameworks is Core PHP,  So we must have good knowledge about Core PHP. Here I have solved this session problem by Core PHP.

Example:

session_start();
public function myset() 
{
        $_SESSION['mydata']='data'
        redirect('/', 'refresh');
}


function index()
{      $mydata='';
        if(isset($_SESSION['mydata']) && !empty($_SESSION['mydata'])) {
                  $mydata= $_SESSION['mydata']);
        }

}

Share:

Wednesday, April 15, 2015

How to use multilanguage in CodeIgniter

Problem:

Suppose you want to use Italian language in CodeIgniter then how to do it?



Solution:

CodeIgniter provide a facility that you can store the predefined words in array in separate files. after that you can use it as per your requirements.

Example:

1- create a folder name "italian" under "application\language".
2- under this folder create a "italian_lang.php" file as below matter. change it's matter as per your requirements.
<?php
$lang['home_slide_1']        = "Rendi <span>unici</span> i tuoi parastinchi";
$lang['home_latuaidea_title']        = "La tua <br/>idea";
/// and many more....
?>
now your file is created, now the question is that how to use it?
4- in view where you want to write italian text at the top of file load this file as below method:
$this->lang->load('italian', 'italian');


<?php echo $this->lang->line('home_slide_1');?>
<?php echo $this->lang->line('home_latuaidea_title');?>


Share:

Friday, April 10, 2015

Run custom sql query in CakePHP 3.0

Problem:

How to Run custom sql query in CakePHP 3.0

Solution & Example:

File : src\Model\Table\ArticlesTable.php
<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Datasource\ConnectionManager;
class ArticlesTable extends Table
{
    var $conn;
    public function initialize(array $config) {
        $this->conn = ConnectionManager::get('default');
    }
    function get_all_users($id) {
        $stmt = $this->conn->prepare('SELECT * from users WHERE id>= :id');
        $stmt->bind( ['id' => $id], ['id' => 'integer']);
        $stmt->execute();
        return $stmt->fetchAll('assoc');
     } 
}
?>

File: src\Controller\ArticlesController.php
<?php
namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
//use MyClass\MyClass;
use MyLib\UtilClass;

 class ArticlesController extends AppController
 {
     public $helpers = array('Html', 'Form');
     public function index() {

    }
    public function showarticles(){
         $data = $this->Articles->get_all_users(3);
         $this->set('data',$data);
    }
}


File: src\Template\Articles\showarticles.ctp
<?php
foreach ($data as $row){
               echo '<br/>'.$row['username']. '-------' . $row['password'];
         }
?>









Share:

Thursday, April 09, 2015

Add new row dynamically in JTable

Problem:

Add new row dynamically in JTable
This is Java code allow to you add a new row in JTable.
when you press enter then a new row automatically inserted and you can make more entry.


Add new row dynamically in JTable









Solution & Example:

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
public class t1 extends JFrame {
DefaultTableModel model;
JTable table;
JScrollPane sc1;
public t1() {
super("Data Entry Form By Amit Gaur (amitt800@gmail.com)");
int i,j;
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
model = new DefaultTableModel();
table = new JTable(model);
model.addColumn("Name");
model.addColumn("ID");
model.addColumn("Salary");
model.addColumn("Jobs");
model.addRow(new Object[]{"","","",""});
table.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
model.addRow(new Object[]{"", "","",""}); } }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { } } );

sc1 = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); cp.add(sc1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
setVisible(true);
}
public static void main(String[] ss) {
new t1();
}
}




Share:

Wednesday, April 08, 2015

How to create own custom class in cakephp 3.0

Problem:

How to use own custom class or library class in CakePHP 3.0
If you have own useful library and you want to use it in your CakePHP 3.0 MVC Framework then follow below steps.


Solution:

If you have good knowledge of Core PHP then It will be easy to create own custom class in CakePHP 3.0 and use it. follow below steps:

1# Create the folder "MyLib" at root of CakePHP 3.0 structure where bin,config,logs folders are showing. you can also create it in the "vendor" folder but I think we should not create in there.

2# Create "UtilClass.php" file in the "MyLib" folder.

3# And last use it in your controller with it's path.

Example:

1# Create the folder "MyLib" at root of cakephp 3.0 structure where bin,config,logs folders are showing.

2# Create "UtilClass.php" file in the "MyLib" folder with below code:
<?php
namespace MyLib; //it is important,it is folder name
class UtilClass
{
    public function show()
    {
        return 'I am from my custom class in cakephp 3.0';
    }
}
?>


3# Use is as below code in any controller:
<?php
use MyLib\UtilClass;
 class TransportersController extends AppController
 {
     public function index() {

    }

    public function showtransporter(){
      require_once(ROOT .DS. "MyLib" . DS . "UtilClass.php");
      $util_obj = new UtilClass();
      echo $util_obj->show();

  }
}
?>
Share:

Tuesday, April 07, 2015

Model in CakePHP 3.0

Problem:

CalePHP 3.0 is different than it previous versions. Lot of things removed. In new CakePHP 3.0  
How to use Model in CakePHP 3.0 using new ORM model

Solution:

See below example

Example:


Create ArticlesController.php controller in "src\Controller" folder
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
class ArticlesController extends AppController
{
     public function index() {

     }
    public function showarticles() {
        $data = $this->Articles->find();
        foreach ($data as $row){
          echo $row->title;
       }
    }
}

ArticlesTable.php in "src\Model\Table" folder
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class ArticlesTable extends Table
{

}
?>

Create Article.php in "src\Model\Entity" folder
<?php
// src/Model/Entity/Article.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Article extends Entity
{
       
}
?>






Share:

Saturday, April 04, 2015

custom query in cakePHP 3.0

Problem:

How to execute custom query in cakePHP

Solution:

Use ConnectionManager::get() and it's method newQuery() you can pass custom sql query

Example:


Change your database information in "config\app.php" file as below:

  'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => 'root',
            'password' => '',
            'database' => 'petro_app',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
        ],
        ],
    ],


At the top in php code file where you want to execute sql query access ConnectionManager class as below:

use Cake\Datasource\ConnectionManager;

In method run sql query as below:
File name HardSelectionController.php   with complete code


use Cake\Datasource\ConnectionManager;

class HardSelectionController extends AppController  {

    public function showhardselection() {
      $conn = ConnectionManager::get('default');
      $query = $conn->newQuery();
     $query->select('*')
                ->from('user_info');
                ->where(['active' => true]);
    foreach ($query as $row) {
         echo $row['u_login'];
    }
}
}
Share:

Form in CakePHP 3.0

Problem:

How to create Form in CakePHP 3.0

Solution:

To create form in CakePHP 3.0 you need to use $this->Form->create() and along with this also use
echo $this->Form->input(), $this->Form->label(), $this->Form->text(), $this->Form->button() and never forget that every for must close with $this->Form->end(array('')) method.


Example:

Create this view file  "showhardselection.ctp" under "src\Template\HardSelection" folder.
<?php
echo $this->Form->create('UserForm', array('url' => array(
                        'controller' => 'HardSelection',
                        'action' => 'showsubmitdata')));
echo $this->Form->input('email');
echo $this->Form->label('username', 'Your username');
echo $this->Form->text('username');
echo $this->Form->button('Submit');
echo $this->Form->end(array(''));
?>

Create this controller file "HardSelectionController.php" in"src\Controller" folder.
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;

class HardSelectionController extends AppController
 {
     public function index() {

    }
    public function showhardselection(){
       
    }
    public function showsubmitdata() {
        if($this->request->is('post')) {
            $email = $this->request->data['email'];
            $username = $this->request->data['username'];
            $this->set('email',$email);
            $this->set('username',$username);           
        }
    }
}

Create this view file  "showsubmitdata.ctp" under "src\Template\HardSelection" folder.
<?php
if(isset($email)) {
    echo 'user email:'.$email;   
}
if(isset($username)){
    echo '<br/>user name:'.$username;   
}
?>

Share:

Friday, April 03, 2015

How to change default controller in CakePHP 3.0

Problem:

How to change default controller in CakePHP 3.0. You know that default page of CakePHP 3.0 is Pages and it's action is display.

Solution:

To change default controller in CakePHP 3.0 open config.php which is located under "config" folder.
and change :

$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
TO
$routes->connect('/', ['controller' => 'Welcome', 'action' => 'index', 'home']);

Where Welcome is your created controller.

Share:

Thursday, April 02, 2015

Notice (8): Undefined variable in cakephp

Problem:

You can get the error message Notice (8): Undefined variable in CakePHP while passing variable value from Controller to View. How to overcome this error?




Solution:

If you mistakenly create a method in predefined Controller "PagesController.php" which is automatically created by default. So don't touch or use "PagesController.php". you need to create own Controller ans create method and pass variable.
In other clear wording "do not use PagesController.php file, create own controller class"

Example:

See below incorrect code:
File:    src\Controller\PagesController.php

<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;

class PagesController extends AppController
{
    public function display()
    {
        $path = func_get_args();

        $count = count($path);
        if (!$count) {
            return $this->redirect('/');
        }
        $page = $subpage = null;

        if (!empty($path[0])) {
            $page = $path[0];
        }
        if (!empty($path[1])) {
            $subpage = $path[1];
        }
        $this->set(compact('page', 'subpage'));

        try {
            $this->render(implode('/', $path));
        } catch (MissingTemplateException $e) {
            if (Configure::read('debug')) {
                throw $e;
            }
            throw new NotFoundException();
        }
    }
   
    public function myshow() {
      $this->set('color', 'pink');
    }
}

File: \src\Template\Pages\myshow.ctp
<?php
   echo $color;
?>


See below Correct code:
Create a new File BooksController
File:  src\Controller\BooksController.php

<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
class BooksController extends AppController
{    
      public function index()
    {

    }
    public function myshow() {
       $this->set('color','pink');
    }
}

Create a new file myshow.ctp
File: \src\Template\Books\myshow.ctp
<?php
   echo $color;
?>

So do not use PagesController.php file, create own controller class





Share:

How to make center align child div

 How to make center align child div?   Suppose you have 2 Div tag. And want the make inner tag center <div id="d1">      ...

Ads Inside Post

Powered by Blogger.

Arsip

Blog Archive