Magento Admin Custom Module Common Problems

Hello friends,

Custom development in any technology is continuous process. The common reason for custom development is frequently changing requirements.

By applying same rule in Magento, developers are developing more and more custom modules. And some of those modules are related to admin functionality.

Just before a week I was developing a magento custom module in which 60% of functionalities were related to admin. While developing those admin related functionalities I faced some common problems.

So here I want to discuss those problems and its solutions.

Problem 1: In my module I have successfully created admin grid. Where add and edit functionalities were working fine. But while editing an item, there was no DELETE button in the form. I surprised, checked my code but didn’t get an idea for that problem. So I searched the web and found the under given solution.

Solution 1: The problem is in Edit.php block, I put

parent::__construct();

at the first line of

 __construct()

method.

But it should be after the

$this->_controller

line.

I did that change and my problem get solved.

Problem 2: In my module, an admin form has facility to upload the file. There I was able to add the item and upload the file successfully. Whenever I edit the item a very small thumbnail image of the uploaded file along with the browse button and delete option was displaying. Then I tick marked the delete option and click on “Save and Continue” button and it gave me the under given error.


Warning: preg_match() expects parameter 2 to be string, array given  in /lib/Varien/Data/Form/Element/Image.php on line 56

Solution 2: Above error occurred, just because there wasn’t any code in custom module’s controller to delete the uploaded file.

So to solve the problem I did the changes in the /app/code/local/Company/Modulename/controllers/Adminhtml/ModulenameController.php file.

Where I looked for the code block like:

if(isset($_FILES['image_file']['name']) && $_FILES['image_file']['name'] != '')

And added the under given else condition block right after the above if condition block.

elseif (isset($data['image_file']['delete']) && $data['image_file']['delete'] == 1) {
    $path = Mage::getBaseDir('media') . '/';
    if(file_exists($path . $data['image_file']['value'])) {
        unlink($path . $data['image_file']['value']);
    }
    $data['image_file'] = '';
} elseif (isset($_POST['image_file']['value'])) {
    $data['image_file'] = $_POST['image_file']['value'];
} else {
    $data['image_file'] = '';
}

And the problem got solved.

That’s it.

Hope this will help you.

Thanks.

Advertisements

Remember me (id-password) functionality on magento login page.

123

We all know about the login functionality of site. In that functionality one option for remember password available. But magento default does not provide that functionality on login page. So today I post this blog for providing that functionality on page.

 

Step: 1 Open the file at following location.

Magento\app\code\core\Mage\Customer\controllers\AccountController.php

 

Step: 2 Find following function.

protected function _loginPostRedirect()

 

Step: 3 Replace with following function code.


protected function _loginPostRedirect()
{

        $session = $this->_getSession();

        if (!$session->getBeforeAuthUrl() || $session->getBeforeAuthUrl() == Mage::getBaseUrl())
        {

               // Set default URL to redirect customer to

               $session->setBeforeAuthUrl(Mage::helper('customer')->getAccountUrl());

             // Redirect customer to the last page visited after logging in

             if ($session->isLoggedIn())
             {
                 if (!Mage::getStoreConfigFlag('customer/startup/redirect_dashboard'))
                 {
                       $referer = $this->getRequest()->getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME);
                       if ($referer)
                       {
                                 $referer = Mage::helper('core')->urlDecode($referer);

                                 if ($this->_isUrlInternal($referer))
                                 {
                                       $session->setBeforeAuthUrl($referer);
                                 }
                        }
                }
                else if ($session->getAfterAuthUrl())
                {
                        $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
                }
            }
            else
            {
                $session->setBeforeAuthUrl(Mage::helper('customer')->getLoginUrl());
            }

       }
       else if ($session->getBeforeAuthUrl() == Mage::helper('customer')->getLogoutUrl())
       {
             $session->setBeforeAuthUrl(Mage::helper('customer')->getDashboardUrl());
       }
       else
       {
             if (!$session->getAfterAuthUrl())
             {
                  $session->setAfterAuthUrl($session->getBeforeAuthUrl());
             }

             if ($session->isLoggedIn())
             {
                  $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
             }
       }

       if ($this->getRequest()->isPost())
       {

             $login = $this->getRequest()->getPost('login');
             $rememberme = $this->getRequest()->getPost('rememberme');

             try
             {

                  $cookie = Mage::getModel('core/cookie');

                  if (!empty($login['username']) && !empty($login['password']) && !empty($rememberme))
                  {
                        $cookie->set('user_name', $login['username']);
                        $cookie->set('pass_user_name', $login['password']);
                        $cookie->set('rememberme', 1);
                  }
                  else if (!empty($login['username']) && !empty($login['password']) && empty($rememberme))
                  {
                        $cookie->delete('user_name');
                        $cookie->delete('pass_user_name');
                        $cookie->delete('rememberme');
                  }
             }
             catch (Exception $e)
             {
             }
       }
       $this->_redirectUrl($session->getBeforeAuthUrl(true));
}

Step: 4 Find following file (login page functionality).

Magento\app\design\frontend\default\[your theme]\template\customer\form\login.phtml

Step: 5 Add following code top of login.phtml.


<?php

          $cooki = Mage::getModel('core/cookie');

          $cookie_user_name = $cooki->get('user_name');

          $cookie_user_password = $cooki->get('pass_user_name');

          $rememberme = $cooki->get('rememberme');

?>

Step: 6 Find following code in login.phtml (user id textbox).


<input type="text" name="login[username]" value="<?php echo $this->htmlEscape($this->getUsername()) ?>" id="email" title="<?php echo $this->__('Email Address') ?>" />

And replace with the following code. The code define the user id of user if that user select remember me option.


<input name="login[username]" value="<?php if($cookie_user_name != "){ echo $cookie_user_name;}else{ echo $this-/>htmlEscape($this->getUsername()); } ?>" title="< ?php echo $this->__('Email Address') ?>" id="email" type="text" />

Step: 7 Find following code in login.phtml (password textbox).


<input type="password" name="login[password]" id="pass" title="<?php echo $this->__('Password') ?>" />

And replace with the following code. The code define the password of user if that user select remember me option.


<input name="login[password]" type="password" class="input-text required-entry validate-password"  value="<?php if($cookie_user_password != ''){ echo $cookie_user_password;}?/>" />

Step: 8 Add the following code at the place where you want to display checkbox for the functionality of remember me on page.


<div>

<input type="checkbox" name="rememberme" value="remember" <?php if($rememberme != ''){ echo "checked";} ?/>   /> Remember me.

</div>

I hope this will help you.

Thank you.

Concept of Heap Size In Java (OUT OF MEMORY ERROR)

Have you ever came across the error like java.lang.OutOfMemoryError in Tomcat, while running an application???? Then this the r8 place you are wondering for.

You generally get along with this error, when you are trying to access extra memory for objects, than the actually defined fixed size. The size allocated when creating new objects is called as heap size.

HEAP SIZE:  When you are working with any application in java, a specific memory is allocated to Java virtual machine (JVM) by Operating System. JVM uses this memory for all its work and from this , a part of memory is known as JAVA HEAP MEMORY.

When any object is created by new operator or by some other way, it is allocated some memory space from heap. If the object creation requires more space than the heap size it throws the error java.lang.OutOfMemory. Heap resides at the bottom space of the memory allocated to JVM.

Java Heap space is generally divided into three regions or generation for sake of garbage collection

i) New Generation

ii) Old or tenured Generation

iii) Perm Space (permanent Generation).

As and when the object dies or is garbage collected , the free memory is joined to the heap memory. The default heap size limit in java is 128MB for a 32-bit, but it highly varies from JVM to JVM. But this is not it, you can also change the heap space if required when you need more objects or your application is quite large.

Changing the heap size

Generally there are two functions that deal with changing the heap size:

1) -Xms : This signifies the minimum(initial) heap size in java.

2) -Xmx : This signifies the maximum heap size in java.

To change the heap size , open CMD-> Change the directory to path where your java is installted.

Suppose your java is installed in directory C:\Program Files (x86)\Java\jdk1.7.0-64\bin

Below shown screen shot shows you the wayto change heap size:

cmd

 

 

Press enter and your heap size gets changed to minimum size of 256Mb and maximum size of 1024Mb.

Program to know heap size:


public class Heapsize {

public static void main(String [] args) {

int mb = 1024*1024;

//Getting the runtime reference from system

Runtime runtime = Runtime.getRuntime();

System.out.println ("##### Heap utilization statistics [MB] #####");

//Print used memory

System.out.println("Utilized Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

//Print free memory

System.out.println ("Free Memory:" + runtime.freeMemory() / mb);

//Print total available memory

System.out.println ("Total Memory:" + runtime.totalMemory() / mb);

//Print Maximum available memory

System.out.println ("Maximum Memory:" + runtime.maxMemory() / mb);

}

}

Output:

output

Java also provides you the facility to change the Thread stack size by the function:

i)   -Xss<size>  set java thread stack size

Hope this helps you. If you face any problem in this blog do leave a message, always keen to help you… 🙂

Get social media activity count of url using php

Hello Friends,

We all know that we widely used social media for the marketing of our different thinks over the world. So we get the information about what status of our thinks. The status means information in the form people like’s, share, comment’s etc.

For that I post this blog to get complete information of the URL from following social media.

  1. Facebook.
  2. Twitter.
  3. Linkedin.
  4. Google Plus (G-Plus).

There are following ways to get information from site.

Method-1: Code for getting like’s of particular URL from face-book, twitter and Google plus.  


<?php

$url = 'http://www.indieswebs.com/';

$json = file_get_contents("http://api.sharedcount.com/?url=" . rawurlencode($url));

$counts = json_decode($json, true);

echo "This page has " . $counts["Twitter"] ." tweets, " . $counts["Facebook"]["like_count"] . " likes, and ". $counts["GooglePlusOne"] . "+1's";

?>

Method-2: Code for getting activities of particular URL from face-book, twitter, Google plus and LinkedIn. 


<?php

//Get Number of Tweets from Twitter

function get_tweets($url)

{

$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);

$json = json_decode($json_string, true);

return intval( $json['count'] );

}

//Get Number of LinkedIn Shares

function get_shares($url)

{

$json_string = file_get_contents("http://www.linkedin.com/countserv/count/share?url=$url&format=json");

$json = json_decode($json_string, true);

return intval( $json['count'] );

}

//Get Number of Facebook Shares/Like/Comment/Click

function get_likes($url)

{

$json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);

$json = json_decode($json_string, true);

return intval( $json[$url]['shares'] );

}

//Get Number of Google+1′s

function get_plusones($url)

{

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");

curl_setopt($curl, CURLOPT_POST, 1);

curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

$curl_results = curl_exec ($curl);

curl_close ($curl);

$json = json_decode($curl_results, true);

return intval( $json[0]['result']['metadata']['globalCounts']['count'] );

}

$facecount = get_likes('http://www.indieswebs.com/');

echo "<br />The Answer For Facebook".$facecount;

$linkdinshare = get_shares('http://www.indieswebs.com/');

echo "<br />The Answer For LINKDIN".$linkdinshare;

$tweetcount = get_tweets('http://www.indieswebs.com/');

echo "<br />The Answer For Tweet".$tweetcount;

$gpcount = get_plusones('http://www.indieswebs.com/');

echo "<br />The Answer For Google".$gpcount;

?>

I Hope this will help you

Thank you

Android Activity Lifecycle

Hello, Everyone Today I am going to describe you about Activity Lifecycle of Android. Activity means nothing but it is simply a Screen or a page.When I first started programming for the Android I was quite confused about the life-cycle of activities. It seemed almost strange how the application started, stopped, and paused without seemingly any logical reasoning. The activity would be destroyed and re-created when the screen was rotated and paused when other applications were started. Now come to the point, seven methods are called during android activity lifecycle.

1)    OnCreate()

2)    OnStart()

3)    OnResume()

4)    OnPause()

5)    OnStop()

6)    OnRestart()

7)    OnDestroy()

I will explain all this methods and also how they work and their usefulness  in this post.

First of all see below Image for getting some idea about how activity lifecycle works.

mdtqE

1) onCreate ():- This method is called when the activity is first created. In this method you have to do all of your normal static set up: create views, bind data to lists, etc. Always followed by onStart ().

2) onStart ():-This method is called when the activity is becoming visible to the user. This is followed by onResume () if the activity comes to the foreground, or   onStop () if it becomes hidden.

3) onResume():-This method is called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. This method is always followed by onPause().

4) onPause ():-This method is called when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A’s onPause () returns, so be sure to not do anything lengthy here.

5) onStop ():-This method is called when you are no longer visible to the user. You will next receive either onRestart (), onDestroy (), or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity’s process running after its onPause () method is called.

6) onRestart ():-This method is called after your activity has been stopped. It is called just before your activity start again. Always followed by onStart()

7) onDestroy():-The final call you receive before your activity is destroyed. This can happen either because the activity is finishing .someone called finish () on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing () method.

When the Activity first time loads the events are called as below:

i)   onCreate()

ii)  onStart()

iii) onResume()

 When you click on Phone button the Activity goes to the background & below events are called:

i)  onPause ()

ii) onStop ()

 Exit the phone dialer & below events will be called:

i)   onRestart()

ii)  onStart()

iii) onResume()

 When you click the back button OR try to finish () the activity the events are called as below:

i)   onPause()

ii)  onStop()

iii) onDestroy()

 Hope it helps in understanding Activity Lifecycle of android. Happy Coding 🙂

 

Add a new banner group in Indies Banner module

Hello Friends.

We use Indies Banner module in our magento application. But up to this time we could only use the default banner styles that were provided by module itself. Today I will describe the way to add new style in the banner module and use that style as per our requirement. For that you have to follow these steps:

STEP: 1: NAME GIVEN TO STYLE FOR ADMIN INTERFACE

For Giving the name to new style, open the status.php that is stored at following location.

Magento\app\code\community\Indies\Banner\Model\status.php

Now add the new entry for our style in static public function getPreAnimationArray() function at the end.

For example:

array(
'value' => 'vdslider',
'label' => Mage::helper('banner')->__('Image Banner Slider'),
),

The above entry “’Image Banner Slider” considers as the label and “vdslider” consider as a value that pass in the array. The label display as option in the Banner Group as

1

and value”vdslider” display in the Banner Group Grid as follows.

2

STEP: 2 NOW REGISTER STYLE FOR EFFECT

In step-1 we just declared the new style. Now in this step we can provide the effect to that style. For giving the effect first we will make entry of that style into banner.phtml located at:

Magento\app\design\frontend\[your theme]\template\indiesbanner\Banner.phtml.

Entry made using adding new case for our style. For Example

case 'vdslider':
 $template = $this->getLayout()->createBlock('banner/banner', 'bannerslider.banner')->setBannerGroupCode($bannerGroupCode)->setTemplate('unibanner/effects/bannerslider.phtml')->toHtml();<br />
 break;

In the following two things are more important.

First the case title (vdslider). The title is the value of style that is given in the step-1.

Second thing is the name of file that is created for this style. Here we create ‘bannerslider.phtml’ and set this file as template as follows. “setTemplate (‘unibanner/effects/bannerslider.phtml’)”.

STEP: 3 CREATE STYLE FILE FOR FRONTEND OUTPUT

The file that is set as template (setTemplate (‘unibanner/effects/bannerslider.phtml’)) in step-2 needs to be created at the following location.

Magento\app\design\frontend\[your theme]\template\indiesbanner\effects\bannerslider.phtml.

In this file we can put logic for new effect.

I Hope this will help you.

Thank You

Encryption and Decryption using AES algorithm in java

In Today’s Internet Era it is highly recommended to keep your data utmost secure from threa12ts and attacks. Attacks are highly costly, whether the attack comes from inside or out. As computer (and especially Internet) technologies evolve, security attacks are becoming more sophisticated and frequent. We have to stay updated with the latest techniques and tools for our Application safety and security, and for this the solid foundation in various technologies such as data encryption, authentication, and authorization is a necessity.

In our web application many things need to get secured , take for an example in  online banking and shopping, recorded data is stored in many places, including bank accounts, store accounts, and medical accounts. User Password, telephone no, credit card no’s, bank account no, etc. are vulnerable to attacks, so these data needs to be highly secured.

So, in this article I will explain you how to secure your data by encrypting and decrypting of data using AES algorithm in java:

Now for encrypting the data, we must use a secret key, which will only be provided to the sender and the receiver using which they can encrypt and decrypt the data. In our example we use an algorithm called AES 128 and the bytes of the word “ThisIsASecretKey” as the secret key. AES algorithm can use a key of 128 bits (16 bytes * 8); so we have selected that key.

Before moving to the example let me make you familiar with some basic terms:

1)      Key Generator class: This provides the methods for cryptographic operations. KeyGenerator objects are reusable, i.e., after a key has been generated, the same KeyGenerator object can be re-used to generate further keys. This class is imported as javax.crypto.KeyGenerator.

2)      generateKey (): This is a static method of the Key Generator class, which is used to generate a secret key using a key for an AES algorithm.

3)      Cipher class: This class provides the cryptographic cipher for encryption and decryption of data. This class forms the base for the Java Cryptographic Extension (JCE) framework. This class is imported as javax.crypto.Cipher.

To create a cipher object, the application calls the Cipher’s getInstancemethod, and passes the name of the requested transformation to it.

A transformation is a string that describes the operation to be performed on the given input, to produce some output. A transformation always includes the name of a cryptographic algorithm (e.g., AES), and may be followed by a feedback mode and padding scheme.

A transformation is of the form:

  • algorithm/mode/padding” or
  • algorithm

For example the correct transformation could be:

 Cipher cipher = Cipher.getInstance("AES/OFB32/PKCS5Padding");

As we are clear with the main concepts, let’s look at the example:

The AES algorithm:


package com.demo.crypto;

import java.security.*;

import java.security.spec.InvalidKeySpecException;

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

import sun.misc.*;

public class Cryptoalgo {

private static final String ALGORITHM = "AES";

private static final byte[] keyValue =

new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };

public static String encrypt(String valueToEnc) throws Exception

{

Key key = generateKey();

//Get the instance for AES algorithm

Cipher c = Cipher.getInstance(ALGORITHM);

c.init(Cipher.ENCRYPT_MODE, key);

byte[] encValue = c.doFinal(valueToEnc.getBytes());

String encryptedValue = new BASE64Encoder().encode(encValue);

return encryptedValue;

}

public static String decrypt(String encryptedValue) throws Exception

{

Key key = generateKey();

//Get the instance for AES algorithm

Cipher c = Cipher.getInstance(ALGORITHM);

c.init(Cipher.DECRYPT_MODE, key);

byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);

byte[] decValue = c.doFinal(decordedValue);

String decryptedValue = new String(decValue);

return decryptedValue;

}

private static Key generateKey() throws Exception

{

Key key = new SecretKeySpec(keyValue, ALGORITHM);

//Below Shown is the code for key generation for DES algorithm

// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);

// key = keyFactory.generateSecret(new DESKeySpec(keyValue));

return key;

}

}

Below shows the code to utilize the above AES algorithm:

package org.demo.crypto;

public class TestExample {

public static void main(String[] args) throws Exception {

String password = "secretpassword";

String passwordEnc = Cryptoalgo.encrypt(password);

String passwordDec = Cryptoalgo.decrypt(passwordEnc);

System.out.println("Plain Text : " + password);

System.out.println("Encrypted Password : " + passwordEnc);

System.out.println("Decrypted Password: " + passwordDec);

}

}

On running the above program you will have the output as:

Plain Text: secretpassword

Encrypted Password: U2FsdGVkX18gnSxz3QREK1HIwIphACMt5JBeQhSwf3w=

Decrypted Password: secretpassword

Hope you have a secure stuff in your application on web 🙂