Wednesday, December 23, 2009

Javascript textfield counter

maxL = 1000;
var bName = navigator.appName;

function taLimit(taObj) {
if (taObj.value.length == maxL) {
return false;
}
return true;
}

function taCount(taObj,Cnt) {
objCnt=createObject(Cnt);
objVal=taObj.value;
if (objVal.length > maxL) {
alert("Description field has to be less than 1000 characters.");
objVal = objVal.substring(0, maxL);
}

if (objCnt) {
if(bName == "Netscape"){
objCnt.textContent=maxL-objVal.length;}
else{objCnt.innerText=maxL-objVal.length;}
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}


To update the counter at last, do something like this:
<script type="text/javascript">
taCount(document.getElementById('txtDescription'), 'myCounter');
</script>

Monday, December 21, 2009

PHP Date Convert

echo date("d/m/y", strtotime($row_sprees['issueDate'])); ?>

Monday, December 14, 2009

mySQL and msSQL Limit and TOP

SELECT TOP 10 * FROM stuff;

Will return the top ten rows, effectively doing the same thing as

SELET * FROM stuff LIMIT 10;

Saturday, December 12, 2009

Router configuration

Home network setup:
WRT300N - the router at level 1
WRT54G - the router at level 2 flashed with DD-WRT firmware, used as repeater.

The information to access the router are as follows:
level1: 192.168.1.1 (admin, admin)
Level2: 10.0.0.1 (root, admin)

Tuesday, December 8, 2009

convert url to links in C# using Regex

public string ConvertUrlsToLinks(string msg)
{
string newMsg = "";

string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
newMsg = r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");

string emailRegex = @"(([a-zA-Z0-9_\-\.]+@)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r2 = new Regex(emailRegex, RegexOptions.IgnoreCase);
newMsg = r2.Replace(newMsg, "$1");

return newMsg;
}

Monday, December 7, 2009

Java Exam Prep

int count = 0;
System.out.println(count++);
System.out.println(count++);
output: 0, 1

int count = 0;
System.out.println(++count);
System.out.println(++count);
output: 1, 2

int count = 0;
System.out.println(count++);
System.out.println(++count);
output: 0, 2

Wednesday, December 2, 2009

Tuesday, November 24, 2009

SMTP Server

To fix this, we will have to make sure that no other mailservers are running. Then we have to startup SMTP service (via services). After which, Inside Manager Server, "Manage Mail Server", "add a POP3 acccount". Use that as the default SMTP details.

Automatic Thumbnail C#

HtmlTable dTable = new HtmlTable();
dTable.Width = "500px";
dTable.CellPadding = 2;
dTable.CellSpacing = 0;
dTable.Border = 0;

int col = 5;

HtmlTableRow dTRow = new HtmlTableRow();
for (int count = 0; count < tmp.Length; count++)
{
if ((count % col == 0) && (count != 0))
{
dTable.Controls.Add(dTRow);
dTRow = new HtmlTableRow();
}
HtmlTableCell dTCell = new HtmlTableCell();
Photo result = tmp[count];
dTCell.InnerHtml = "

";
dTRow.Controls.Add(dTCell);
}

dTable.Controls.Add(dTRow);
Panel1.Controls.Add(dTable);

C# SQL Encode/Decode

public string SqlEncode(string inStr)
{
inStr = inStr.Replace("'", "''");
inStr = inStr.Replace("<", "<");
inStr = inStr.Replace(">", ">");
return inStr;
}
public string SqlDecode(string inStr)
{
if (inStr == "")
return null;

inStr = inStr.Replace("''", "'");
inStr = inStr.Replace("<", "<");
inStr = inStr.Replace(">", ">");

return inStr;
}

C# Binary Image Upload

// adapted from http://snippets.dzone.com/posts/show/1485
public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
{
System.Drawing.Image original = System.Drawing.Image.FromStream(new MemoryStream(imageFile));
int targetH, targetW;
if (original.Height > original.Width)
{
targetH = targetSize;
targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
}
else
{
targetW = targetSize;
targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
}
System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(new MemoryStream(imageFile));
// Create a new blank canvas. The resized image will be drawn on this canvas.
Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(72, 72);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);
// Save out to memory and then to a file. We dispose of all objects to make sure the files don't stay locked.
MemoryStream mm = new MemoryStream();
bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
original.Dispose();
imgPhoto.Dispose();
bmPhoto.Dispose();
grPhoto.Dispose();
return mm.GetBuffer();
}


public int uploadImage()
{
int photonum = 1;
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
string imgContentType = UploadFile.PostedFile.ContentType;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData, 0, imgLen);
byte[] imgBinaryData2 = ResizeImageFile(imgBinaryData, 200);
string imgName = UploadFile.PostedFile.FileName;
int newImageLen = imgBinaryData2.Length;
String cdate = DateTime.Now.ToString();
int RowsAffected = SaveToDB(imgName, imgBinaryData2, imgContentType, newImageLen, cdate);
if (RowsAffected > 0)
{
OleDbDataReader rdr = null;
strConnection = ConfigurationManager.AppSettings["DBKey"];
String strSQL = "SELECT img_id FROM tblImages where created_date='" + cdate + "'";
conUser = new OleDbConnection(strConnection);
if (conUser.State.ToString().Equals("Open")) { conUser.Close(); }
conUser.Open();
cmdUser = new OleDbCommand(strSQL, conUser);
rdr = cmdUser.ExecuteReader();
while (rdr.Read())
{
photonum = rdr.GetInt32(0);
}
return photonum;
}

return -1;
}

C# Binary Image Upload

// adapted from http://snippets.dzone.com/posts/show/1485
public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
{
System.Drawing.Image original = System.Drawing.Image.FromStream(new MemoryStream(imageFile));
int targetH, targetW;
if (original.Height > original.Width)
{
targetH = targetSize;
targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
}
else
{
targetW = targetSize;
targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
}
System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(new MemoryStream(imageFile));
// Create a new blank canvas. The resized image will be drawn on this canvas.
Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(72, 72);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);
// Save out to memory and then to a file. We dispose of all objects to make sure the files don't stay locked.
MemoryStream mm = new MemoryStream();
bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
original.Dispose();
imgPhoto.Dispose();
bmPhoto.Dispose();
grPhoto.Dispose();
return mm.GetBuffer();
}


public int uploadImage()
{
int photonum = 1;
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
string imgContentType = UploadFile.PostedFile.ContentType;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData, 0, imgLen);
byte[] imgBinaryData2 = ResizeImageFile(imgBinaryData, 200);
string imgName = UploadFile.PostedFile.FileName;
int newImageLen = imgBinaryData2.Length;
String cdate = DateTime.Now.ToString();
int RowsAffected = SaveToDB(imgName, imgBinaryData2, imgContentType, newImageLen, cdate);
if (RowsAffected > 0)
{
OleDbDataReader rdr = null;
strConnection = ConfigurationManager.AppSettings["DBKey"];
String strSQL = "SELECT img_id FROM tblImages where created_date='" + cdate + "'";
conUser = new OleDbConnection(strConnection);
if (conUser.State.ToString().Equals("Open")) { conUser.Close(); }
conUser.Open();
cmdUser = new OleDbCommand(strSQL, conUser);
rdr = cmdUser.ExecuteReader();
while (rdr.Read())
{
photonum = rdr.GetInt32(0);
}
return photonum;
}

return -1;
}

Form does not get value from readonly fields

To fix this, don't put readonly property for the controls by default, do it programatically. This has something to the storage of values for disabled properties. Apparently .NET does not store the value of disabled controls and hence does not pass the value on.

txtStartDate.Attributes.Add("readonly", "readonly");
txtExpDate.Attributes.Add("readonly", "readonly");

ASP.NET function calling from HTML

<%# formatColor(DataBinder.Eval(Container.DataItem, "status").ToString()) %>

Monday, November 23, 2009

HTML code for em-dash

is —

SQL Stored Procedure for Number Format

CREATE FUNCTION [dbo].[fnFormatPhoneNumber](@PhoneNo VARCHAR(20))
RETURNS VARCHAR(25)
AS
BEGIN
DECLARE @Formatted VARCHAR(25)

IF (LEN(@PhoneNo) >= 10)
SET @Formatted = LEFT(@PhoneNo, 3) + '.' + SUBSTRING(@PhoneNo, 4, 3) + '.' + SUBSTRING(@PhoneNo, 7, 4)
ELSE
SET @Formatted = @PhoneNo


RETURN @Formatted
END
GO
Use it as follows:
SELECT [dbo].[fnFormatPhoneNumber](PhoneNumber) AS PhoneNumber FROM SomeTable

Tuesday, November 17, 2009

Foreign Keys in PhpMyAdmin

Only available with innodb, set the relationships via normal 'linking' and then you can view the relationships via 'designer'.

http://www.phpmyadmin.net/documentation/#faqpdf

6.8 How can I produce a PDF schema of my database?

First the configuration variables "relation", "table_coords" and "pdf_pages" have to be filled in.

Then you need to think about your schema layout. Which tables will go on which pages?

* Select your database in the left frame.
* Choose "Operations" in the navigation bar at the top.
* Choose "Edit PDF Pages" near the bottom of the page.
* Enter a name for the first PDF page and click Go. If you like, you can use the "automatic layout," which will put all your linked tables onto the new page.
* Select the name of the new page (making sure the Edit radio button is selected) and click Go.
* Select a table from the list, enter its coordinates and click Save.
Coordinates are relative; your diagram will be automatically scaled to fit the page. When initially placing tables on the page, just pick any coordinates -- say, 50x50. After clicking Save, you can then use the graphical editor to position the element correctly.
* When you'd like to look at your PDF, first be sure to click the Save button beneath the list of tables and coordinates, to save any changes you made there. Then scroll all the way down, select the PDF options you want, and click Go.
* Internet Explorer for Windows may suggest an incorrect filename when you try to save a generated PDF. When saving a generated PDF, be sure that the filename ends in ".pdf", for example "schema.pdf". Browsers on other operating systems, and other browsers on Windows, do not have this problem.

Monday, November 16, 2009

SQL Namepipe issues

Try starting/restarting the sql server/sql server agent.

The SQL Server service terminated with service-specific error 126.
Start->All Programs -> Microsoft Sql server 2005 -> Configuration Tools -> SQL Server Configuration Manager.
In the SQL SERVER configuration Manager Window, click the plus (+) sign against SQL SERVER 2005 Network Configuration.
Highlight 'Protocols for MS SQL SERVER'
In the right pane you'd find VIA in protocol name column , you can right click it san select 'Disable'

Friday, November 13, 2009

SQL manipulating date time using CONVERT

SELECT status, event_id, title, CONVERT(VARCHAR(12),event_date,107) as edate, dbo.udf_DayOfWeek(event_date) AS DayOfWeek from tblEvent where Convert(datetime,Convert(varchar(12), event_date, 103),103) >= Convert(datetime,Convert(varchar(12), GETDATE(),103),103) order by event_date

SELECT status, event_id, title, CONVERT(VARCHAR(12),event_date,107) as edate, dbo.udf_DayOfWeek(event_date) AS DayOfWeek from tblEvent where Convert(datetime,Convert(VARCHAR(12), event_date, 103),103) < Convert(datetime,Convert(VARCHAR(12), GETDATE(),103),103) AND Convert(datetime,Convert(VARCHAR(12), event_date, 103),103) > Convert(datetime,datediff(day, 30, GETDATE()),103) order by event_date DESC

Wednesday, November 11, 2009

Unable to deploy war file

It seems that there is some permission issues with Windows Vista, if we run tomcat as administrator the problem would be solved. When deploying the .war file, make sure it is deployed within the webapp directory above ROOT. After running tomcat, the server would extract the files into a folder and then we should be able to run tomcat from then.

Sunday, November 8, 2009

Error loading feeds from flash and opening asp.net program without sln file

1. to load the xml feeds, make sure that the url is correct, then recompile it for projector mode (in exe)

2. within vs.net, create a new project and then import all the files from the other server into the folder (if you have subversion, commit it to SVN). The program should not work and should prompt errors mainly about being unable to find certain objects, even though it clearly exist.

The idea is that designer.cs file is missing for the individual document, hence you need to generate it by right clicking on the file and select the "Convert to web application" option. Sometimes if the designer file exist by default and it still throw the error, remove the designer file and try again.

empty datetime inside a datagrad

if (edate.Equals("")) {
param3.Value = DBNull.Value;
} else {
param3.Value = DateTime.Parse(edate);
}

submit form on enter key asp.net

can do so using the defaultbutton option inside asp.
form defaultbutton="button1" runat="server"

Friday, November 6, 2009

Creating user in SQL Server

INside Microsoft SQL Server Management after you login via windows authentication, select the security table and insert new user, you also need to assign userrole such as sysadmin to the user.

After that, you need to modify the properties of the connection instance to WINDOWS + SQL Server mode. Either that modify it via the Registry settings.

Creating user in SQL Server

INside Microsoft SQL Server Management after you login via windows authentication, select the security table and insert new user, you also need to assign userrole such as sysadmin to the user.

Export SQL Server to MDF

The best way to do so is by using SQL Script and not by any other methods.

To do so, simply go to the sql tools: "tasks" -> "generate script" -> remember to set the option for data export to be true.

VS.NET Namescape could not be found

Make sure that the class (which normally resides in app_code) has its build action set to compile and not just content.

Thursday, October 29, 2009

Eclipse Tips

1. To import and export WAR files. Use the default export and import function within eclipse.

2. When Eclipse has this red exclaimation mark after importing a WAR file, that means the servlet path has not been set for the project. Right click on the project > Build Path > Configure Build Path > Add External Jar > Servlet-api.jar

Tuesday, October 27, 2009

Microsoft Synchronization Framework

To synchronize two database (bidirectional), you have to place the following line within the onInit function of the code portion of the .sync file. For example:

this._giftSyncTable.SyncDirection = Microsoft.Synchronization.Data.SyncDirection.Bidirectional;

SQL Server Connection

http://www.visual-paradigm.com/support/articles/solve-sql-server-connection-problem.jsp

Ensure that inside SQL Server configuration, under SQL Network Configuration, that TCP port settings has been set. The default port is 1433.

Sunday, October 25, 2009

ASp.NET Upload

Solution file "C:\abc\abc.sln" cannot be converted because it cannot be modified. To convert the solution, change the permissions on the solution file to allow modification and reopen it".

- Make sure that the solution file is not read-only.

Thursday, October 22, 2009

Uploading file to salt folder

I was trying to create a folder within asp.net and got an error:
Access to the path 'C:\inetpub\Dream\creatives\20091023_1406\' is denied.

Basically I was trying to upload files into the newly created directory 20091023.. so to fix this, open up web.config, beneath the tag, add the following tag:

Saturday, October 3, 2009

Ink Errors

1. If you run into errors about IACore, look into the bin folder of the application folder and make sure the relevant libraries are inside there. This is true for both development and deployment environment
C:\Users\awtan\Documents\Visual Studio 2008\Projects\SilverlightInkServicesCSharp\bin

2. The architecture for pen input of salon is as follows:
a. Salon main program (which resides on gbeacon) contains an ink folder that holds the clientbin output of the MSDNMagAnnotationClient program. Hence when we call inkinput.aspx it actually calls the silverlight application from the MSDNMagAnnotationClient program.

b. As we submit the request from MSDNMagAnnotationClient (silverlight ink program), we will send a request to pragma which contains the SilverlightInkServicesCSharp WPF service. The service translates the strokes and outputs the text information.

c. The text then gets display in the MSDNMagAnnotationClient textfield. Through javascript, it communicates with the flex textfield.

Monday, September 28, 2009

tablet Input

Main article: http://msdn.microsoft.com/en-us/magazine/cc721604.aspx

Need to install:
1. Tablet PC recognizer
http://www.microsoft.com/downloads/details.aspx?familyid=080184dd-5e92-4464-b907-10762e9f918b

2. Table PC Edition SDK 1.7
http://www.microsoft.com/downloads/details.aspx?familyid=B46D4B83-A821-40BC-AA85-C9EE3D6E9699

Invalid win32

Got weird errors like: invalid win32 application.

This is due to the following scenario:

64Bit IIS7 running a 32Bit application so Enable 32Bit is set to true on the application pool
Also running as an exchange front end server and hence RPCProxy is loaded

In this scenario you might get the errors

In IE -
"HTTP Error 503. The service is unavailable."


In the event viewer-
"The Module DLL C:\Windows\system32\RpcProxy\RpcProxy.dll failed to load. The data is the error."
and
"Application pool 'xxxxxxxxx' is being automatically disabled due to a series of failures in the process(es) serving that application pool."

Essentially the rpcpoxy is trying to load into the 32bit pool. The question I have i guess is why is this dll trying to load in the first place. It's not part of my application. Anyway to fix this issue:

Edit c:\windows\system32\inetsrv\config\applicationhost.config

In the section which has add - precondition="bitness64" to the rpcproxy line so that you have the following

Subversion

Projectlocker.com offers free svn repository

If the folder to be submitted into repo already exist, do the following:
1. right click to import (this imports the existing files into SVN)
2. right click to create repository (this indexes your existing files and allows you to use SVN normally)

Wednesday, September 16, 2009

Right align/justify in textarea, java

1. Font has to be first of all changed to monospace. Using something like:
txtAreaResult.setFont(new Font("monospaced",Font.PLAIN,12));

2. When we append character to the stringbuffer, we use this method
private String rightAlign(String input, int pad) {

int length = pad - input.length();

if (length < 0)
return input.substring(0,input.length());

StringBuffer buffer = new StringBuffer(pad);
for(int i=0; i<length; i++)
buffer.append(" ");

return new String(buffer.append(input));
}

3. we can use append like this:
StringBuffer results = new StringBuffer();
results.append(rightAlign("Months", 6));

Saturday, August 22, 2009

Radio button in datagrid

Radio buttons will not work by default inside a datagrid. The selection will be individual, because the groupname/id of the control is going to be different for each role automatically. Hence we need to make use of the literal control.

1. Insert literal control instead of the radiobutton control into the datagrid
2. The idea is to find the literal control inside the datagrid
3. Replace it with a radio button control with a fix name.

Something like:

if (e.Row.RowType == DataControlRowType.DataRow)
{
Literal literal = (Literal) e.Row.FindControl("RadioButtonMarkup");
literal.Text = String.Format("<input type='radio' name='couponId' id='coupon{0}' value='{0}' />", e.Row.RowIndex);
}

Friday, August 21, 2009

Datagrid ASP.NET C#

Inside the datagrid, insert a template column with the checkbox name chkSelect. The next column should be the ID of the column you want to obtain information from.

protected void btnModify_Click(object sender, EventArgs e)
{
for (int i = 0; i < couponGrid.Rows.Count; i++)
{
GridViewRow row = couponGrid.Rows[i];
bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
if (isChecked)
{
// Column 2 is the ID column
String accessId = couponGrid.Rows[i].Cells[1].Text;
lbl.Text = lbl.Text + "haha" + accessId;
}
}
}
}

Eval("info") Eval of HTML fields in C#

If you try manipulating Eval binding tags within HTML, chances are you are not able to and you will get nasty errors. The only way to do it is to handle the process via a method. For example:

<asp:checkbox id="chkSelect" runat="server" checked="'<%#">' />

public bool checkOrNot(object id)
{
return true;
}

Thursday, August 20, 2009

Database

Select IDENTITY of the record after you insert, the XSD way.

Within the XSD file, create a new query -> create new standard procedure -> Select insert -> add a select query after the insert query, something like:

INSERT INTO [coupon] ([memberId], [categoryId], [couponCode], [couponName], [couponImage], [couponVideo], [couponSMSText], [couponExpiration], [couponDisclaimer], [couponPrice], [couponDiscount], [couponStart], [couponEnd], [couponLimit], [couponCreationDateTime], [couponStatus]) VALUES (@memberId, @categoryId, @couponCode, @couponName, @couponImage, @couponVideo, @couponSMSText, @couponExpiration, @couponDisclaimer, @couponPrice, @couponDiscount, @couponStart, @couponEnd, @couponLimit, @couponCreationDateTime, @couponStatus);SELECT couponId FROM coupon WHERE (couponId = SCOPE_IDENTITY())

After that, select the property of the query and select SCALAR mode instead of NonQuery

Tuesday, August 18, 2009

XAMPP PHP INI modifying

The only PHP.ini file that really matters is the one found in /apache/bin/php.ini.

Sunday, August 16, 2009

Pipe Problems

Gbeacon server has SQL Server Configuration Manager
http://blogs.msdn.com/sql_protocols/archive/2006/03/23/558651.aspx

Saturday, July 11, 2009

Remove Non Empty Directory

We cannot use rmdir as per traditional methods, we need to use RM with the option -rf

rm -rf /htdocs/www/dirname

Thursday, July 9, 2009

Setting up two linksys router to expand range

By default, most of the linksys router do not support repeater/bridging. But luckily the folks at DD-WRT created a router firmware so that we can use our traditional router as a repeater so that we can expand the range of our networks.

You can obtain the .bin firmware from:
http://www.dd-wrt.com/

I got into the directory v24-sp1. From which select your router. Mine is linksys and version of your router can normally be obtained from the label on your router. In which case mine is 1.1, before you proceed further, do check the 'supported hardware' page to ensure that you can actually flash your firmware of your router. If your hardware is not supported then you should not attempt to even flash it.

Get a RJ45/Ethernet cable, armed with the Firmware and you are good to go.

FIRST PART
------------------------------------------------------------------
On the end of the second router (this is not the REPEATER)
1. Plug your RJ45 cable from your computer (with the firmware) to the router
2. Login http://192.168.1.1/ with username: linksys and password admin (if your router is linksys)
3. If you can't login, that means you forgot your password and username then you can always hard reset your router by holding and pressing the small button behind your router to reset it.
4. Inside the page after you login, click on firmware. And update the firmware by locating the .bin file you downloaded earlier.
5. Make sure you do this via a cable and not through WIFI so that the probability of failure is greatly reduced. Afterwhich if you see "successful". Congratulations, you are done with the first part of installing the firmware.

SECOND PART (on your computer which is connect to the REPEATER via RJ45)
--------------------------------------------------------------------
1. Login to the repeater (the router with the new firmware)
2. The login should now be: username: root, password: admin
3. Leave DHCP Server settings to be 'on' and modify the TCP settings to become 10.0.0.1 instead of 192.168.1.1 ( this is to avoid conflict with the main router)
4. You should then not be able to connect to your page via 192.168.1.1 anymore. Modify the TCP/IP Settings for your computer. Set the TCP/IP settings from automatic to become the following:
IP: 10.0.0.2
SUBNET: 255.255.255.0
GATEWAY: 10.0.0.1
5. Login again to http://10.0.0.1/
6. Disabel Sp1 Firewall
7. Click on the status main Tab and search for the home network under the wireless tab and join the network
8. Inside the Wireless main tab -> basic settings, Add virtual interface
9. The SSID of this virtual interface should be different from your main SSID.
10. Wireless Security for both the virtual interface and the main interface (on your repeater) should be the same as your real router's. In my case, I set the Wireless security for both virtual/main interface to be WEP.

Now to test everything, take off all wires. Connect using Wireless from your laptop. Without any wires connecting to the repeater. You should be able to see the broadcast of your repeater's SSID. If you can see it but can't connect to the internet, try removing all security settings and work backwards from there, 99% of the time, its the security settings in conflict.

Aaron

Tuesday, June 9, 2009

Measuring Execution Time

DateTime startTime = DateTime.Now;
Console.WriteLine(startTime);

Wednesday, June 3, 2009

CSS Visibility vs Display

There is a difference when you want to hide things using CSS. Setting Visibility = 'hidden' and Display = "none" may appear similar at first, but actually it is not. If we have multiple lines of items arranged vertically that we want to hide, it will be obvious that the div layer set with visibility:none will have a whitespace placeholder wherelse a div layer set with display:none will not have a whitespace placeholder.


function showhide(header, childid)
{
var myHeader = document.getElementById(header);
var myLayer = document.getElementById(childid);
if (myLayer.style.display == "none") {
myLayer.style.display = "block";
} else {
myLayer.style.display = "none";
}
}

Random Number in C#

int RandomNo(int min, int max){

Random random = new Random();

return random.Next(min, max);

}

Friday, May 29, 2009

C# String vs StringBuilder

When we have to loop through a huge number of recordset to concatenate the results, we should use a stringbuilder as opposed to a string. The reason being, in C#, the String object is being truncated and recreated elsewhere in memory as opposed to the StringBuilder which stays in memory and does not gets recreated.

If the recordset is huge enough (say maybe more than 10 records), then the usage of a StringBuilder rather than plain old concatenation will result in a faster response time.

I had a text file that I was reading the results from (the text file had 7000 lines of records) and I suspected the textfile was the bottleneck to the application as it was taking over 60 seconds to execute. Apparently after some usage of:


DateTime currentSystemTime = DateTime.Now;
Debug.WriteLine("DB START: " + currentSystemTime);

I realised that the program was really slow when it was trying to concatenate the files to form an sql query string. So rather than doing this:

String insertionQuery = "";
insertionQuery = insertionQuery + String.Format("INSERT INTO [log] (mac, type, yearmth, dte, tme) VALUES ('{0}','{1}','{2}', '{3}', '{4}');",
logMac, logType, logIndex, logDate, logTime);

I did this:

StringBuilder insertionQuery = new StringBuilder();
insertionQuery = insertionQuery.Append(String.Format("INSERT INTO [log] (mac, type, yearmth, dte, tme) VALUES ('{0}','{1}','{2}', '{3}', '{4}');",
logMac, logType, logIndex, logDate, logTime));

Solved

Tuesday, May 26, 2009

ASP.NET Date Programming

//String to DateTime
String MyString;
MyString = "1999-09-01 21:34 PM";
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);

//DateTime to String
MyDateTime = new DateTime(1999, 09, 01, 21, 34, 00);
String MyString; MyString = MyDateTime.ToString("yyyy-MM-dd HH:mm tt");

// FORMATS
d - Numeric day of the month without a leading zero.dd - Numeric day of the month with a leading zero.ddd - Abbreviated name of the day of the week.dddd -
f,ff,fff,ffff,fffff,ffffff,fffffff - Fraction of a second. The more Fs the higher the precision.
h - 12 Hour clock, no leading zero.hh - 12 Hour clock with leading zero.H - 24 Hour clock, no leading zero.HH - 24 Hour clock with leading zero.
m - Minutes with no leading zero.mm - Minutes with leading zero.
M - Numeric month with no leading zero.MM - Numeric month with a leading zero.MMM - Abbreviated name of month.MMMM - Full month name.
s - Seconds with no leading zero.ss - Seconds with leading zero.
t - AM/PM but only the first letter. tt - AM/PM ( a.m. / p.m.)
y - Year with out century and leading zero.yy - Year with out century, with leading zero.yyyy - Year with century.
zz - Time zone off set with +/-.


http://www.codeproject.com/KB/cs/String2DateTime.aspx

ASP NET DEBUGGING

For ASP.NET, Console.WriteLine does not work, so we have to use System.Diagnostics.Debug.WriteLine("output"); instead. We can view the output log by viewing the program in debug mode (pressing F5 instead of CTRL+F5).

Monday, May 25, 2009

WF GF

then this guy bring his gf
wah the GF SUPER IRRITATING think she damn smart
then keep saying other ppl's english bad
the waiter came and take orders
she tried to act 'sophisticated'
act like she don't understand the waiter's broken singlish
then she said: "can you slower down? AR"
hahaha.. i almost laugh till i peng

Monday, May 11, 2009

Could not find stored procedure

When you cannot find the stored procedure and you are sure that the connectionString works and the stored procedure is inside the programmability folder. Example connection String is:
csb.ConnectionString = "Server=SERVER\WHATEVER;Initial Catalog=mw;Database=mw;User ID=aaron;Password=aaron";

Restore failed for Server

When you restore a database from another device and run into an error such as: System.Data.SqlClient.SqlError: File 'c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\salon.mdf' is claimed by 'salon_1'(1) and 'salon_Data'(2). The WITH MOVE clause can be used to relocate one or more files. (Microsoft.SqlServer.Smo)

You need to look under options and make sure that the SQL server is not trying to output to the same file name. The problem was due to the rows under the column "Restore As" (under options tab) having the same file name. So in other words, simply change the value of the column name for the "Restore As" to unique MDF values, and the restore should be successful.

Sunday, May 10, 2009

Import Data to SQL Server

1. On the existing server
Go to Microsoft SQL Server Studio Express
Task > Backup >
* take note to create the backup to only a single media file, unless you have to split it up.

2. On the new server
Go to Microsoft SQL Server Studio Express
Task > Restore
* there is no need to create a new database with the same name if this is a completely new restore. once we set the database file device, the new database name will appear to be restored.

Wednesday, May 6, 2009

Macintosh and FileReference Type in Flex

In Mac, the Type attribute of the filereference object returns null by default and this is a huge problem, considering that the type attribute works by default for the PC.


private function getMacExtension(myExtension:String,myName:String):String {
if (myExtension == null) {
if (myName.lastIndexOf(".") > 0) {
myExtension = myName.substr(myName.lastIndexOf("."), myName.length);
myExtension = myExtension.toLowerCase();
}
}
return myExtension;
}

Saturday, May 2, 2009

Use Zune as Hard Disk

Make sure your Zune is not plugged in and your Zune software isn't running
open up regedit by going to the start menu and selecting "run". Type regedt32 and hit "OK"
Browse to HKEY_LOCAL_MACHINE\System\ControlSet001\Enum\USB\
Search for "PortableDeviceNameSpace". This should be contained in the Vid_####&Pid_####\########_-_########_-_########_-_########\Device Parameters within the above ...\USB\ The ##'s listed here will be numbers and letters specific to your Zune
Change the following values:
EnableLegacySupport to 1
PortableDeviceNameSpaceExcludeFromShell to 0
ShowInShell to 1
Plug in your Zune, and make sure the Zune Software starts up.
Hopefully at this point you can open up "My Computer" and browse your device, though it does NOT show up as a drive letter.

Monday, April 27, 2009

Gmail Configuration

CNAME: mail - 3600 - ghs.google.com.
MX: vinculumventures.com. - 3600 - 1 - aspmx.l.google.com.
MX: vinculumventures.com. - 3600 - 5 - alt1.aspmx.l.google.com.
MX: vinculumventures.com. - 3600 - 5 - alt2.aspmx.l.google.com.
MX: vinculumventures.com. - 3600 - 10 - aspmx2.googlemail.com.
MX: vinculumventures.com. - 3600 - 10 - aspmx3.googlemail.com.

Monday, April 20, 2009

A generic error occurred in GDI+.

When you program in VB.NET/C#, if you encounter into situation such as a GDI error. Chances are it is a permission issue. Do check that you have the required 'write' permission for the ASPNET and USER account. That should solve your problem.

Similarly for flex, if it keeps checking for permission when you are loading images from a folder, chances are it is a permission issue on your server.

To modify permission, Right click on 'permission' inside IIS for the folder.

Saturday, April 18, 2009

Phrases

One chapter in a person life is not going to define the rest of his life.
Countries that out studies us will outperform us tomorrow
The absence of evidence, does not give evidence of absence
You do not marry someone whom you can live with, you marry someone whom you can't live without

Friday, April 17, 2009

Transparency issues with SPRY in Dreamweaver

When we add transparent PNG and use any effects in dream weaver, we may get problems with the transparency. There may be unwanted border color around the area of transparency. To solve that, we can very simply add a border color to it using CSS.

A simple style="background-color:#FFFFFF" will fix the problem.

Centering DIV

Centering a DIV using CSS

#content { width: 700px ; margin-left: auto ; margin-right: auto ;}

But how do you center a DIV in the center within a DIV? Say I have two absolute div and one is within the other. Both has got position set to absolute. We can do this:
<div style="width:900px;position:absolute;margin-left:-450pxtop:50px;left:50%;">

position:absolute will set the position to absolute
left:50% will set the child div to be drawn in the center
margin-left:450px will dictate that the drawn child be drawn to left by 450

Tuesday, April 14, 2009

Convertible Top Care

I was researching on convertible top car care kits recently and found two products. Mainly 303 and RaggTop. RaggTop is the premium version of 303 (as it appears by pricing). The last thing I want to do is to spoil my convertible's roof and hence I went ahead to buy the RaggTop kit from Amazon.

But before you buy any convertible car care kits, do make sure you check out if your convertible's roof is fabric or vinyl. It is different! Google about your car top material online. At least I am certain that my Z4 is Fabric :)

RAGGTOPP Convertible Top Care Kit - Fabric

PHP Debug Using TextFiles

The best way to debug PHP application is using textfiles.

$fp=fopen("temp.txt",'a');
fwrite($fp, $sqlCmd . "\n\n");
fclose($fp); // close file

Monday, April 13, 2009

Flex Getting Image Dimension before load complete

Flex does not have any library that supports obtaining the source image height and width on load. If you need to put the image into a container, you will not be able to manipulate the container/image accurately. For example, I was trying to put an image into a container, and set the image to 100% width and 100% height. But this wont work since the container does not have the correct image dimension.

To overcome this, we can make use of PHP's internal function 'getimagesize'. The codes are as follows:

$file = "uploader/upload/" . $row_imageinfo['bitmapurl'];
$info = getimagesize($file);
$width = 0;
$height = 0;
list($width, $height) = $info;


echo("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
echo("<result>");
echo(sprintf("<picurl>%s</picurl>",$row_imageinfo['bitmapurl']));
echo(sprintf("<width>%s</width>", $width));
echo(sprintf("<height>%s</height>", $height));
echo("</result>");

?>

Sunday, April 12, 2009

css id and class

Usage of class and id in CSS for DIVs

.newsRowText {
color:#333333;
margin:10px;
line-height:22px;}

.newsRowText#errors {
color:#CC0000;
margin:10px;
line-height:22px;
}

<div id="errors" class="newsRowText">Error Message</div>
<div class="newsRowText">Normal Message</div>

Flex getting objects that are created

Things to note:
1. When we create an object, they belong to a particular container, so when we access it we need to make sure that the accessor is going in order of it. Say for example, I have a button inside the RichTextArea object, I need to do this in order to access it:
this.richtextarea.textarea.button and not just simply this.richtextarea.button

2. We can access objects created on screen in two ways.
a. When we add the objects we created via an array. e.g.
public var imgArray:Array = new Array(); // this is declared at the top of the page
for (var count:int =0; count <>
var myImage:Image = new Image();
myImage.x = 10;
myImage.y = 10;
myImage.source = "whatever.jpg";
imgArray.push(myImage);
}

b. When we add a name to the object and obtain the current Event Source of it e.g.
public function init():void {
var myImage:Image = new Image();
myImage.x = 10;
myImage.y = 10;
myImage.source = "whatever.jpg";

myImage.name = "whatever";
myImage.addEventListener(MouseEvent.CLICK, getEventName);
}

public function getEventName(event:Event):void {
var myObject:Image = event.currentTarget as Image;
// if you want to get the image Name, we can do it like this:
// var myObjName:String = (event.currentTarget as Image).name;
}

List of countries

<option value="Andorra ">Andorra </option><option value="Argentina ">Argentina </option><option value="Australia ">Australia </option><option value="Austria ">Austria </option><option value="Azerbaijan Republic ">Azerbaijan Republic </option><option value="Bahrain ">Bahrain </option><option value="Belgium ">Belgium </option><option value="Belize ">Belize </option><option value="Bhutan ">Bhutan </option><option value="Brazil ">Brazil </option><option value="Brunei ">Brunei </option><option value="Bulgaria ">Bulgaria </option><option value="Cambodia ">Cambodia </option><option value="Canada ">Canada </option><option value="Chile ">Chile </option><option value="China Worldwide ">China Worldwide </option><option value="Costa Rica ">Costa Rica </option><option value="Croatia ">Croatia </option><option value="Cyprus ">Cyprus </option><option value="Czech Republic ">Czech Republic </option><option value="Denmark ">Denmark </option><option value="Ecuador ">Ecuador </option><option value="El Salvador ">El Salvador </option><option value="Estonia ">Estonia </option><option value="Finland ">Finland </option><option value="France ">France </option><option value="French Guiana ">French Guiana </option><option value="Germany ">Germany </option><option value="Gibraltar ">Gibraltar </option><option value="Greece ">Greece </option><option value="Greenland ">Greenland </option><option value="Guatemala ">Guatemala </option><option value="Honduras ">Honduras </option><option value="Hong Kong ">Hong Kong </option><option value="Hungary ">Hungary </option><option value="Iceland ">Iceland </option><option value="India ">India </option><option value="Indonesia ">Indonesia </option><option value="Ireland ">Ireland </option><option value="Israel ">Israel </option><option value="Italy ">Italy </option><option value="Japan ">Japan </option><option value="Jordan ">Jordan </option><option value="Kazakhstan ">Kazakhstan </option><option value="Kuwait ">Kuwait </option><option value="Kyrgyzstan ">Kyrgyzstan </option><option value="Latvia ">Latvia </option><option value="Liechtenstein ">Liechtenstein </option><option value="Lithuania ">Lithuania </option><option value="Luxembourg ">Luxembourg </option><option value="Malaysia ">Malaysia </option><option value="Mexico ">Mexico </option><option value="Nepal ">Nepal </option><option value="Netherlands ">Netherlands </option><option value="New Zealand ">New Zealand </option><option value="Nicaragua ">Nicaragua </option><option value="Norway ">Norway </option><option value="Oman ">Oman </option><option value="Papua New Guinea ">Papua New Guinea </option><option value="Peru ">Peru </option><option value="Philippines ">Philippines </option><option value="Poland ">Poland </option><option value="Portugal ">Portugal </option><option value="Qatar ">Qatar </option><option value="Romania ">Romania </option><option value="Russia ">Russia </option><option value="San Marino ">San Marino </option><option value="Saudi Arabia ">Saudi Arabia </option><option value="Singapore ">Singapore </option><option value="Slovakia ">Slovakia </option><option value="Slovenia ">Slovenia </option><option value="South Africa ">South Africa </option><option value="South Korea ">South Korea </option><option value="Spain ">Spain </option><option value="Sri Lanka ">Sri Lanka </option><option value="Suriname ">Suriname </option><option value="Sweden ">Sweden </option><option value="Switzerland ">Switzerland </option><option value="Taiwan ">Taiwan </option><option value="Tajikistan ">Tajikistan </option><option value="Thailand ">Thailand </option><option value="Turkey ">Turkey </option><option value="Turkmenistan ">Turkmenistan </option><option value="Ukraine ">Ukraine </option><option value="United Arab Emirates ">United Arab Emirates </option><option value="United Kingdom ">United Kingdom </option><option value="United States ">United States </option><option value="Uruguay ">Uruguay </option><option value="Vatican City State ">Vatican City State </option><option value="Venezuela ">Venezuela </option><option value="Vietnam ">Vietnam </option><option value="Yemen ">Yemen </option>

Thursday, April 9, 2009

Hitler (Charlie Charplin) Speech

"I'm sorry, but I don't want to be an emperor. That's not my business. I don't want to rule or conquer anyone. I should like to help everyone if possible - Jew, Gentile - black man - white.
We all want to help one another. Human beings are like that. We want to live by each other's happiness - not by each other's misery. We don't want to hate and despise one another. In this world there's room for everyone and the good earth is rich and can provide for everyone.

The way of life can be free and beautiful, but we have lost the way. Greed has poisoned men's souls - has barricaded the world with hate - has goose-stepped us into misery and bloodshed. We have developed speed, but we have shut ourselves in. Machinery that gives abundance has left us in want. Our knowledge has made us cynical; our cleverness, hard and unkind. We think too much and feel too little. More than machinery we need humanity. More than cleverness, we need kindness and gentleness. Withouhese qualities, life will be violent and all will be lost.

The aeroplane and the radio have brought us closer together. The very nature of these inventions cries out for the goodness in man - cries for universal brotherhood - for the unity of us all. Even now my voice is reaching millions throughout the world - millions of despairing men, women, and little children - victims of a system that makes men torture and imprison innocent people. To those who can hear me, I say: 'Do not despair.' The misery that is now upon us is but the passing of greed - the bitterness of men who fear the way of human progress. The hate of men will pass, and dictators die, and the power they took from the people will return to the people. And so long as men die, liberty will never perish.

Soldiers! Don't give yourselves to brutes - men who despise you and enslave you - who regiment your lives - tell you what to do - what to think and what to feel! Who drill you - diet you - treat you like cattle, use you as cannon fodder. Don't give yourselves to these unnatural men - machine men with machine minds and machine hearts! You are not machines! You are not cattle! You are men! You have the love of humanity in your hearts. You don't hate, only the unloved hate - the unloved and the unnatural!

Soldiers! Don't fight for slavery! Fight for liberty! In the seventeenth chapter of St Luke, it is written the kingdom of God is within man not one man nor a group of men, but in all men! In you! You, the people, have the power - the power to create machines. The power to create happiness! You, the people, have the power to make this life free and beautiful - to make this life a wonderful adventure. Then in the name of democracy - let us use that power - let us all unite. Let us fight for a new world - a decent world that will give men a chance to work - that will give youth a future and old age a security.

By the promise of these things, brutes have risen to power. But they lie! They do not fulfil that promise. They never will! Dictators free themselves but they enslave the people. Now let us fight to fulfil that promise! Let us fight to free the world - to do away with national barriers - to do away with greed, with hate and intolerance. Let us fight for a world of reason - a world where science and progress will lead to all men's happiness. Soldiers, in the name of democracy, let us unite!

Inmates as telemarketers

The US prison department is using the inmates as telemarketers.

You know.. What I do to telemarketers when they call me? I will pick up and then I will say oh yes, and ask them to hold on for a second and go about doing my things, come back one hour later and hang up the phone. Its not such a good idea anymore huh? They are inmates, they have my telephone number, and they may come out one day.


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

Tay Choon Teng (I kill you). Multiple disruptions. The NSF that burst my vein.

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


Oh you are a scholar? Can I do project with you?

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

The world is small, becareful on who you tell on. (I think he cannot make it in life)
Followed by the dinner with Erika which ended up with the conclusion


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

Mango spoon licking incident

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

Italy and how unsafe it is (coach lost camera). TomatoMayo. Breastfeeding with muslim

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

USA, sucky weather, nothing to do, black man smile, thanksgiving turkey, black friday, online shopping addiction, research on HCI and Virtualization. Demographics of students, lack of exams, student quality - project manager only, z4, bribe, driving test that never materialize, danger, snow, spring carnival. Lost of iphone.

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

Golf, pittsburgh, singapore, malaysia, indonesia

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

Poly, KTV days, Javelin, President Track and Field, Play poker in car


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

Kath, demanding, mad, clinic, jeans, combing hair, breakup threats, birthday breakup

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

Perry, Samantha, Carol, MH, PY, Nikky. Running at gim moh, driving across the causeway. pimp

Monday, April 6, 2009

Populate Dropdownlist programmatically

Say if you need to populate a dropdownlist programatically and do not have access to a bindable object or array. You have to first of all create an ArrayCollection, then create an object. Add that object within the ArrayCollection then set the dataprovider of the combobox to point to that. Its incredible how something so simple can be so hard to achieve in Flex.

try {
var qnsArrayList:ArrayCollection = new ArrayCollection();
var counter:int;
for (counter = 0; counter < qnsArray.length; counter++) {
var obj:Object = {data:qnsArray[counter][0],label:qnsArray[counter][1]};
qnsArrayList.addItem(obj);
}
ddl_response.labelField = "label";
ddl_response.dataProvider = qnsArrayList;
} catch (error:Error) {
Alert.show(error.message);
}

Saturday, April 4, 2009

SQL Left Join Twice

Say if you have two category id for a logo {logoId, logoCode }, and the category {catId,catDescription} belongs to another table with a link on table {catId, logoId} we need to left join on each logo twice, so that we can get the logo category as a single row. The SQL is as follows:

SELECT `categoryLinksId`, `_category`.`catId` as `pcatId`, `_category`.`catName` as `pcatName`, `category1`.`catId` as `ccatId`, `category1`.`catName` as `ccatName` FROM (`_categorylinks` LEFT JOIN `_category` ON `_categorylinks`.`parent_categoryId` = `_category`.`catId`) LEFT JOIN `_category` as `category1` ON `_categorylinks`.`child_categoryId` = `category1`.`catId`

Update parent body from child popup

This script is typically full of bugs due to the difference in the way Javascript is being processed in Internet Explorer or Firefox. Fundamentally, the difference is in the way Internet explorer does chaining (its more intelligent) as compared to that of Firefox. But then again, Firefox forces you to write good codes. What normally works in Firefox will work in Internet Explorer, but not neccessarily the other way round.

Anyhow, the codes for the parent window is as follows:
<script type="text/javascript">
<!--
// What these codes does it open up a popup when you click on something and when we receive a signal from the child, we updateLayer
function openBrWindow(theURL,winName,features) {
(theURL,winName,features);
}
function updateLayer() {

var obj = document.getElementById('selectcat1');
obj.innerHTML = "Testing"; // I had to do it this way else Firefox won't accept it!
}
//-->

</script>
You can open a new window with the following:

<a onclick="openBrWindow('selectcat.php','selectcat1','location=0,scrollbars=1,width=700,height=300')" href="#">popup</a>
The thing to update in parent is a SPAN Tag:
<span id="selectcat1" class="greyFont">None</span>


The codes for the child popup window is:
<script type="text/javascript">
<!-- function updateParentCloseSelf() {

opener.updateLayer();
self.close();
}
//-->
</script>

The button within the child is:

<input onclick="javascript:updateParentCloseSelf();" border="0" value="Submit Query" type="submit" name="Submit">

Wednesday, April 1, 2009

Accurately Position Drag and Drop Item

Anyone who played with Flex' drag and drop function (for canvas) will know that the drag and drop function will cause the image to be incorrectly placed on a canvas. That is, the background transparent image will appear on this particular position (when you hold down your mouse button) but when you release your mouse, the image appears in another position that is not accurately where you dropped it.

This is due to the fact that the image (when you clicked) had a pointer that was not at coordinates zero, zero. When we click the image and drag, it was most likely at a portion of the image, and when we drag it around the canvas, the 'transparent rectangular background of the image' made it appear as if we are dropping the image at that particular rectangular position.

You can see the codes to do drag and drop for canvas at:
http://livedocs.adobe.com/flex/3/html/help.html?content=dragdrop_7.html

In order to overcome this problem, at line dragInitiator, i added the following lines:
ds.addData(event.localX, "NumberX");
ds.addData(event.localY, "NumberY");

Then at the line of dragDropHandler, I placed the following:
Image(event.dragInitiator).x =
Canvas(event.currentTarget).mouseX- parseInt("" + event.dragSource.dataForFormat("NumberX"));
Image(event.dragInitiator).y =
Canvas(event.currentTarget).mouseY- parseInt("" + event.dragSource.dataForFormat("NumberY"));

Viola! Your image should appear wherever you drop them now.

Monday, March 30, 2009

Fatal error: Cannot use object of type stdClass as array...

While programming, I was stuck in this bug.
Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\redtaglogo2\members\temp3.php on line 24

I immediately check the var_dump output of the array and I got:
array(3) { [1]=> object(stdClass)#14 (6) { ["id"]=> string(1) "1" ["parent_id"]=> string(1) "0" ["title"]=> string(8) "Artistic" ["nleft"]=> string(1) "1" ["nright"]=> string(2) "28" ["nlevel"]=> string(1) "1" } [5]=> object(stdClass)#13 (6) { ["id"]=> string(1) "5" ["parent_id"]=> string(1) "1" ["title"]=> string(7) "Objects" ["nleft"]=> string(2) "20" ["nright"]=> string(2) "27" ["nlevel"]=> string(1) "2" } [6]=> object(stdClass)#12 (6) { ["id"]=> string(1) "6" ["parent_id"]=> string(1) "5" ["title"]=> string(6) "People" ["nleft"]=> string(2) "23" ["nright"]=> string(2) "24" ["nlevel"]=> string(1) "3" } }

Which looks correct and I have something for my array. The code that was producing the error was:
for ($i=0; $i <>
echo $path[$i][0];
}

I then tried to get it like an object:
for ($i=0; $i < sizeof($path); $i++) {
echo $path[$i]->title;
}

It returned me the wrong results!

I finally solved the problem using foreach:
foreach ($path as $stdObject) {
echo $stdObject->title . "
";
}


Viola

Friday, February 27, 2009

Error on git-warning

While I was executing a gui program from the console, I got the following error:

Application initialization failed: couldn't connect to display "0:0"
Error in startup script: invalid command name "mc"
while executing
"mc "git-gui: fatal error""
invoked from within
"if {[catch {package require Tcl 8.4} err]
|| [catch {package require Tk 8.4} err]
} {
catch {wm withdraw .}
tk_messageBox \
-icon error \
-typ..."
(file "/usr/bin/git-gui" line 34)

The problem turn out to be the fact that I am not in the sudoers list.

Friday, February 6, 2009

Unable to view Flex program in Firefox and Safari

If you have a Flex program, but you are unable to run it successfully in Firefox and Safari but you can run it inside internet explorer, then chances are you are having some problems with the javascript component that loads the flex program.

It may not be a flex program error, look in the javascript first.

Looking for content within files in Linux

Within your directory, type the following command:

sudo find . -print xargs grep "pattern to search for"

or if you have the name type, you can try

sudo find . -name "*.pl" xargs grep "pattern to search for"

Wednesday, January 21, 2009