Pages

Thursday, January 2, 2014

Authorize .Net-Reading Response of Authorize.net api

Reading Error Response
 
AuthorizeNetCIM_Response Object  
 (  
   [xml] => SimpleXMLElement Object  
     (  
       [messages] => SimpleXMLElement Object  
         (  
           [resultCode] => Error  
           [message] => SimpleXMLElement Object  
             (  
               [code] => E00003  
               [text] => The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value '668988888888177645' is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.  
             )  
         )  
     )  
   [response] => ErrorE00003The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value '668988888888177645' is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.  
   [xpath_xml] => SimpleXMLElement Object  
     (  
       [messages] => SimpleXMLElement Object  
         (  
           [resultCode] => Error  
           [message] => SimpleXMLElement Object  
             (  
               [code] => E00003  
               [text] => The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value '668988888888177645' is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.  
             )  
         )  
     )  
 ) 
 Reading Error Response
 $error = (string)array_pop($response->xpath('messages/message/text'));  

Reading Success Response
 AuthorizeNetCIM_Response Object  
 (  
   [xml] => SimpleXMLElement Object  
     (  
       [messages] => SimpleXMLElement Object  
         (  
           [resultCode] => Ok  
           [message] => SimpleXMLElement Object  
             (  
               [code] => I00001  
               [text] => Successful.  
             )  
         )  
       [customerPaymentProfileId] => 21000823
     )  
   [response] => OkI00001Successful.21000823 
   [xpath_xml] => SimpleXMLElement Object  
     (  
       [messages] => SimpleXMLElement Object  
         (  
           [resultCode] => Ok  
           [message] => SimpleXMLElement Object  
             (  
               [code] => I00001  
               [text] => Successful.  
             )  
         )  
       [customerPaymentProfileId] => 21000844  
     )  
 )
 Reading Authorize .Net Success Object
 if($response->isOk())  

Wordpress-Get Post ID in functions.php

  $url = explode('?', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);  
   $ID = url_to_postid($url[0]);  
   echo $ID;  

Friday, November 29, 2013

Javascript-Fire event on resolution change

In the era of responsive websites sometimes it is needed to fire an event on change of resolution.

My designer was stuck in one such scenario and we sorted the same out as follows


 <script>  
 $(document).ready(function () {  
 var width = screen.width,  
 height = screen.height;  
 setInterval(function () {  
 if (screen.width !== width || screen.height !== height) {  
 width = screen.width;  
 height = screen.height;  
 $(window).trigger('resolutionchange');  
 }  
 }, 50);  
 }());  
 $(window).bind('resolutionchange', heightchanges)  
 function heightchanges(){  
 /*Your code on resolution change event here*/
 }  
 });  
 </script>  

HTML-Input Field that accepts only number

If you are looking for a Html Input field that accepts only number on basis of regular expression here is the code


 <input name="number"  
 onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">  

Thursday, October 17, 2013

Cakephp-Query and Cache Optimization

Recently while working for a technical client I learnt a lot of things regarding optimization of a cakephp site
which I am discussing as follows

1. Cache regularly used queries in cache.Queries regarding listing Menu's which are listed on every page footer item's,header item's should be cached.

For example if you are showing a list of categories in Menu from database.You must cache those so same query is not run again and again on same page

I cached as follows

 $mainCategories = Cache::read('Categories','long_db');  
         if (!$mainCategories)   
         {  
           $mainCategories = $this->Category->find('all', array('conditions' => array(''),'fields'=>array(''),'order'=>array('')));  
           Cache::write('Categories',$mainCategories,'long_db');  
         }  

2. In AppModel add

 public $recursive = -1;  
    function find($conditions = null, $fields = array(), $order = null, $recursive = null) {  
     $doQuery = true;  
     // check if we want the cache  
     if (!empty($fields['cache'])) {  
       $cacheConfig = null;  
       // check if we have specified a custom config  
       if (!empty($fields['cacheConfig'])) {  
         $cacheConfig = $fields['cacheConfig'];  
       }  
       $cacheName = $this->name . '-' . $fields['cache'];  
       // if so, check if the cache exists  
       $data = Cache::read($cacheName, $cacheConfig);  
       if ($data == false) {  
         $data = parent::find($conditions, $fields,  
           $order, $recursive);  
         Cache::write($cacheName, $data, $cacheConfig);  
       }  
       $doQuery = false;  
     }  
     if ($doQuery) {  
       $data = parent::find($conditions, $fields, $order,  
         $recursive);  
     }  
     return $data; 
    } 

Now what we have done here is
a. In first line we have added recursive=-1 so cake will no longer fetch 1st level relationships by default and they can be acquired by manually setting when required thus reducing over load.
b. In the second line we have added a function which will allow you to cache your queries even without writing the code in step one it automates the process as follows


 $this->User->find('list',  
   array('cache' => 'userList', 'cacheConfig' => 'short')  
 );  

This will automatically cache your query's when it finds cache and cacheConfig parameter's in find condition

Make sure following is enabled and added in "/app/Config/core.php"

 Configure::write('Cache.check', true);  
 Cache::config('short', array(  
   'engine' => 'File',  
   'duration'=> '+5 minutes',  
   'probability'=> 100,  
   'path' => CACHE,  
   'prefix' => 'cache_short_'  
 ));  


The second statement is a cache configuration defined in core.You can also set another configuration and pass the same to "cacheConfig" parameter's above like we have passed "short"

3. Bind/Unbind Model's on Fly

This requires proper requirement analysis and analyzing ERD the way it reflects on project.
One way out is that if you feel if the binding between 2 model's is required at every step

For example Menu categories and subcategories are required so it is very much feasible to join them together at the beginning only.So if at any point you require only categories you should unbind the subcategories relation.

It's very hard to judge which way to follows to Bind all model's first and then unbind on fly to taste or vice versa.I prefer a mix approach i.e. when in doubt I prefer to bind on fly rather than to load an unnecessary association on fly

Friday, October 4, 2013

HTACCESS-Add MIME Type

Sometimes some MIME types are not present in default Apache Server configurations.But we may need to add them to our server so that we can perform operation's such as gzip compression,add them to browser caching etc

Recently I came across one such issue where I had to add a font type called "woff" to the same i added the same as follows

 <IfModule mod_mime.c>  
   AddType application/x-font-woff woff  
 </Ifmodule>  

Page Speed-Enable gzip compression

Add the following code to .htaccess(preferably in root)


 # compress text, HTML, JavaScript, CSS, and XML  
 AddOutputFilterByType DEFLATE text/plain  
 AddOutputFilterByType DEFLATE text/html  
 AddOutputFilterByType DEFLATE text/xml  
 AddOutputFilterByType DEFLATE text/css  
 AddOutputFilterByType DEFLATE text/javascript  
 AddOutputFilterByType DEFLATE application/xml  
 AddOutputFilterByType DEFLATE application/xhtml+xml  
 AddOutputFilterByType DEFLATE application/rss+xml  
 AddOutputFilterByType DEFLATE application/javascript  
 AddOutputFilterByType DEFLATE application/x-javascript  
 # remove browser bugs  
 BrowserMatch ^Mozilla/4 gzip-only-text/html  
 BrowserMatch ^Mozilla/4\.0[678] no-gzip  
 BrowserMatch \bMSIE !no-gzip !gzip-only-text/html  
 Header append Vary User-Agent  

Thursday, October 3, 2013

Page Speed-Leverage browser caching

Make sure that Browser cache expire time should be at least 
1 week for consistent things. This can be reduced files that change constantly.
 
To add this add following like structure in .htaccess
(preferably root can be changed to taste in some cases)
 
 
 ## EXPIRES CACHING ##  
 ExpiresActive On  
 ExpiresByType image/jpg "access plus 1 year"  
 ExpiresByType image/jpeg "access plus 1 year"  
 ExpiresByType image/gif "access plus 1 year"  
 ExpiresByType image/png "access plus 1 year"
 ExpiresByType text/javascript "access plus 1 month"
 ExpiresByType text/css "access plus 1 month"
 ExpiresByType application/pdf "access plus 1 month"  
 ExpiresByType text/x-javascript "access plus 1 month"  
 ExpiresByType application/x-shockwave-flash "access plus 1 month"  
 ExpiresByType image/x-icon "access plus 1 year"  
 ExpiresDefault "access plus 2 days"  
 ## EXPIRES CACHING ##  

Page Speed-Specify a Vary: Accept-Encoding header


 <IfModule mod_headers.c>  
  <FilesMatch "\.(js|css|xml|gz)$">  
   Header append Vary Accept-Encoding  
  </FilesMatch>  
 </IfModule>  
If you would like to add more file type to this rule, add the its extension to the statement

Wednesday, October 2, 2013

PHP-Version Check code

 if (version_compare(phpversion(), '5.0.0', '>=') !== true) {  
   exit('This website runs with PHP5... You version is <b>' . phpversion() . '</b>.Please upgrade');  
 }