Category Archives: Technologies

Added valid date validation in jQuery validator


Hi,
Recently I got lots of error on mobile page, where I cannot give a nice date picker.
I use jQuery validator for form validations, but its date validation is not validating valid date.

If you use the new Date() function with 32nd as date, then it takes next month’s date.

I came up with adding more validations in default date validation method.

(function($) {
	/*
	 * This is a date validation fix,
	 * Because earlier it was validating invalid dates like '12//2/12' or '04/31/2012'
	 */
	/*
	 * Edit 1: Added year range: 1012 is invalid year, SQL datetime range is 1/1/1753 TO 12/31/9999
	 */
	 $.validator.addMethod("date", function(value, element) {
		return this.optional(element) || (/^\d{2}([\/])\d{2}\1\d{4}$/.test(value) && !/Invalid|NaN/.test(new Date(value)) && parseInt(value.match(/^\d{2}/)) == (new Date(value).getMonth()+1) && parseInt(value.match(/\d{4}/)) > 1752);
	});
})(jQuery);

Save the above code in one js file e.g. jquery.validate.datefix.js and include it after you include jQuery validator js.

Managing ColdFusion code formatting


Hi all!

Since I use eclipse as ColdFusion editor, I have installed cfeclipse plug-in for ColdFusion.

I got two issues which makes me writing this blog post. One is slowing down editing of large file in cfeclipse and proper code formatting which improves readability.

Since cfelipse is now providing more features, eclipse is now taking more time and gives a slow response in typing. My project has some files with more that 1200 lines to 10k lines! So eclipse becomes time-consuming if we try to edit those files.

cfmodule and cfinclude are two options that can be used to reduce the file size by splitting main file by your functionality. But if you are still stick and you don’t want to use them, then you can use notepad++ for those files.

Most of the ColdFusion guys aware of Notepad++’s plugin for ColdFusion. It is simply great! But Notepadd++ and its plug-ins are not yet compared with eclipse with efclipse.

I reviewed my files and those files are also having leading spaces in code indentation. I think tab is the best way to have white spaces for code indentation, because if you can move cursor with your keyboard’s arrow keys faster than if we have spaces. It can also reduce number of characters of your file.

Recently cfeclipse’s update provides color formatting for variable scopes and color formatting within cfscript tag.
They are now also providing css, JavaScript and SQL code formatting as well as. But the main issue is we do not need newline for each ColdFusion tag. For example:

<input type="checkbox" name="mycheckbox" <cfif form.mycheckbox EQ 1>checked</cfif>/>

So auto code formatting with Ctrl+Shift+F will not give you nice and intelligent output.

So I decided to remove leading spaces with tab characters, without using auto code formatter.

To see the tab and space characters, just enable the “Show symbols” option.

notepad-optionWhat my logic is to find all leading spaces and replace 4 spaces with one tab character.

space-issueRun this code with providing your large file which has mix of spaces and tab in code indentation and see the output!

<cfif FileExists("#ExpandPath('/codeformatter_out.cfm')#")>
	<cffile action="delete" file="#ExpandPath('/codeformatter_out.cfm')#"/>
</cfif>
<cfloop file= "#ExpandPath('/codeformatter_source.cfm')#" index="theLine">
	<cfset ret = ReFind("^[ \t]+",theLine, 1, true) > <!--- RegEx to file leading spaces (tab+spaces) --->
	<cfif ret.len[1] GT 0>
		<!--- Find space count --->
		<cfset totalspace = len(rereplace(left(theLine,ret.len[1]),'[^ ]+',"","all"))>
		<!--- Find tab count --->
		<cfset totaltab = len(rereplace(left(theLine,ret.len[1]),'[^\t]+',"","all"))>
		<!--- 4 space should be converted to 1 tab --->
		<cfset totalnewtab = ceiling(totalspace / 4)>
		<!--- Calculate total tab to set --->
		<cfset finaltab = totaltab + totalnewtab>
		<!--- Create tab string to replace --->
		<cfset tabStr = "">
		<cfloop from="1" to="#finaltab#" index="i">
			<cfset tabStr = tabStr & "	">
		</cfloop>
		<!--- Replace leading spaces with our tab string --->
		<cfset theLine = ReReplace(theLine,"^[ \t]+",tabStr)>
		<!--- Remove trailing spaces --->
		<cfset theLine = ReReplace(theLine,"[ \t]+$",'')>
	</cfif>
     <cffile action="append" file="#ExpandPath('/codeformatter_out.cfm')#" output="#theLine#"/>
</cfloop>

Search opening square bracket in SQL query with LIKE operator


Hi,

In my previous post, I’ve identified an issue of file name with square bracket in Amazon S3 URL wasn’t opening in FireFox.

So my next job was to rename the files, and update the path in database.

I wanted to search how many path has ‘[‘ or ‘]’ bracket in file name (consider attachment as SQL table column name for convenient).

I wrote like:

WHERE attachment LIKE '%[%'

But this will not work. When I see MSDN link I came to know that % and [ are used as wild card characters, and I mixed them!!

Then I thought escaping it might work

WHERE attachment LIKE '%\[%'

Silly huh! finally I came up with following:

WHERE attachment LIKE '%[\[]%'

Problems, tips and tricks about Magento


Hello friends,

I am new to Magento. I find many configurations that has to be done before you make your Magento site live. So I though I should list out all important configurations at one place so that this list can also be used as checklist as well as tips and tricks for new Magento developers.

  • Install Magento on XAMPP
    Magento requires itself to be installed on a host name with at least one period ‘.’ in it, therefore installing to http://localhost doesn’t work. So, before you install it on your local machine, you should update your host file and add some domain name. For e.g. magento.local. In windows normally host file is located at C:/Windows/System32/drivers/etc/hosts location. In Linux it may be in /etc/hosts. Please refer this wiki page for more about Magento on XAMPP and WAMP. The only important section is note in that wiki page.
  • Linux/Ubuntu installation error: curl not enabled
    Please install php5-curl module. e.g. For Ubuntu “sudo apt-get install php5-curl”
  • Linux/Ubuntu installation warning: “Your web server is configured incorrectly. As a result, configuration files with sensitive information are accessible from the outside. Please contact your hosting provider.”
    To solve this issue, modify Apache site configuration from “AllowOverride None” to “AllowOverride All”
  • Installation warning: The URL “http://yourdomainname.com.local&#8221; is invalid.Response from server isn’t valid
    Domain name probably not pointing to your installation directory, try to update server host file and add your domain name to point to localhost IP.
  • Select correct time zone while you install Magento
    Please refer to this forum.
  • Use a better way to customize your site
    There are some good tips from community to turn off some Magento blocks here. Please go through that. I’d also like to refer this blog post. This will help you a lot.
  • Changing default logo and other important settings
    There is another nice wiki page here, that will some good points while you customize your Magento site.
  • Fix about Magento Admin notification issue
    It has been solved in Latest Magento version 1.7, but if you have previous versions you’ll notice an issue described in this forum.
  • Setting up cron
    To set up cron please refer this Magento wiki page. Ideally you should set cron to run every 5 minutes.
  • Make sure SEO is enabled
    To check it, go to System -> Configuration -> General -> web -> Search Engine Optimization
  • Make cron settings for currency conversion rate
    I was having a case where currency was listed in Magento but I was not able to get the conversion rate. Please refer this wiki page.
  • Setting up log cleaning
    By default log cleaning is not enabled, so you must need to configure it, other wise your database will grow surprisingly.
    To configure it, go to System -> Configuration -> Advanced -> System -> Open Log cleaning section. Please note that, this will be triggered by Magento cron job, so you must have to configure cron job for Magento. Please read more about log cleaning in this blog post.
  • Upgrading Magento to higher version
    Go to System -> Magento connect -> Magento connect manager. login with admin credentials. Then, go to section with name “Manage Existing Extensions” and click the button that says “Check for Upgrades”. To upgrade all Magento core extensions, just select “Mage_All_Latest” and select the upgrade action (only available if new version is available) and then click on commit changes button. Similarly your can also upgrade any other extension that you installed on your website.
  • Add CMS page links to top navigation
    Please refer to my previous post.
  • Moving Magento from One server to another
    This wiki page covers two methods to migrate Magento site from one server to another. From my point of view second method is more appropriate. Here are the steps that you can perform.

    1. Take back up of database and website files.
    2. Export data from old MySQL server
    3. Create new database on new server and import data that we’ve downloaded from old server.
    4. Table core_config_data has rows that need to be changed and updated with the new url.
      path:                       value:
      web/unsecure/base_url       http://[you_domain_here]/
      web/secure/base_url         https://[your_secure_domain_here]/
    5. Download all files from old server and upload it to new server
    6. Delete /var/cache and /var/session directory
    7. Modify /app/etc/local.xml file to update new database information
    8. Make sure that /var and /media should have read/write permission with recursive
    9. All is done! Now browse the new server
  • Add currency dropdown on top of the page
    Modify your local.xml file and add following code between the default tag:

     <reference name="header">
    <block type="directory/currency" name="store_currency_selector" as="store_currency_selector" before="top.menu" template="directory/currency.phtml"/>
    </reference>
    
  • Change three column layout to two column layout and update grid column count
    Modify your local.xml file and it should contains tags shown as bellow:
  •  <?xml version="1.0"?>
    <layout version="0.1.0">
    <default>
    <reference name="root">
    <action method="setTemplate"><template>page/2columns-left.phtml</template></action>
    </reference>
    </default>
    <catalog_category_default>
    <reference name="product_list">
    <action method="setColumnCount">
    <count>4</count>
    </action>
    </reference>
    </catalog_category_default>
    <catalog_category_layered>
    <reference name="product_list">
    <action method="setColumnCount">
    <count>4</count>
    </action>
    </reference>
    </catalog_category_layered>
    <catalogsearch_result_index>
    <reference name="root">
    <action method="setTemplate"><template>page/2columns-left.phtml</template></action>
    </reference>
    <reference name="search_result_list">
    <action method="setColumnCount">
    <count>4</count>
    </action>
    </reference>
    </catalogsearch_result_index>
    </layout>
    
  • Add Facebook, twitter, Google plus buttons
    AddThis simplifies social sharing. You can get the Magento extension for AddThis from here.
  • Remove Email to friend link
    Go to System -> Configuration -> Catalog -> Email to a Friend -> Email templates -> Change Enabled to No
  • Add Banner slider
    Banner slider is a well known tool that you can use. To solve the issue of adding new slider image, please refer to this forum post.
  • User your SMTP server to send emails
    This extension will help you if your localhost is not allowed to send emails and even if you want different SMTP server.
  • 404 Page not found error when using newly installed extension
    logoff and login will solve that issue.
  • Email sending issue
    If you get an error like “Warning: Illegal offset type  in /lib/Zend/Mail.php on line 574”, Please refer to this and this post.
  • Solve issue of Service Temporarily Unavailable Magento
    Refer to this page.

Classic ASP SQL injection prevention by using query parameter


Hello friends,

Recently I got a client email that his site is affected by malware and Trojan virus. Google safe browsing tool and other firewall security gateway was blocking some of the site URLs.

Site was written in classic asp long ago by other company. When I look into the file contents, no files were modified. Normally if hackers get the ftp details then they modify files and add some iframe code that will load other virus affected sites. But this wasn’t case here. So there may be a case of SQL injection. When I looked into database tables, I found some of the fields with having some html code. That html code was loading other sites which are virus infected. Our site is not allowing anyone to add/edit records, however records were modified. This was done by SQL injection using query string parameter.

I looked into some of the pages, and I found page that lists records and records were filtered by some condition and by query string parameter.

In classic asp, most of the developers write an SQL query like following:

sql = " SELECT * FROM table WHERE id = " & Request("id") 

Executing such query easily opens a way for SQL injection. We must need to validate the variables used in SQL query.

Fortunately, we can do it by adding parameters in SQL query. Basically we need to create ADODB command object. A detailed example is show bellow:

<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Your connection string"

set cmd = server.createobject("ADODB.Command")
sql = " SELECT * FROM table WHERE id = ? or name like ?"

cmd.ActiveConnection = conn
cmd.CommandText = qText
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900
cmd.Parameters.Append cmd.CreateParameter("@id", adInteger, adParamInput, ,request("id"))
cmd.Parameters.Append cmd.CreateParameter("@name", adVarchar, adParamInput, 50, "%" & request("name") & "%")

set rs = cmd.Execute

Set rs = Nothing

Set conn = Nothing
%>

Also note that, when you add or append a parameter, name is not much important. Parameter position is the important thing. First ? mark will be replaced by first parameter and second ? mark with second parameter.

Please note that here we have used some VB constants. You need to declare them somewhere. You can include this asp file on the top of your page.

Android – Simple XML DOM Parser Example for Reading Response From InputStream


Hi,

I am trying to use simple XML DOM Parser for my HTTP response.

Basically I am calling .Net webservice and I need to parse response.

Let me also cover calling the .Net webservice.

Webservice can be called/consumed by may way.
For Example:

Use SOAP call, HTTP Get method, HTTP Post method and many more..

I have one Web service method with Post call structure:

POST /api.asmx/validateCredentials HTTP/1.1
Host: api.mywebsite.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length

username=string&password=string

Now I want to call it from Android HTTP Post method.
I will also need BasicNameValue pair for sending data to web service URL.

I’ll do it like:

try {
	HttpClient httpClient = new DefaultHttpClient();
	HttpContext localContext = new BasicHttpContext();
	HttpPost httpPost = new HttpPost("http://api.mywebsite.com/api.asmx/validateCredentials");

	List<NameValuePair> nvps = new ArrayList<NameValuePair>();

	nvps.add(new BasicNameValuePair("username", username));
	nvps.add(new BasicNameValuePair("password", password));

	httpPost.setEntity(new UrlEncodedFormEntity(nvps));

	HttpResponse response = httpClient.execute(httpPost, localContext);

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

Now First of all I wanted my response as String.

So I use Buffer reader to read the data from response object.

BufferedReader reader = new BufferedReader(new InputStreamReader(
		response.getEntity().getContent(), "UTF-8"));
StringBuffer responseString = new StringBuffer("");
String line;
while ((line = reader.readLine()) != null) {
	responseString.append(line);
}
System.out.println(responseString.toString());

Now I can see the response in LogCat.
I get the XML response (in String) as follow:

<?xml version="1.0" encoding="utf-8"?>
<returnMessage xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.myserver.com/">
	<responseCode>S000</responseCode>
	<message>User Authenticated</message>
	<extendedMessage>
		The user's credentials were valid and is authorized to execute this transaction.
	</extendedMessage>
	<userno xsi:type="xsd:double">211</userno>
</returnMessage>

Here you can see some tags and actually we need those values!!

So I can now use this “String” object to parse the XML.

To parse the XML we have several methods like SAX parser, DOM parser XML pool parser etc.

I heard that SAX parser is best, I had also used that one, But here I will go with Simple DOM parser.

So Instead of getting the response in String as above, I can directly use InputStream for DOM parser.

InputStream in = response.getEntity().getContent();

DocumentBuilder builder = DocumentBuilderFactory.newInstance()
		.newDocumentBuilder();
Document doc = builder.parse(in);
String responseCode = "";
String extendedMessage = "";
if (doc != null) {
	NodeList nl = doc.getElementsByTagName("responseCode");
	if (nl.getLength() > 0) {
		Node node = nl.item(0);
		responseCode = node.getTextContent();
	}
	nl = doc.getElementsByTagName("extendedMessage");
	if (nl.getLength() > 0) {
		Node node = nl.item(0);
		extendedMessage = node.getTextContent();
	}
}
System.out.println(responseCode + " " + extendedMessage);

I hope this post can help some one who wants to get started with Android in just 10 minutes!

Bug – count() function in ColdFusion query of query


Hi,

It has been a great time since I started working on ColdFusion. I must say that it is the easiest language in the world and yet it is a powerful and can be compared to any major programming language.

In last few days, I was using ColdBox and MockBox framework in our current project. I was using query of query which is very similar to SQL query, and we can use it over query object in ColdFusion.

Count() is a math function, but if we use it with select statement like count(*), it returns a number of rows fetched in select query. I used it query of query, and it was giving me the correct count if my select statement is returning some rows, but if it is not returning any row then ideally it should give 0 as output, but it gives [empty string].

I must need to come out of this issue, and I used a recordCount property of returning object, but you can also use CodlFusion function val() to convert the empty string to 0.

I can state that it is a bug base on the answer I get from the community. See my question on Stack Overflow Community. Still I will wait for some time if it is appropriate I’ll report it to ColdFusion bug tracking system.