Archive

Archive for the ‘tricks’ Category

Enable or Disable an anchor tag in javascript: IE and Firefox compatible

September 29, 2010 Leave a comment

Hi,

To add full ‘disable’ functionality to both IE & Firefox browsers

Add or remove the href attribute (both browsers will enable/disable the anchor with this method).

To allow this to work you need to store the existing href value – I just add another (non standard html) attribute eg href_User_defined.

function disableAnchor(anchorObj, disable){
if(disable){
var href = anchorObj.getAttribute(“href”);
if(href && href != “” && href != null){
anchorObj.setAttribute(‘href_User_defined’, href);
}
anchorObj.removeAttribute(‘href’);
anchorObj.style.color=”gray”;
}
else{
anchorObj.setAttribute(‘href’, anchorObj.attributes['href_User_defined'].nodeValue);
anchorObj.style.color=”blue”;
}
}

Thanx

Ref Document:  http://geekswithblogs.net/TimH/archive/2006/01/19/66396.aspx

Categories: javascript, tricks

GridView in asp.net 3.5 c#

September 2, 2010 Leave a comment

Hi All,
Today I learned Grid View:
Here I am assigning LINQ as datasource.

.aspx file
You need to include it in form tag.

<asp:GridView ID=”GridView1″ runat=”server” AllowPaging=”True” CellPadding=”4″
ForeColor=”#DEDEDE” BackColor=”#E7E3E3″ GridLines=”None”
AutoGenerateColumns=”False”  AllowSorting=”True”
onpageindexchanging=”GridView1_PageIndexChanging” BorderWidth=”1px”>
<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
<Columns>
<asp:TemplateField HeaderText=”Sr. No”>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText=”Group Name” DataField=”GroupName” />
<asp:BoundField HeaderText=”Status” DataField=”Status” />
<asp:HyperLinkField HeaderText=”Action” Text=”Edit” />
</Columns>
<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White”
BorderStyle=”Dotted” BorderWidth=”1px” />
<EditRowStyle BackColor=”#999999″ />
<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
</asp:GridView>

.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
public void bindGridView()
{
List admGrp = GroupService.Instance.GetAllGroups();
GridView1.DataSource = admGrp;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
int newPageIndex = e.NewPageIndex;
GridView1.PageIndex = newPageIndex;
bindGridView();
}

Note: You need to set AutoGenerateColumns = “False” explicitly as by default its True.
When the AutoGenerateColumns property is set to true, an AutoGeneratedField object is automatically created for each field in the data source. Each field is then displayed as a column in the GridView control in the order that the fields appear in the data source.

1) Also, If you want to add serial number or Row Index, use following code:

<asp:TemplateField HeaderText=”Sr. No”>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>

2)If you need to provide dynamic hyperlink then,

<asp:HyperLinkField HeaderText=”Action” Text=”Edit” datanavigateurlfields=”GroupId”
datanavigateurlformatstring=”addGroups.aspx?action=edit&grpid={0}” />

Note,  we need to  include datanavigateurlfields.

You can  also  add  tags DataTextField & DataTextFormatString to  show dynamic text.

Also, You can add more than one parameters as follows:
<asp:HyperLinkField HeaderText="UserName" DataTextField="LoginId" SortExpression="LoginId" datanavigateurlfields="LoginId,Password" datanavigateurlformatstring="getUserDetail.aspx?uid={0}&pass={1}" HeaderStyle-ForeColor="#164b6d" />


If you want to disable particular link depending upon some condtion(in my case it depend upon status),
you can use following code: e.Row.Cells[2].Enabled = false;(where Cells[2] is location of Hyperlink)

3) If you need  to display dynamic text base  upon  text  fetched  fromDb  or  change  the color   of cell depending  on data,you need to include  following code:

Here  e.g  I am  showing status = Active or Inactive  base  upon the flag  value stored in DB.

In .aspx  file  we need to write as usual,

<asp:BoundField HeaderText=”Status” DataField=”Status”  />

Also additionally we need to include an event,    OnRowDataBound=”GridView1_RowDataBound”

In aspx.cs,

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs  e)
{
// Check if row is data row, not header, footer etc.
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get value of third column. Index is zero based, to
// get text of third column we use Cells[2].Text
int CellValue = Convert.ToInt32(e.Row.Cells[2].Text);

// If value is greater of 10, change format
if (CellValue == 1)
{
// Use this syntax to change format of complete row
//e.Row.BackColor = System.Drawing.Color.Yellow;
// Use this syntax to change format of single cell
// e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
e.Row.Cells[2].Text = “Active”;
}
else
{
e.Row.Cells[2].Text = “Inactive”;
}
}
}

4)

Disable Edit Button if condition in another column is met

Chk :  http://forums.asp.net/p/1513875/3621570.aspx

5)

If you want to provide fixed  length to grid view column:

Actually  I  faced  the same  problem.I got the solution from site mention below:

http://www.pluralsight-training.net/community/blogs/keith/archive/2008/07/30/controlling-column-width-in-a-gridview.aspx

To fix the issue you need to do following steps:

1) Set up a CssClass for the GridView itself and include the table-layout:fixed style.

2) Use either HeaderStyle-CssClass or HeaderStyle-Width to set the width of the cell.

B’coz the width of the column  is set  by the first row, which in  most of the cases is Header.

3) Include following  style into your CssClass for the GridView TD(e.g. In my case it was .mGrid td)
word-wrap : break-word ;
word-break : normal;

Hope it will solve your problem.

Ref Links:

http://www.asp.net/data-access/tutorials/paging-and-sorting-report-data-cs
http://msdn.microsoft.com/en-us/library/aa479347.aspx

http://www.beansoftware.com/ASP.NET-Tutorials/Conditional-Values-Styles-GridView.aspx

http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=80853

Today I had following issue:
“how to access hidden fields from gridview in asp.net”
I need to set hidden ID value & need to access it.(I need to access uid(primary key) of record), I got following solution.
Previously I was trting asp:BoundField with Visible=”false”,but wasa not able to access the values.The problem is that when the Visibility property of the BoundField is set to false the column isn’t rendered to the client.

The I tried following:
[CODE]

<asp:HiddenField ID="HiddenField1" runat="server" Value='' />

[CODE BEHIND]
In RowDataBound function
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField hidden = (HiddenField)e.Row.Cells[6].FindControl(“HiddenField1″);

}

hidden.Value will give text data.

Reference:

http://stackoverflow.com/questions/1833532/get-hidden-field-value

Categories: ASP.net C#, General, tricks

Five Tips For Making Ideas Happen

June 8, 2010 Leave a comment

Hello,
I went through a nice article “Five Tips For Making Ideas Happen” at www.smashingmagazine.com wrttrn by Scott Belsky. As author says We have so many great ideas, but most of them never see the light of day. Why do most ideas never happen? The reason is that our own creative habits get in the way.
I personally fount some of the points very true, so i am listing them down.

1. Avoid A Reactionary Workflow:
Without realizing it, most of us have gradually adopted a “reactionary workflow.” We are constantly bombarded with incoming communication: email, text messages, tweets, Facebook posts, phone calls, instant messages, etc. Rather than be proactive with our energy, we spend all of our energy reacting, enslaved to the last incoming item.

To avoid this reactionary workflow, some of the most productive people I have met schedule what can be called “windows of non-stimulation” in their day. For two to three hours per day, these people avoid email and all other incoming communication. In this time, they focus on their list of big items: not routine tasks, but long-term projects that require research and deep thought.

2. Reduce Your Insecurity Work
In the era of Google Analytics and Twitter, we spend too much time obsessing over real-time data because it’s all at our fingertips. Whether it’s your website’s traffic or bank account, checking these repeatedly doesn’t help make your ideas happen. They just make you feel “safe.” Insecurity work is stuff we do that (1) has no definable outcome, (2) does not move the ball forward in any way and (3) takes up so little time that we can do it multiple times a day without realizing it. Still, it puts us at ease.

The first step to reducing insecurity work is becoming self-aware. Identify the insecurity work in your daily life. The second step is to establish guidelines and rituals for yourself that create discipline. Perhaps you could try restricting all of your insecurity work to a particular 30 minutes every day? The third step, if applicable, is to delegate your insecurity tasks to a less insecure colleague, who can review the data periodically and report any concerns.

You will get complete article at here.

Categories: General, My Issuses, tricks

Parameterized query

May 6, 2010 Leave a comment

Hey,
I learned parametrized query in ASP.net C#.

The following link was very helpful.

http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx

Adding part of code for your quick reference.
The code is basically a registration form:

private void ExecuteInsert(string name, string username, string password, string gender, string age, string address)

{

SqlConnection conn = new SqlConnection(GetConnectionString());

string sql = "INSERT INTO tblRegistration (Name, UserName, Password, Gender, Age) VALUES "

+ " (@Name,@UserName,@Password,@Gender,@Age)";

try

{

conn.Open();

SqlCommand cmd = new SqlCommand(sql, conn);

SqlParameter[] param = new SqlParameter[5];

param[0] = new SqlParameter("@Name", SqlDbType.VarChar, 50);

param[1] = new SqlParameter("@UserName", SqlDbType.VarChar, 50);

param[2] = new SqlParameter("@Password", SqlDbType.VarChar, 50);

param[3] = new SqlParameter("@Gender", SqlDbType.Char, 10);

param[4] = new SqlParameter("@Age", SqlDbType.Int, 100);

param[0].Value = name;

param[1].Value = username;

param[2].Value = password;

param[3].Value = gender;

param[4].Value = age;

for (int i = 0; i < param.Length; i++)

{

cmd.Parameters.Add(param[i]);

}

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

}

catch (System.Data.SqlClient.SqlException ex)

{

string msg = "Insert Error:";

msg += ex.Message;

throw new Exception(msg);

}

finally

{

conn.Close();

}

}

The code works perfect if we are using MSSQL DB Server.

But in case you are using Mysql DB server then you need to modify the code little bit as follows:

private void ExecuteInsert(string name, string username, string password, string gender, string age)
{
MySqlConnection conn = new MySqlConnection(GetConnectionString());

string sql = "INSERT INTO test_user (first_nm, last_nm, pword, age ,gender) VALUES "

+ "(?Name,?UserName,?Password,?Age,?Gender)";

try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand(sql, conn);

MySqlParameter[] param = new MySqlParameter[5];

param[0] = new MySqlParameter("?Name", MySqlDbType.VarChar, 50);
param[1] = new MySqlParameter("?UserName", MySqlDbType.VarChar, 50);
param[2] = new MySqlParameter("?Password", MySqlDbType.VarChar, 50);
param[3] = new MySqlParameter("?Age", MySqlDbType.VarChar, 12);
param[4] = new MySqlParameter("?Gender", MySqlDbType.VarChar, 6);

param[0].Value = name;
param[1].Value = username;
param[2].Value = password;
param[3].Value = age;
param[4].Value = gender;

for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}

//Response.Write(CommandType.Text+ "
");
cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

}
catch (Exception ex)
{

string msg = "Insert Error:";

msg += ex.Message;

throw new Exception(msg);

}

finally
{

conn.Close();

}

}

This example shows you how to run a parameterized query against MySQL.
The trick is to remember the ? instad of @ – which is the case of SQL Server.

Session Funda in PHP

March 5, 2010 Leave a comment

Hey guys,
It took me some time to understand basics of Session in php.
If you create a logout.php to end user session, the right sequence is as follows

session_start();
session_unset();
session_destroy();

he difference between both session_unset and session_destroy is as follows:

session_unset just clears out the sesison for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists.

Using session_unset in tandem with session_destroy however, is a much more effective means of actually clearing out data. As stated in the example above, this works very well, cross browser:

session_unset();
session_destroy();

I noticed that in firefox, one could simply use sesison_unset and the session would be cleared. When trying this on IE, I was horrified to find out that the data was still there, so I had to use session destroy.
(Ref : http://www.php.net/manual/en/function.session-unset.php)

session_unset() is like doing a session_unregister() on all registered variables. They can still be re-registered by calling session_register() whereas after session_destroy, they cannot.

If you want to clear all sessions:
$_SESSION = array();

Categories: Bugs, PHP, tricks

Sorting result explicitely in MySQL

January 6, 2010 1 comment

Hello,
I you want to sort the result explicity & specify the order of which ‘order by’ comes back in,
like if you had a priority field that had the values “Low” “High” or “Medium” .. do this:

select * from tablename order by priority=’High’ DESC, priority=’Medium’ DESC, priority=’Low” DESC;

Another Smart way is :

SELECT * FROM tickets ORDER BY FIELD(priority, ‘High’, ‘Normal’, ‘Low’, ‘The Abyss’);

I observed that its not necessary to mention all the possible values.

e.g. The query we built was quit complex
SELECT b.mf_cocode,b.mf_schcode,b.mf_schname,b.grpcode,b.moptionname,b.mplanname
FROM
(SELECT c.mf_cocode,c.mf_schcode,c.mf_schname,c.grpcode,c.moptionname,c.mplanname
FROM mutual_category c
ORDER BY c.moptionname=’growth’ DESC,c.mplanname=’regular’ DESC) b
GROUP BY b.grpcode

Categories: database, mysql, SQL, tricks

Virtual Hosts

January 6, 2010 Leave a comment

Hello Friends,

Today I implemented interesting concept called “Virtual Hosts”.
The Apache HTTP Server’s built in virtual hosting allows the server to provide different information based on which IP address, hostname, or port is being requested.
To activate name-based virtual hosting, uncomment the NameVirtualHost line by removing the hash mark (#) and replace the asterisk (*) with the IP address assigned to the machine.

Next, configure a virtual host by uncommenting and customizing the container.

On the line, change the asterisk (*) to the server’s IP address. Change the ServerName to a valid DNS name assigned to the machine, and configure the other directives as necessary.

To create a name-based virtual host, it is best to use the virtual host container provided in httpd.conf as an example.

The virtual host example read as follows:

#NameVirtualHost *:80
#
#
# ServerAdmin webmaster@dummy-host.example.com
# DocumentRoot /www/docs/dummy-host.example.com
# ServerName dummy-host.example.com
# ErrorLog logs/dummy-host.example.com-error_log
# CustomLog logs/dummy-host.example.com-access_log common
#

Note :- The location of httpd.conf may vary as per server.
In my case, it was apache centos.
To activate name-based virtual hosting, uncomment the NameVirtualHost line by removing the hash mark (#) and replace the asterisk (*) with the IP address assigned to the machine.

Next, configure a virtual host by uncommenting and customizing the container.

On the line, change the asterisk (*) to the server’s IP address. Change the ServerName to a valid DNS name assigned to the machine, and configure the other directives as necessary.

To activate a newly created virtual host, the Apache HTTP Server must be reloaded or restarted.

E.g.

ServerAdmin preetul.correia@geo.com
DocumentRoot /home/preetul

sudo /etc/init.d/httpd restart

Ref : http://httpd.apache.org/docs/2.2/vhosts/

http://www.centos.org/docs/5/html/Deployment_Guide-en-US/s1-apache-virtualhosts.html

Categories: PHP, tricks

Mysql Query Cache – Current Cache Size

September 28, 2009 Leave a comment

HI Buddies,
I leaned something new about Mysql Query caching.
Indeed it would be good to be able to see query cache contents.
Unfortunately it is not possible in current MySQL version. So you’ve just got to guess.

SESSION shows the values for the current connection.
mysql> SHOW GLOBAL STATUS;
+———————————–+————+
| Variable_name | Value |
+———————————–+————+
| Aborted_clients | 0 |
| Aborted_connects | 0 |
| Bytes_received | 155372598 |
| Bytes_sent | 1176560426 |

| Connections | 30023 |
| Created_tmp_disk_tables | 0 |
| Created_tmp_files | 3 |
| Created_tmp_tables | 2 |

| Threads_created | 217 |
| Threads_running | 88 |
| Uptime | 1389872 |
+———————————–+————+

#Qcache_free_memory -
The amount of free memory for the query cache.
#Qcache_hits -
The number of query cache hits.
#Qcache_inserts -
The number of queries added to the query cache.
#Qcache_queries_in_cache -
The number of queries registered in the query cache.

For Details Ref :- http://dev.mysql.com/doc/refman/5.0/en/server-status-variables.html#statvar_Qcache_free_memory

Byte to MB relation (16777216 bytes
16384.000 kilobytes (abbreviated as KB or Kb*)
16.0000 megabytes (abbreviated as M or MB))

To set the size of the query cache, set the query_cache_size system variable. Setting it to 0 disables the query cache.
When you set query_cache_size to a nonzero value, keep in mind that the query cache needs a minimum size of about 40KB to allocate its structures.
mysql> SET GLOBAL query_cache_size = 40000;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SHOW WARNINGS\G
*************************** 1. row ***************************
Level: Warning
Code: 1282
Message: Query cache failed to set size 39936;
new query cache size is 0

mysql> SET GLOBAL query_cache_size = 41984;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE ‘query_cache_size’;
+——————+——-+
| Variable_name | Value |
+——————+——-+
| query_cache_size | 41984 |
+——————+——-+

For the query cache to actually be able to hold any query results, its size must be set larger:

mysql> SET GLOBAL query_cache_size = 1000000;
Query OK, 0 rows affected (0.04 sec)

mysql> SHOW VARIABLES LIKE ‘query_cache_size’;
+——————+——–+
| Variable_name | Value |
+——————+——–+
| query_cache_size | 999424 |
+——————+——–+
1 row in set (0.00 sec)

The query_cache_size value is aligned to the nearest 1024 byte block. The value reported may therefore be different from the value that you assign.

To control the maximum size of individual query results that can be cached, set the query_cache_limit system variable. The default value is 1MB.

Setting the GLOBAL query_cache_type value determines query cache behavior for all clients that connect after the change is made. Individual clients can control cache behavior for their own connection by setting the SESSION query_cache_type value. For example, a client can disable use of the query cache for its own queries like this:

mysql> SET SESSION query_cache_type = OFF;

If you set query_cache_type at server startup (rather than at runtime with a SET statement), only the numeric values are allowed.

query_cache_type = 2; means You can cache query on defmand using
SELECT SQL_CACHE id, name FROM customer;
SQL_CACHE

The query result is cached if it is cacheable and the value of the query_cache_type system variable is ON or DEMAND.
vice versa,
SELECT SQL_NO_CACHE id, name FROM customer;

The default value of query_cache_min_res_unit is 4KB. This should be adequate for most cases.
For details Ref : http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html

To check whether the query cache is present in your MySQL server, use the following statement:

mysql> SHOW VARIABLES LIKE ‘have_query_cache’;
+——————+——-+
| Variable_name | Value |
+——————+——-+
| have_query_cache | YES |
+——————+——-+

To monitor query cache performance, use SHOW STATUS to view the cache status variables:

mysql> SHOW STATUS LIKE ‘Qcache%’;
+————————-+——–+
| Variable_name | Value |
+————————-+——–+
| Qcache_free_blocks | 36 |
| Qcache_free_memory | 138488 |
| Qcache_hits | 79570 |
| Qcache_inserts | 27087 |
| Qcache_lowmem_prunes | 3114 |
| Qcache_not_cached | 22989 |
| Qcache_queries_in_cache | 415 |
| Qcache_total_blocks | 912 |
+————————-+——–+

The information provided by the Qcache_lowmem_prunes status variable can help you tune the query cache size. It counts the number of queries that have been removed from the cache to free up memory for caching new queries. The query cache uses a least recently used (LRU) strategy to decide which queries to remove from the cache
The optimal value of Qcache_lowmem_prunes is 0.
For details Ref : http://dev.mysql.com/doc/refman/5.0/en/query-cache-status-and-maintenance.html

Categories: database, mysql, SQL, tricks

Updating foreign keys in a multiuser environment.

September 8, 2009 Leave a comment

Updating foreign keys in a multiuser environment. Using LAST_INSERT_ID().

The LAST_INSERT_ID() is unique to the login session. This allows updating
of foreign keys.

CREATE TABLE keytest (
pkey int(11) NOT NULL auto_increment,
ptext text,
ptype int(11),
timeEnter timestamp(14),
PRIMARY KEY (pkey)
);

CREATE TABLE foreignkeytest (
pkey int(11) NOT NULL auto_increment,
pkeykeytest int(11) NOT NULL,
ptext text,
ptype int(11),
timeEnter timestamp(14),
PRIMARY KEY (pkey)
);

mysql> insert into keytest(ptext,ptype) values (‘one’,1);

mysql> select LAST_INSERT_ID() from keytest;
+——————+
| last_insert_id() |
+——————+
| 1 |
+——————+
1 row in set (0.03 sec)

mysql> insert into foreignkeytest (ptext,pkeykeytest) values (‘one’,LAST_INSERT_ID());

Note: If your session didn’t update any records, LAST_INSERT_ID() will be zero. Never
assume LAST_INSERT_ID()+1 will be the next record. If another session inserts a record,
this value may be taken. You are assured that this value will be unique to the “session”.

**SPECIAL NOTE: MySQL 4.1.2. supports UUID.

mysql> select uuid();
+————————————–+
| uuid() |
+————————————–+
| 167c1afe-0a0f-1027-891e-0004e222b485 |
+————————————–+
1 row in set (0.00 sec)

“A UUID is designed as a number that is globally unique in space and time.
Two calls to UUID() are expected to generate two different values, even if
these calls are performed on two separate computers that are not
connected to each other.”

So in the future, UUID() could be used as a better primary key. The advantage
being tables from a one server could be up-loaded to a second server without
worrying about duplicate keys.

Categories: database, mysql, SQL, tricks

Select the nth Highest Record in a Database Table using MySQL

August 28, 2009 1 comment

If you want to select 2nd Highest Date from a recored set :
Then You have 2 options:

1. SUB-QUERY:
SELECT datetobefetch
FROM table1
WHERE datetobefetch < (
SELECT max(datetobefetch)
FROM table1
WHERE datetobefetch
)

But if have fetch 5th record then, the better approach is as follows:
2.Using LIMIT:

SELECT datetobefetch
FROM table1
ORDER BY datetobefetch
DESC LIMIT 4,1

The query just returns the first row after 4 row(s) so you get the nth highest record.

Categories: database, mysql, SQL, tricks
Follow

Get every new post delivered to your Inbox.