Pages

Thursday, August 11, 2011

Javascript to check if variable exists

if(typeof(variablename)= = = 'undefined')
{
//do action
}

Ajax Request Using prototype.js

Prototype a Javascript framework makes life of Ajax Request as easier as ever though they are also available in Jquery but I prefer this framework infact I heard somewhere that Jquery is also based on this

All you have to do is download and include prototype.js from
http://www.prototypejs.org/

and then use the following Url
new Ajax.Request("url",
{
asynchrnous:"false";
method:post;
onSuccess: responsefunction;//(function name to which response needs to be sent)
parameters:{sum:amount,rowid:rowid},
onComplete:function(request,json){ element.hide('loader');},
onLoad:Element.show('loader')
});

function responsefunction(rsp)
{
var response =eval('(' + rsp.responseText + ')')
console.log(response)//show response in firebug
var amt=rsp.request.parameter.sum;
var name=response.Name //array which came from the json data thrown by url
}

);
//since its javascript data outputted must be json always by the url.
//rsp contains the values of all your response which comes from url

//at the url
json_encode($fetchdata);//most important to encode your data be it any file
?>

this $fetchdata comes as json in the responsefunction(rsp)

Using Xml Http Response Object

var xmlhttp
if(window.XMLHttpRequest)
{
//for IE7+,firefox,opera,safari
xmlhttp=new xmlHttp Request();
}
else
{
xmlhttp=new ActiveXobject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readystate=4 && xmlhttp.status=200)
{
//do the task from data
doc.getElementById("load1").style.display="none";
}
else
{
//do waiting task
}
xmlhttp.open("Post",'url',true);
xmlhttp.send();
}

Dynmically creating a table using Javascript and adding rows to it

For this you need to first of all define an empty html table element with an id property at least to refer to it my dummy was.
table
tr
th /th
th /th
/tr
tr
td /td
td /td
/tr
/table

Written without tags so that it is not interpreted by blog as html.

My table has a header row and a normal row

The table rows starts from index 0.You can use following code from a js file or directly on an html file.
(I recommend js file helps in re usability of code)

var tbl=document.getElementByid('tbl');
//Get the last row

var lastrow=tbl.rows.length

//since I already have a header row in my table and a row manually added so in my case //new row will be equal to last row (table length does not includes the last row)

var iteration=lastrow;
//create a new row
row=tbl.insertRow(lastrow);

//leftcell
//general text node to show the Sno's
var cellleft=row.insertcell(0);
var textnode=document.CreatetextNode(value of the node);
cellleft.appendChild(textnode);

//rightcell
//creation of a textbox node
var cellright=row.insertCell(1);
var el=document.CreateElement('input');
el.type='text';
el.name='name';
el.id='id';
cellright.appendChild(el);

you can add more columns by incrementing index in var cellright=row.insertCell(1);

One of my columns required to create a list dynamically..since I need the whole list and so I cloned the same from my first row(it was the only need for which I had to create a row manually)

To clone an element use the following
elsource=document.getElementById('list element');
eldestination=elsource.clone();
eldestination.name='new list name'
eldestination.id='new id'

So that's how we can dynamically add rows to a table....

Wednesday, August 10, 2011

Element.dispatchEvent(event) is not a function

Occurs when we use jquery and prototype framework at the same time.These 2 frameworks conflict
use the following code

$$=jquery.noConflict()

and then in each jquery code use $$ instead of $

Class 'Database_config' not found during Baking

Use
Cake Bake -app path to your app and issue resolved....

btw I have just tested this process looks a great automated process to me..will add more on it soon

Getting Previous or Next Dates in PHP

date('Y-m-d',strtotime($date +1 day));
date('Y-m-d',strtotime($date +1 month));
date('Y-m-d',strtotime($date +1 year));

Scheduling Crone Jobs from Console shells in Cakephp

I wrote a scheduler and then used the file given at
http://book.cakephp.org/view/1110/Running-Shells-as-cronjobs
to run the same as crone jobs but it wasn't that easy to proceed.

Usually webspace providers provide services to schedule crone jobs and get their output via mail from their control panel.Since my service provider provides service from a linux server so following tutorial is tried and tested on linux server however I will be glad if someone pastes their experience with windows machines as well...

So lets start from beginning I will discuss the errors faced as we proceed

1) I created a file cakeshell and copied it to vendors folder in root when I tried to run my shell I got following errors

/bin/bash^M: interpreter:No such file or directory
Solution:Remove the commented line at the top of the file cakeshell i.e

#! /bin/bash

2) Generally web space providers add php path to the system path already so in those cases we do not need -cli /usr/bin to add as parameter as given in the link however if it is not added you will need to add it.

If you are unable to find the path i.e you are getting error msg such as file not found make sure you are starting from root

Mine was as follows

/home/username/public_html/app name/vendors/cakeshell
-console /home/username/public_html/app name/app/console
-app /home/username/public_html/app name/app
-cli /usr/bin (if your php path is not added to system path else not required)

3)Make sure cakeshell and cake(in console) have permissions to execute for all

That's all create a shell and add a crone job to your scheduler on server and it will run

Database errors while running cakephp console

Failed to open stream No such file or directory

One way is to use -app /cake/app/ and then run your cakephp shell

for example if your shell name is myshell use

cake myshell -app /cake/app/(absolute/relative path to app folder)

other way round is to copy console folder in your app directory in that case simply run

cake myshell and it will work

Cannot Modify header information-headers already sent by (output started at)

Issue looked a bit awkward at first but the solution was simple

Check for spaces before and after the opening and closing tags respectively in the concerned file

PHP Convert a date to Mysql Format

For PHP 5.3.5 this works(worked on my development environment)

$orgdate=DateTime::CreatefromFormat('d-m-Y',$orignaldate);

$converteddate=$orgdate->format('Y-m-d');

In case of 5.2.4 I used the Cakephp Helper to convert the same so check your framework you might have a helper for the same for core PHP you might need to play with Date function

Here is how it went in case of cakephp

Add this line to the top of your view/controller

App::import('Helper','Time');

$time=new TimeHelper //create object of class

$data['date']='28-07-2011';

$time->format('Y-m-d',$data['date']);

worked on hosting env i.e php 5.2.4

Check in Cakephp if Flash Message has been set or not

Here is the code which helps to check if flash message has been set or not..sometimes its a need to use a default message if it is not set..

if(!($this->Session->check('Message.flash'))));

Generate Excel from PHP using Code

Many a times excel needs to be generated.People usually generate the same using screenshot method i.e first they output the text to the screen and then they map the same to Excel file which may include invalid characters many a times recently I found a good link to generate Excel using code...I successfully used it in Cakephp so I believe its also good on frameworks here is the link to the same

http://smartcoderszone.com/2010/09/how-to-generate-excel-report-with-php-and-mysql/

Sunday, June 26, 2011

Transactions Shortcut in Cakephp

Add the following functions in app/models/AppModel

function begin()
{
$db=&ConnectionManger::getDataSource
$db->begin($this);
$this->useDbConfig;
}

function commit()
{
$db->commit($this);
}

function rollback()
{
$db->rollback($this);
}

Now in you controller
Use
$this->Model->Begin()
$this->Model->commit();
$this->Model->rollback();

Cakephp:To run an ajax on page load use

$this->Ajax->remoteFunction($options);

where $options are 'url'=>controller,action
'update'=>
'with'=>Form.SearlizeElements(new array($("BillClientId")))');

Using Pear Framework in Cakephp

1. Copy the pear in the venders directory in the root(there are 2 one in app folder as well)

If you wish to use that one copy cake/config/paths to app/config/paths and change the following line

/**
* Path to the vendors directory.
*/
if (!defined('VENDORS')) {
define('VENDORS', CAKE_CORE_INCLUDE_PATH.DS.app.DS.'vendors'.DS);
}

After copying Pear now you have the framework its time to copy components

2.copy the package needed in the pear directory

Now we will create a path for our Pear package so that Cake can easily access that

For that copy cake/config/paths.php to app/config.paths.php add an entry after venders definition as follows

"define ('PEAR',VENDORS.'Pear'.DS)";

This defines a constant for PEAR path...

Now we need to set that path in our include path for that in your boot_strap file mark an entry as

ini_set("include_path",PEAR.PATH_SEPARATOR.ini_get("include_path"));

so path is now set in "include_path".

Next we need our controller to recognize this so just before start of controller or view(as per requirement)enter the following line

App::import('Vendor','Words',array('file'=>'../vendors/Pear/Numbers/Words.php'));

That's all now you can create an object of class and use it as follows

$numberconverter=new number_words();

echo $numberconverter->towords($grandtotal);

If your view is going blank on creation of object check that the import link on top of controller or view is correct.

Cakephp:send multople elements values in observe field

$options=>array('url'=>array('controller'=>'admin','action'=>'update_list'),'update'=>'divIdToUpdate','frequency'=>'0.2','with'=>'Form.serialize elements($('elementid1','elementid2,elementid3')));

echo $this->Ajax->observefield('Schedulepart',$options);

Cakephp:Image on clear Button

$this->Html->link($this->Html->image('button-clear.gif',array('alt'=>('clear',true),'border'=>'0'),array('onclick'=>"document.form.reset();return false;",'escape'=>'false)

Cakephp:Selecting Multiple Entries from a list

use the following code

$this->Form->select('Model.name',$listarray,'selectedvalue',array('multiple'=>'multiple','size'=>'5');

CakePHP:Button Image does not appear

Button Image does not appears in fact html tags are converted to escape sequences

When ever an button image is inserted tags appear as in written instead of showing image

Sunday, May 1, 2011

Fatal error: Maximum execution time of 30 seconds exceeded in

Fatal error: Maximum execution time of 30 seconds exceeded in
Faced this error while installing a PHP project on my webserver.The solution to This problem is simple Simply increase the Execution timeout in the Php.ini file till the time you are getting the error.

Search for these lines

; Maximum execution time of each script, in seconds
; http://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI
max_execution_time = 150

Bingo here you go

Thursday, February 24, 2011

Fatal error: Class 'Debugger' not found in when debug level set to 2 in core.php

Just started off with another RAD platform Cake PHP..and faced an issue so decided to share this fresh hard nut of my cake...

As I downloaded the version 2.0.0 of the Cake PHP RAD platform and copied it to my Apache's root...

And then there was a welcome message awaiting for me

Fatal error: Class 'Debugger' not found

I altered the Debugger value in php.ini file to 0 this problem went away..But I wanted the debugger level to be 2 so I started peeping into the websites for a solution and got a one liner

Add this:

App::import('Core', 'Debugger');

in app/config/bootstrap.php

I am still studying so will let you know more on this statement as I get back till now its a mere copy paste

Thursday, February 10, 2011

Items collection must be empty before using ItemsSource.

This error occurs when you try to add Children to a control which already has a item source as a result there is a lot of confusion to the parser regarding which one to choose.

Any children you add to the control are a part of its item collection consider for example

<listview margin="8,9,11,125" name="listView1" itemssource="{Binding}" minwidth="250" minheight="200" columnspan="2" rowspan="2">
<listview.view>
<gridview>
<gridviewcolumn header="ID" displaymemberbinding="{Binding Path=ID}"></gridviewcolumn>
<gridviewcolumn header="Company" displaymemberbinding="{Binding Path=Company}"></gridviewcolumn>
<gridviewcolumn header="Email" displaymemberbinding="{Binding Path=Email}"></gridviewcolumn>
<gridviewcolumn header="Website" displaymemberbinding="{Binding Path=Website}"></gridviewcolumn>
<gridviewcolumn header="Phone" displaymemberbinding="{Binding Path=Phone}"></gridviewcolumn>
<gridviewcolumn header="Address" displaymemberbinding="{Binding Path=Address}"></gridviewcolumn>
<gridviewcolumn header="Field of Development" displaymemberbinding="{Binding Path=Field}"></gridviewcolumn>
<gridviewcolumn header="Notes" displaymemberbinding="{Binding Path=Notes}"></gridviewcolumn>
</gridview>
</listview.view>
<Button Margin="0,0,-326.634,-49.995" Name="buttonReset" HorizontalAlignment="Right" Grid.Row="6" Width="99.99" Height="31.123" VerticalAlignment="Bottom" Click="buttonReset_Click">Reset</Button>
</listview>

Now here I have added a button in the last as a part of Item collection for the list view so it gives me that error

When I remove that code everything works fine.We cannot insert items and set items source at same time.

A Database WPF Application

I started fresh on WPF and decided to build an app which required storage of some kind of database.To my amaze it was a bit different than my other applications on Windows Forms.

Although the ADO .Net connectivity part was almost same there was much changes in the XML part.

Let me brief you regarding my design a bit

I have used a List view which holds a Grid View which holds my data in turn.The Grid view is a part of view property of my List view.Lets see how

<listview margin="8,9,11,125" name="listView1" itemssource="{Binding}" minwidth="250" minheight="200" columnspan="2" rowspan="2">
<listview.view>
<gridview>
<gridviewcolumn header="ID" displaymemberbinding="{Binding Path=ID}"></gridviewcolumn>
<gridviewcolumn header="Company" displaymemberbinding="{Binding Path=Company}"></gridviewcolumn>
<gridviewcolumn header="Email" displaymemberbinding="{Binding Path=Email}"></gridviewcolumn>
<gridviewcolumn header="Website" displaymemberbinding="{Binding Path=Website}"></gridviewcolumn>
<gridviewcolumn header="Phone" displaymemberbinding="{Binding Path=Phone}"></gridviewcolumn>
<gridviewcolumn header="Address" displaymemberbinding="{Binding Path=Address}"></gridviewcolumn>
<gridviewcolumn header="Field of Development" displaymemberbinding="{Binding Path=Field}"></gridviewcolumn>
<gridviewcolumn header="Notes" displaymemberbinding="{Binding Path=Notes}"></gridviewcolumn>
</gridview>
</listview.view>
</listview>

Now if you see above ItemsSource="{Binding}" is the crux of this binding.It tells that the List view View data come from a binding source.What Happens if I add a control to my listview.I tried it got an error which I will discuss in my next post.

Mean while My code behind file has the following code

SqlConnection con = new SqlConnection(@"Data Source=PC\SQLEXPRESS AttachDbFilename=|DataDirectory|\JAMS.mdf;Integrated Security=True;User Instance=True");
con.Open();
try
{
SqlCommand comm = new SqlCommand("SELECT ID, Company, Email, Website, Phone, Address, Field, Notes FROM JAMS_Companies", con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
Console.Write("Blah");
Console.Write(dt.Rows[0][0].ToString());
listView1.DataContext = dt.DefaultView;
}
catch (Exception e)
{
Console.Write(e.ToString());
}

As usual dt is bound to the list view.

Now I am trying to add a button to this Window.I will get back as soon as I get Success

Visual Studio 2008,WPF application,Events button(yellow lightning) not visible

A very Small problem but sometimes leads to extra efforts as you can't select between the known events in Solution.

To solve this issue update your VS 2008 with Service Pack1

To download click here

http://www.microsoft.com/downloads/en/details.aspx?FamilyId=FBEE1648-7106-44A7-9649-6D9F6D58056E&displaylang=en

Tuesday, February 8, 2011

Use of sn Strong Names

GAC is Global access cache sometimes I also heard it as Global Assembly cache.
GAC is used particularly when a dll or assembly is needed by many programs and that requires some Administrative security rights to work.In this case that dll is placed under "C:/windows/Assamblies/GAC" depending on the type of GAC folder When I dir my "C:/windows/assembley" folder I get following GAC's
  1. GAC
  2. GAC_32
  3. GAC_MSIL
Since GAC stores assemblies common to all problem of DLL HELL can occur which means two different apps with requirement of same dll with different versions may not be able to work simultaneously. Since their requirement is of only1 concerned dll and only 1 version of a dll can be present at a time in GAC.

This problem is solved using sn or Strong Naming where a hash value of dll is taken and is decoded using a private key and a public key is added to the resultant information or to its name.
Thus multiple versions of same dll can be used with different public keys.

This can be seen here in the below figure

Here if you see in the end there is a dir in the end with name 2.0.0.0__b77a5c561934e089 the first part here implies the version and second part implies the public key.
We can also create Strong Names of our own dll's a tool called gc.exe comes with Visual studio for that purpose I will cover the use of that tool in my next post.

Saturday, February 5, 2011

Could not write value to Key in registry during installation in windows server 2003


I am using Windows 2003 server sp2 protected with Mcafee Enterprise edition antivirus recently I faced an issue during installation of programs like Microsoft Office or VS 2008.I thought it had to do with security in windows that is why it is unable to access.But to my amaze I wasn't installing any 3rd party software it was all Microsoft.My doubts raised on my antivirus

I went to the antivirus console and turned off Access protection as shown in the image and it solved my problem

Wednesday, February 2, 2011

Running Joomla and Apache on same machine

I am using Win 7 iis7.Recently I installed Wamp just to try a hand on PHP.But to my amaze when I started off with my localhost It was showing iis7 content.

I figured out the problem that port 80 was configured with IIS so it could not bee allocated to Apache.

You can test this on Wamp by left clicking on Wapm icon in taskbar goto services and test port 80.

And a command window popper up showing that it was in use by Microsoft IIS.So I gave my Apache a first Aid

I just changed the port under the httpd.conf.Here is how I did it

Find a test called "Listen 80" in httpd.conf which is Apache's configuration file and change its value to "Listen 85"

Now your localhost url will be as follows

for Apache

http://localhost:85/

And for IIS

http://localhost or http://localhost:80

Browsers by default listen to port 80.

That's it

Saturday, January 29, 2011

Configuring Sql 2005 for remote connecions

I added a server machine and created a small home network. I tried to connect but recieved the following error message

TITLE: Connect to Server
------------------------------

Cannot connect to GAURAV-PC.

------------------------------
ADDITIONAL INFORMATION:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=2&LinkId=20476

------------------------------
BUTTONS:

OK
------------------------------

The instance name as specified in the error to check was very correct but the other point had some doubts whether my SQL server on server machine is configured for remote SQL connections or not in fact it was not....

This is the best guide I got to resolve this issue

http://support.microsoft.com/kb/914277

Microsoft SQL Server 2005 Error 5120 while attaching a Database

Recently I migrated from Windows XP to windows 7 and with that migrated my SQL server 2005 and my Visual Studio 2005.And of course my local databases.
I installed a fresh copy of windows 7 added Sql server 2005 to it. The problem occurred while I was attaching my old Databases to my fresh copy of Sql server.

The error was as follows

TITLE: Microsoft SQL Server Management Studio Express
------------------------------

Failed to retrieve data for this request. (Microsoft.SqlServer.Express.SmoEnum)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&LinkId=20476

------------------------------
ADDITIONAL INFORMATION:

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.Express.ConnectionInfo)

------------------------------

CREATE FILE encountered operating system error 5(error not found) while attempting to open or create the physical file 'F:\Learning Projects\Product Catalouge Application\catelouge\App_Data\Products.mdf'. (Microsoft SQL Server, Error: 5123)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=09.00.4053&EvtSrc=MSSQLServer&EvtID=5123&LinkId=20476

------------------------------
BUTTONS:

OK
------------------------------


At first it looked to be a big error but after a bit of research I found this issue to be the tiniest one I ever faced. Windows 7 security features were coming i between

Just start SQL Server in Administrator mode and you will come out of this error.
Let me know if you are still facing problems.

Tuesday, January 25, 2011

How to Configure ASP.Net Membership Providers on our own databases

By default, the required tables and stored procedures will be created in aspnetdb database.

To create the required tables and stored procedures for the SqlMemberShip provider in our own database, use a tool called as aspnet_regsql.exe packed with the ASP .Net Framework.

This tool is known by the Name ASP.Net Sql server registration tool.

To invoke this tool, type aspnet_Regsql in visual studio command prompt. It will open a wizard which will takes us through a series of steps where we can provide information about the database to create the required objects. Refer to the link below for more information

http://www.codedigest.com/FAQ/16-How-to-Configure-ASP-Net-Membership-Providers-to-Use-Our-Own-Database-.aspx