Header Ad

Tuesday, June 15, 2010

Parsing XML string or content using java code

The following program is an example for parsing the XML string using code.

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLParse {
  public static void main(String arg[]) throws Exception{
    String xmlRecords = "A"
        "";

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("employee");

    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Elementnodes.item(i);

      NodeList name = element.getElementsByTagName("name");
      Element line = (Elementname.item(0);
      System.out.println("Name: " + getCharacterDataFromElement(line));

      NodeList title = element.getElementsByTagName("title");
      line = (Elementtitle.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }

  }

  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterDatachild;
      return cd.getData();
    }
    return "";
  }
}

Friday, June 11, 2010

How to load Base URL in CMS page of Magento

The following code will show the base url in CMS pages of Magneto when it executes.


{{store url=""}}

Wednesday, May 19, 2010

Unable to login into Customer Account in Magento

Update the following code inMage.php
changed this,
Mage::register('original_include_path', get_include_path());
to
Mage::register('original_include_path', '');

Wednesday, May 12, 2010

Reading CSV using java program

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.StringTokenizer;

public class ReadCSV {

//readCSV class starts here

public static void main(String args[]) throws IOException

{ //main method starts

String fName = "test1.csv";//csv file which u wanna read

String thisLine; //string variable which take each record at a time

int count=0; //to count no. of records

FileInputStream fis = new FileInputStream(fName);
//A FileInputStream obtains input bytes from a file in a file system

DataInputStream myInput = new DataInputStream(fis);
/*data input stream lets an application read primitive Java data types
from an underlying input stream in a machine-independent way*/

while ((thisLine = myInput.readLine()) != null)
{ //beginning of outer while loop
StringTokenizer st =new StringTokenizer(thisLine,",");
while(st.hasMoreElements()){
String field = st.nextToken();
System.out.print(field+", ");
}
System.out.println();

} //ending of outer while loop
} //main method ends
} //readCSV class ends here

Tuesday, May 4, 2010

Wiky aboout Magento

Hi All,

Recently i came across one of the useful links about Magento Wiki. This will be helpful to all. Please look into this.

http://en.wikipedia.org/wiki/Magento

Magento Backend Tour

Magento Front-end Tour

Tuesday, April 27, 2010

Enabling log in Magento

We can enable the log in Magento. We need to follow the below steps to enable the log.

Login into the Admin panel
Select System -> Configuration
Select Developer tab from left hand side of the page
In that, select Log Settings tab
Enable - Yes and click on Save Config

How to resize an image in JAVA or Thumbnail creation in Java

package com.jiva.bean.javabeans;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import javax.swing.ImageIcon;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.Container;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.io.BufferedOutputStream;
import com.sun.image.codec.jpeg.JPEGEncodeParam;

public class ImageResize
{
int setWidth;
int setHeight;
com.jiva.application.auth.AppSession appSession;
public void setWidth(int width)
{
setWidth=width;
}
public void setHeight(int height)
{
setHeight=height;
}

public String imageProps(String path) throws FileNotFoundException, IOException
{
File source=new File(path);
Image inImage = new ImageIcon(source.getAbsolutePath()).getImage();
int imageWidth=inImage.getWidth(null);
int imageHeight=inImage.getHeight(null);
inImage.flush();
int returnImageWidth=setWidth;
int returnImageHeight=setHeight;
double ReturnImageRatio = (double)returnImageWidth/ (double)returnImageHeight;
double ImageRatio = (double)imageWidth / (double)imageHeight;
if (ReturnImageRatio < ImageRatio)
{
returnImageHeight = (int)((double)returnImageWidth / ImageRatio);
}
else
{
returnImageWidth = (int)((double)returnImageHeight * ImageRatio);
}
String x=Integer.toString(returnImageWidth)+"."+Integer.toString(returnImageHeight);

return x;
}
public void createThumbnail(String imgFilePath,String thumbPath,int thumbWidth,int thumbHeight)throws Exception{

Image image = Toolkit.getDefaultToolkit().getImage(imgFilePath);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageHeight;
if (thumbRatio < imageRatio) {
thumbHeight = (int)(thumbWidth / imageRatio);
} else {
thumbWidth = (int)(thumbHeight * imageRatio);
}
BufferedImage thumbImage = new BufferedImage(thumbWidth,
thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(thumbPath));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.
getDefaultJPEGEncodeParam(thumbImage);
int quality = 100;
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
}
public static void main(String args[])
{
try{
ImageResize resize=new ImageResize();
resize.createThumbnail("D:/Photos/1/original.jpg", "D:/Photos/1/original_resize.jpg", 70, 70);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Random Password Generation in Java

The following program will generate the random password.

import java.util.Random;
public class AutoPwdGenerator {

public String gen8DigitPwd()
{
String strPassword="";
try{
Random randomPassword = new Random();
int i=randomPassword.nextInt(10);
int j = randomPassword.nextInt(100);
int k = randomPassword.nextInt(100);
int l = randomPassword.nextInt(10);
int m = randomPassword.nextInt(10);
strPassword=i+"T"+j+k+"P"+l;
System.out.println("Auto generated password"+strPassword);

}catch(Exception e)
{
e.printStackTrace();
}
return strPassword;
}

}

public class AutoPwdGeneratorTest
{
public static void main(String args[])
{
AutoPwdGenerator autoGen = new AutoPwdGenerator();
String randomPwd = autoGen.gen8DigitPwd();
System.out.println("Generated Random Password:"+randomPwd);
}

}

Monday, April 26, 2010

How to change Pdf logo in Magento

Login into the Magento admin panel

Select System -> Configuration -> Sales

In that select the Invoice and Packing Slip Design. In that upload the logo images.

how to change pdf font & styles in magento

All the Pdf which are related to the order is available in the following location.

/app/code/local/Mage/Sales/Model/Order/Pdf/

We can edit the invoice pdf font & styles in magento. Please follow the below inorder to successed the changes.

Page format: The default invoice PDF is set up in the A4 format. To set it for letter in /app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php

change

$page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);

to

$page = $pdf->newPage(Zend_Pdf_Page::SIZE_LETTER);

Friday, April 23, 2010

Java Script Regular Expressions

The following are the some of the java script regular expressions.

var Integer =/^[\-]?\d*$/;
var PositiveInteger =/^\d*$/;
var RealNumber = /^[\-]?\d*$|^[\-]?\d*\.\d*$/;
var PositiveRealNumber = /^\d*$|^\d*\.\d*$/;
var Currency = /^[\-]?[\$]?[\-]?\d+$|^[\-]?[\$]?[\-]?\d+\.\d*$|^[\-]?[\$]?[\-]?\d{1,3}(,\d{3})*\.\d{0,2}$/;
var Currency$ = /^[\-]?[\$]?[\-]?\d*$|^[\-]?[\$]?[\-]?\d*\.\d*$|^[\-]?[\$]?[\-]?\d{1,3}(,\d{3})*\.\d{0,2}$/;
var PositiveCurrency = /^[\$]?\d*$|^[\$]?\d*\.\d*$|^[\$]?\d{1,3}(,\d{3})*\.\d{0,2}$/;
var PositiveCurrency$ = /^[\$]?\d*$|^[\$]?\d*\.\d*$|^[\$]?\d{1,3}(,\d{3})*\.\d{0,2}$/;
var GeneralNumber = /^\d*$|^\d*\.\d*$/;
var FixedNumber = /^\d*\.\d*$/;
var StandardNumber = /^\d{1,3}(,\d{3})*\.\d{2}$/;
var Percentage = /^\d*$|\d{1,3}(,\d{3})*\.\d{1,3}[\%]?/;
var Alphabet = /^\b[a-z\s\.]*$/i
var Address = /./
var CreditCardNo = /^[0-9]{16}$/;
var AlphaNumeric = /^[a-z_0-9\s]*$/i
var Phone = /^\d{10}$|^\d{3}\-\d{3}\-\d{4}$/;
var LongPhoneFormat = /^\d{10}$|^[\(]?\d{3}[\)]?[\-\s]*\d{3}[\-\s]?\d{4}$/;
var StandardPhoneFormat = /^\d{10}$|^\d{3}[\-\s]{1,2}\d{3}[\-\s]?\d{4}$/;
var ZipCode1 = /^[0-9]{5}$/;
var ZipCode2 = /^[0-9]{4}$/;
var Email = /^[a-z_0-9]?[a-z_0-9\.\-\']+@[a-z_0-9\.\-]+\.[a-z_0-9]{2,3}$/i
var MultiEmail =/^[a-z_0-9\@\.\,\;\:\#\']$/i
var SSN = /^\d{3}[\-\s]*\d{2}[\-\s]*\d{4}$/;
var DateOfBirth=/^\d{2}[\\\s]*\d{2}[\\\s]*\d{4}$/;
var urlPattern = /^(?:(?:ftp|https?):\/\/)?(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)+(?:com|edu|biz|org|gov|int|info|mil|net|name|museum|coop|aero|[a-z][a-z])\b(?:\d+)?(?:\/[^<>()\[\]{}\s\x7f-\xff]*(?:[.,?]+[^<>()\[\]{}\s\x7f-\xff]+)*)?/;

Wednesday, April 21, 2010

Ability to retrieve products under a brand or manufacturer in MAGENTO

$brandId = "1"; //manufacturer id or brand id
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('manufacturer', array('in' => array($brandId)));
$products->addAttributeToFilter('status', '1');
$products->addAttributeToSelect('*');
$products->load();

echo "
";
foreach($products as $product)
echo $product->getId()."
";

Thursday, April 15, 2010

Unable to login into admin panel of MAGENTO.

We can overcome this problem by modifying or updating the following page.

app\code\core\Mage\Core\Model\Session\Abstract\varien.php

$this->getCookie()->getDomain(),
$this->getCookie()->isSecure(),
$this->getCookie()->getHttponly()

Comment the isSecure() and save the file.

Hope from the above changes, magento admin will work now on your localhost with the following url.

Monday, April 12, 2010

How to get product data using product id in MAGENTO

We can use the following code to get the product data using product id.
$_product = new Mage_Catalog_Model_Product();
$product_id = 535;//define the product id which you required
$_product->load($product_id);
From the above step, all the product data will be loaded in the $_product Product object. Use the following code to print the total data.
echo "

";

print_r($_product->getData());

Compressing CSS & JS Files in Magento

The following is the extension for Compressing CSS & JS Files in Magento.

click here

How to enable USPS in magento

Aside from the many unanswered questions about USPS shipping, I found ONE real gem with all kinds of reasons why USPS shipping might not work:
http://www.magentocommerce.com/boards/viewthread/10356/
1) First you register at usps.com
2) They'll email you a testing server, assuming that you are a developer. IGNORE everything about TESTING, but not the user name:
Thank you for registering for the U. S. Postal Service's Web Tools Application Program Interfaces (APIs). We are providing you with a User ID that serves multiple purposes, as explained below.
Your Username is xxxx
Your Password is xxxx
Your Web Tools User ID, shown above, is required to test and integrate USPS Web Tools APIs. With this ID, you may begin sending calls to the test server. Depending on the API, the address to the test server is either http://testing.shippingapis.com/ShippingAPITest.dll or https://secure.shippingapis.com/ShippingAPITest.dll. Use this information in combination with your User ID and your XML string to send a request to the USPS servers. For more details, refer to the programming guides (located at http://www.usps.com/webtools) for the specific API you are integrating.
A sample test request would look like: "http://testing.shippingapis.com/ShippingAPITest.dll?API=[API_Name]&XML=[XML_String_containing_User_ID]"
...
3) Unless you do want to develop something, immediately let them know that you're using Magento.
4) They'll email the REAL server
5) Then you might just add the server to the shipping setup at ...index.php/admin/system_config/edit/section/carriers/ as I did.
I just tested it and it didn't work. So I went back to the Magento thread and looking at a screenshot there, I noticed that I hadn't entered my user ID. It's been so long, I forgot what it was and I looked it up in my notes.
It STILL didn't work.
FINALLY I realized as I went through their emails that my user ID is NOT what I used to set up my online web tools account at USPS, they had sent a separate user id and pw. I'd forgotten about that and didn't put it in my notes.
So with the RIGHT user id it finally works.

Wednesday, April 7, 2010

Newsletter queue not sending in Magento

You can create a cron job to run repeatedly… or manually run them by entering this
http://www.youdomain.com/admin/newsletter_queue/sending
I noticed that when I entered the above, the number of recipients dropped by only about 20 at a time… that’s when I found the second link above. In summary, the system is programmed to send only 20 newsletters at a time! You can change that by changing a line in app/code/core/Mage/Adminhtml/controllers/Newsletter/QueueController.php
$countOfSubscritions = 20;
Replace the number 20; with any number you wish. . . and ‘yes’ the code has Subscriptions misspelled throughout - with the ‘p’ missing. I just left it misspelled and increased the number to 200.
Clearly this is not optimal and the newsletter module has some problems with it. For my first newsletter I took the steps listed above. For my second, I decided this took too much time and ended up using a 3rd party program. I’ve used ConstantContact in the past but used CampaignMonitor this time. There is a free extension to link Magento to CampaignMonitor in MagentoConnect. It worked well for me and CampaignMonitor was EXTREMELY easy to use - very clean and concise.
FYI… after I used the CampaignMonitor extension, I had to uninstall it. It seemed to be effecting my ability to save customer profiles on the frontend or backend. Now that I have all of my newsletter subscribers uploaded to CampaignMonitor, I plan on just using their code in my Magento site to allow new subscribers to sign-up and have their subscription stored on CampaignMonitor.
Perhaps someone else might have an easier solution. This was just my solution after hours and hours of frustration with Magento’s newsletter module. You can use Magento for a small list of subscribers. But I’m not sure it is the best option for larger numbers. It is definitely a module that needs some work!

Monday, April 5, 2010

Magento Video Throwback

Changing the Magento Favicon

If you’re using a default theme, the new favicon.ico needs to be uploaded into the /skin/frontend/default/default/favicon.ico directory.

For custom themes, the favicon should go into the /skin/frontend/default/CUSTOM_THEME/favicon.ico directory instead. That was simple and we have successfully updated our favicon! To view it we need to clear the browser cookies and cache and hit refresh.

Replacing the Logo Image in Transactional Emails of Magento

One important thing to note is that in the root directory, Magento has two main directories for the overall store theme, the /app and /skin directories. The /app directory contains the layout, translations for labels and terms, and templates. On the other hand, the /skin directory contains the graphical elements which are images, style sheets (CSS), and JavaScript for the blocks.

In this article, we will be using the default Magento theme. Therefore, the images we will be using will be located in the directory /skin/frontend/default/default/images. The image below shows the default logo image in the transactional email.

To replace the logo image, upload the new logo image into the images directory and rename the file as logo_email.gif, overwriting the existing image. Also, and very importantly, to ensure that the new image will show up in the transactional emails, the permissions need to be changed so that it includes read and write permissions.

Saturday, April 3, 2010

Ability to get error messages in Magento

The following code will be helpful to get error messages in magento.

$mm = Mage::getSingleton('checkout/session');

foreach ($mm->getData('messages')->getErrors() as $item){
echo $item->getCode();
}

Ability to get success message in Magento

The following code will be helpful to get the messages in magento.

$mm = Mage::getSingleton('checkout/session');

foreach ($mm->getData('messages')->getItems() as $item){
echo $item->getCode();
}

Friday, April 2, 2010

Retriving Cart Amount in Magento

The following code will be helpful to get the cart totals informaiton in magento.
$mageFilename = 'app/Mage.php';
require_once $mageFilename;

umask(0);
Mage::app();

Mage::getSingleton('core/session', array('name'=>'frontend'));

$session = Mage::getSingleton('checkout/session');

$totals = $session->getQuote()->getTotals();

Retriving Cart Items in Magento

$mageFilename = 'app/Mage.php';
require_once $mageFilename;

umask(0);
Mage::app();

Mage::getSingleton('core/session', array('name'=>'frontend'));

$session = Mage::getSingleton('checkout/session');

$output = "";

foreach ($session->getQuote()->getAllItems() as $item) {

$output .= $item->getSku() . "
";
$output .= $item->getName() . "
";
$output .= $item->getDescription() . "
";
$output .= $item->getQty() . "
";
$output .= $item->getBaseCalculationPrice() . "
";
$output .= "
";
}

print $output;

Thursday, April 1, 2010

Magento Vendor Notification

Hi,

This is one of the link which i came across in MAGENTO for vendor notification. This mighe be useful for somebody.

http://www.magentocommerce.com/extension/1193/vendor-notifications

How to get sub category id's under a category in Magento

The following code will provide the necessary steps for fetching the sub-category id's under selected category.

//this will return the category object
$_category = Mage::getModel('catalog/category')->load($categoryId);

$subcategoryIds = array();

//This will return the list of category id's under specified category
$subcategoryIds = split(",", $_category->getChildren());

Ability to get all the manufacurers or brands in Magento

We can use the following code to get the list of manufacturers in MAGENTO.

$product = Mage::getModel('catalog/product');

//Retriving the attribute values for the manufacturer id
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', 'manufacturer') // This can be changed to any attribute code
->load(false);

$attribute = $attributes->getFirstItem()->setEntity($product->getResource());

//This is an array of manufacturers
$manufacturers = $attribute->getSource()->getAllOptions(false);

How to remove test orders in Magento

There is an extension for deleting test orders

http://www.magentocommerce.com/extension/reviews/module/873

or see this
http://www.eliasinteractive.com/blog/magento-ecommerce-how-to-reset-all-test-order-information-and-set-unique-prefix-for-orders-invoices-shipments-and-credit-memos

or this one http://inchoo.net/ecommerce/magento/delete-test-orders-in-magento/

Adding new language in Magento

As anything in Magento adding a new language is something that requires a certain procedure which we will explain right now and for future reference.

Follow these easy steps and enjoy your multilingual site:

* 1. Download the desired translation thru Magento connect via admin.
* 2. Once installed Go to: System -> Manage Stores -> Create store view. Enter the data and save.
* 3. Now go to: Configuration -> Current Configuration Scope (Select your language from the dropdown) and on the right side under “Locale options” choose the desired language.

Truncate the test data in Magento

This script will start you over, remember to backup first!

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE `sales_order`;
TRUNCATE `sales_order_datetime`;
TRUNCATE `sales_order_decimal`;
TRUNCATE `sales_order_entity`;
TRUNCATE `sales_order_entity_datetime`;
TRUNCATE `sales_order_entity_decimal`;
TRUNCATE `sales_order_entity_int`;
TRUNCATE `sales_order_entity_text`;
TRUNCATE `sales_order_entity_varchar`;
TRUNCATE `sales_order_int`;
TRUNCATE `sales_order_text`;
TRUNCATE `sales_order_varchar`;
TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_order_item`;
TRUNCATE `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;

ALTER TABLE `sales_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_int` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_text` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_varchar` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
ALTER TABLE `tag` AUTO_INCREMENT=1;
ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
ALTER TABLE `wishlist` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
ALTER TABLE `report_event` AUTO_INCREMENT=1;

-- reset customers
TRUNCATE `customer_address_entity`;
TRUNCATE `customer_address_entity_datetime`;
TRUNCATE `customer_address_entity_decimal`;
TRUNCATE `customer_address_entity_int`;
TRUNCATE `customer_address_entity_text`;
TRUNCATE `customer_address_entity_varchar`;
TRUNCATE `customer_entity`;
TRUNCATE `customer_entity_datetime`;
TRUNCATE `customer_entity_decimal`;
TRUNCATE `customer_entity_int`;
TRUNCATE `customer_entity_text`;
TRUNCATE `customer_entity_varchar`;
TRUNCATE `log_customer`;
TRUNCATE `log_visitor`;
TRUNCATE `log_visitor_info`;

ALTER TABLE `customer_address_entity` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `log_customer` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1;

-- Reset all ID counters
TRUNCATE `eav_entity_store`;
ALTER TABLE `eav_entity_store` AUTO_INCREMENT=1;

SET FOREIGN_KEY_CHECKS=1;

Magento Customer Password Encryption

Magento follows the below steps to encrypt the password. This encypted passowrd will be stored in the database.

Let suppose your password will be "test123". Magento will add auto generated slot variable for this password. Let the auto-generated slot is "BJ".

The following is code for generating the hash.
echo Mage::helper('core')->getHash('test123', 'BJ');

Printed variable is the one stroed in the database.

Wednesday, March 31, 2010

Adding fields to the Contact form in Magento

This is one of the reference link for adding new fields to the Contact form in magento.

http://www.magentocommerce.com/wiki/how_to/add_fields_to_contact_form

Calculating UPS Shipping Rate with PHP

This is one of the post which i came across for calculating the UPS Shipping charges in PHP.

Please find the code at http://code.google.com/p/ups-php

Things you will need

* UPS Online Tool Account – free but requires registration
* UPS Access Key – Comes with the online tool account
* cURL – Most LAMP (Linux, Apache, Mysql, PHP) web hosts have this installed by default.
* PHP – You must know a little bit about using php. After all you are about to create a custom UPS shipping calculator.
* XML – If you know what PHP is you should know what this is. If not read about it here.
* SSH access – Many web hosts offer this. You don’t HAVE to have it but it makes troubleshooting easier.

Basically you start off by getting setup with UPS and grabbing a copy of their XML manual. Now you need to construct an XML file that will be later sent off to UPS’s server. UPS will then send a response back to you in XML format. We then use PHP to turn the XML into variables that we can use and manipulate. Even add the shipping cost into the subtotal or final checkout cost. After all, whats the use of calculating UPS shipping if you are not going to charge the user for it.

Copy the UPS PHP Function I have created into a new .txt file and name it ups.php.

Go through this function and find the parts in the XML file that are in CAPS, You will need to add your UPS shipper number, access key, username, password, departure zip, etc…

Then create another .php file and make sure to include ups.php.

It might look something like this:
view plaincopy to clipboardprint?

1. require_once("ups.php")

require_once("ups.php")

Now all you have to do to get an accurate UPS rate for a package is call the ups function.

The basic syntax for the function is:
view plaincopy to clipboardprint?

1. ups($dest_zip,$service,$weight,$length,$width,$height)

ups($dest_zip,$service,$weight,$length,$width,$height)

So, for example if you wanted to send a five pound package to Beverly Hills CA using UPS ground you would do this:
view plaincopy to clipboardprint?

1. ups(90210,03,5,5,5,5)

ups(90210,03,5,5,5,5)

Here is an already written php test file that uses the ups function.

By now you may be wondering how I know that 03 is the code for UPS ground and you also may be wondering what the code is for 2nd Day Air.

You can find all this information in the huge manual with the name dtk_RateXML_V1.zip. You can find this manual on the UPS website after you login under UPS Rates and Services Selection but to save you the time I have listed them below.
UPS Service Selection Codes

* 01 – UPS Next Day Air
* 02 – UPS Second Day Air
* 03 – UPS Ground
* 07 – UPS Worldwide Express
* 08 – UPS Worldwide Expedited
* 11 – UPS Standard
* 12 – UPS Three-Day Select
* 13 Next Day Air Saver
* 14 – UPS Next Day Air Early AM
* 54 – UPS Worldwide Express Plus
* 59 – UPS Second Day Air AM
* 65 – UPS Saver

Feel free to edit the function. The XML part of the code should be altered to fit your needs. This function only has the basic elements needed to calculate a rate. There are other attributes you can specify in the XML part of the document, such as pickup type, packaging type, etc…

Unlike some UPS Rate calculators you do not need to update the fuel surcharges or anything else. These rates come straight from UPS and are as accurate as your XML file has specified.
Troubleshooting


If it’s not working and you think you may have messed up the PHP code you can test to see if it is working by sending your XML file with curl.

Log into your host via SSH, make an xml file named RequestXML.txt. Then run this command.

curl -d @RequestXML.txt https://www.ups.com/ups.app/xml/Rate

If you want to use UPS’s testing server you can use this URL:

https://wwwcie.ups.com/ups.app/xml/Rate
Special Instructions for Godaddy


Godaddy requires a minor change in the ups function. After reading this article:

You need to have a proxy to use cURL on Godaddy.

So under this line:
“curl_setopt($ch,CURLOPT_TIMEOUT, 60);”

add this:
“curl_setopt($ch,CURLOPT_PROXY,’http://proxy.shr.secureserver

How to Import Products in Magento

There’s a little confusion among some on how to import products into a Magento ecommerce store. I spent some time today researching and trying to find the best method on doing this. The reason for my research is because there was no simple documentation anywhere that I could find on how to import products. Magento actually has built a pretty robust import/export mechanism into the ecommerce cms that has a ton of flexibility to do many things. I’m not going to cover all of those. This is just for those of you who simply just want to import products into their Magento cart.

Step 1 – Add a new product manually
add a new product manually to the catalog, assign it to a category, and fill out all fields that will be necessary to your store. The obvious ones are price, description, quantity etc. It’s important that you fill out all fields that you know you are going to need for all the products you import.

Step 2 – Export Your Products
Now we want to export your product to a .csv file so that we can view the fields that are required to import. Go to System >> Import/Export >> Profiles. Now click on Export All Products then Run Profile. Click on the “Run Profile in Popup” button. Once the export is completed, go to your var/export directory on your Magento install and you will find the .csv file there for you to download.

Step 3 – Analyze The .CSV File
Now if you look at your .csv export file you will see the field names that you need to match up. Now just start filling yours in and creating your csv file ready for import. This step is extremely important. Otherwise Magento cannot match what you are trying to import and the importing will fail. At a most basic level, here are the fields that I imported:

* store
* attribute_set
* type
* sku
* category_ids
* status
* visibility
* tax_class_id
* weight
* price
* name
* description


Step 4 – Import Your New .CSV File
Now go to System >> Import/Export >> Profiles. Now click on Import All Products. Change “Type” under Data Format to CSV/Tab Seperated. Now click on Upload File, and browse for your .csv file and click “Save and Continue Editing”. Now go to “Run Profile” and select your file from the dropdown menu. Click the button underneath to run the import. And whalllah. All your products should now be imported.

That was the easiest most simple approach that I could find for Importing Products into a Magento Open Source Ecommerce Store. Like I said I tried this myself and it worked well for me. After that, I went in and manually updated all of my Images and
Quantity numbers. You could even import those if you want to. But for
my purpose I didn’t need to.

Monday, March 29, 2010

Magento - Retrieve products with a specific attribute value

Almost all Magento Models have a corresponding Collection object that can be used to fetch multiple instances of a Model.

To instantiate a Product collection, do the following

$collection = Mage::getModel('catalog/product')->getCollection();

Products are a Magento EAV style Model, so you'll need to add on any additional attributes that you want to return.

$collection = Mage::getModel('catalog/product')->getCollection();
//fetch name and orig_price into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');


There's multiple syntaxes for setting filters on collections. I always use the verbose one below, but you might want to inspect the Magento source for additional ways the filtering methods can be used.

The following shows how to filter by a range of values (greater than AND less than)

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');


//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
array('attribute'=>'orig_price','gt'=>'100'),
));


//AND filter for products whose orig_price is greater than (lt) 130
$collection->addFieldToFilter(array(
array('attribute'=>'orig_price','lt'=>'130'),
));

While this will filter by a name that equals one thing OR another.

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');


//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
array('attribute'=>'name','eq'=>'Widget A'),
array('attribute'=>'name','eq'=>'Widget B'),
));

Saturday, March 27, 2010

Ability to Get Products under a category in Magento

Hi,

We can use the following code to get the products under a category.



$_categories=$this->getCurrentChildCategories();

$_category = $this->getCurrentCategory();
$subs = $_category->getAllChildren(true);
$result = array();
foreach($subs as $cat_id) {
$category = new Mage_Catalog_Model_Category();
$category->load($cat_id);
$collection = $category->getProductCollection();
foreach ($collection as $product) {
$result[] = $product->getId();
}

}
shuffle($result);
?>

Monday, March 8, 2010

How to find in between value from an array in javascript

Take the following code is an simple example for finding bigger value in an array


var foo = new Array("222","323","314","431","422");
var biggest = 10;
for (x=0;xif (foo[x] > biggest) {
biggest = parseint(foo[x]); //right here
}
}
document.write(biggest);