Archive for February, 2013

rtrim($string, ",") would cut trailing commas.

trim($string, ",") would cut trailing and prefixing commas.

Asp.net insert, Edit, update, delete data in gridview
By: Shailesh Singh Feb 25, 2013
Categories: Asp.net, Gridview
Introduction:

In this article I will explain how to insert, edit, update and delete data in gridview using asp.net.

Description:

I have one gridview I need to write code to insert data into gridview after that I need to edit that gridview data and update it and if I want to delete the record in grdview we need to delete record simply by click on delete button of particular row to achieve these functionalities I have used some of gridview events those are

1) Onrowcancelingedit
2) Onrowediting
3) Onrowupdating
4) Onrowcancelingedit
5) Onrowdeleting

By Using above griview events we can insert, edit, update and delete the data in gridview. My Question is how we can use these events in our coding before to see those details first design table in database and give name Employee_Details
ColumnName

DataType
UserId

Int(set identity property=true)
UserName

varchar(50)
City

varchar(50)
Designation

varchar(50)
After completion table creation design aspx page like this

Untitled Page

.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}

<asp:Label ID="lbleditusr" runat="server" Text='’/>

<asp:Label ID="lblitemUsr" runat="server" Text='’/>

<asp:TextBox ID="txtcity" runat="server" Text='’/>

<asp:Label ID="lblcity" runat="server" Text='’/>

<asp:TextBox ID="txtDesg" runat="server" Text='’/>

<asp:Label ID="lblDesg" runat="server" Text='’/>

Now add the following namespaces in codebehind

using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing
After that write the following code

SqlConnection con = new SqlConnection(“Data Source=shaileshsingh;Integrated Security=true;Initial Catalog=MySampleDB”);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand(“Select * from Employee_Details”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = “No Records Found”;
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values[“UserName”].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl(“txtcity”);
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl(“txtDesg”);
con.Open();
SqlCommand cmd = new SqlCommand(“update Employee_Details set City='” + txtcity.Text + “‘,Designation='” + txtDesignation.Text + “‘ where UserId=” + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + ” Details Updated successfully”;
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values[“UserId”].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values[“UserName”].ToString();
con.Open();
SqlCommand cmd = new SqlCommand(“delete from Employee_Details where UserId=” + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = username + ” details deleted successfully”;
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals(“AddNew”))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl(“txtftrusrname”);
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl(“txtftrcity”);
TextBox txtDesgnation = (TextBox) gvDetails.FooterRow.FindControl(“txtftrDesignation”);
con.Open();
SqlCommand cmd =
new SqlCommand(
“insert into Employee_Details(UserName,City,Designation) values(‘” + txtUsrname.Text + “‘,'” +
txtCity.Text + “‘,'” + txtDesgnation.Text + “‘)”, con);
int result= cmd.ExecuteNonQuery();
con.Close();
if(result==1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtUsrname.Text + ” Details inserted successfully”;
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + ” Details not inserted”;
}
}
}

PHP : Create bar graph with dynamic scaling

Posted: February 22, 2013 in PHP
Tags: ,
Hi everyone, this tutorial will help you in creating a bar graph from PHP with the ability to adjust the scale depending upon the values provided. The technique used is smart enough to handle the number and range of values. A preview of the graph is shown below

All you need to understand this tutorial is the knowledge of following PHP image functions

in addition the following PHP functions are also used and offcourse some mathematics as well

If you have a good understanding of all these function, its good to go otherwise you should click on function which is new to you to consult the documentation and get back after learning all these functions

Lets get started
First of all declare an array of values for the graph. Declare these values in the form of associative array (i.e key and value pairs). Keys will be shown at the bottom as the graph legend and the values will be used to draw bars.
 $values=array(
	"Jan" => 110,
	"Feb" => 130,
	"Mar" => 215,
	"Apr" => 81,
	"May" => 310,
	"Jun" => 110,
	"Jul" => 190,
	"Aug" => 175,
	"Sep" => 390,
	"Oct" => 286,
	"Nov" => 150,
	"Dec" => 196
);
Now define the size of image, i have used an image of size 600×400 for this tutorial.
 $img_width=600;
 $img_height=400;
The graph we are going to create has a border around it, i have declared a variable $margins to create that border around the four sides.
 $margins=20;
Now find the size of graph by subtracting the size of borders.
 $graph_width=$img_width - $margins * 2;
 $graph_height=$img_height - $margins * 2;
Create an image of the size defined above
 $img=imagecreate($img_width,$img_height);
Define the width of bar. Gap between the bars will depend upon the width and number of bars and the gaps will be one more than the total number of bars as there is gap on the right and left of the graph. You can see in our example, we have 12 bars but 13 gaps, thats why you see ($total_bars+1) in the denominator.
 $bar_width=20;
 $total_bars=count($values);
 $gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1);
Define colors to be used in the graph
 $bar_color=imagecolorallocate($img,0,64,128);
 $background_color=imagecolorallocate($img,240,240,255);
 $border_color=imagecolorallocate($img,200,200,200);
 $line_color=imagecolorallocate($img,220,220,220);
Create a border around the graph by filling in rectangle
 imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color);
 imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color);
Now the maximum value is required to adjust the scale. Ratio is calculated by dividing graph height by maximum graph value. Each value will be multiplied with ratio, so that no bar goes beyond the graph height.
 $max_value=max($values);
 $ratio= $graph_height/$max_value;
Drawing horizontal lines is optional, note that the margin variable is subtracted from image height so that first line is positioned inside the graph area (Discarding the margins). If you have trouble understanding this code, use a paper and pencil to manually find the values of variable at each repitition of the loop
 $horizontal_lines=20;
 $horizontal_gap=$graph_height/$horizontal_lines;
 for($i=1;$i<=$horizontal_lines;$i++){
	$y=$img_height - $margins - $horizontal_gap * $i ;
	imageline($img,$margins,$y,$img_width-$margins,$y,$line_color);
	$v=intval($horizontal_gap * $i /$ratio);
	imagestring($img,0,5,$y-5,$v,$bar_color);
 }
Here comes the most crucial part of our graph, drawing the bars. Each of the 8 lines in the for loop are individually explained below

  1. Extract key and value pair from the current pointer position, each iteration of loop moves the internal pointer of array to the next entry
  2. The x1 value (i.e. left) of each bar gets and increment by $gap+$bar_width with each iteration of loop
  3. The x2 value (i.e. right) is calculated by adding bar width with x1
  4. y1 is the top of each bar. ratio is multiplied with individual values to mare sure that bars remain inside the graph boundries.
  5. y2 (i.e bottom) is fix for all bars. Can also be placed outside the loop
  6. Draw the graph with calculated left, top, right and bottom positions
  7. The numeric value of each bar is shown at the top. Some plus or minus will be required to center align the displayed value with the bar
  8. Display the legend i.e. Month names
 for($i=0;$i< $total_bars; $i++){
	list($key,$value)=each($values);
	$x1= $margins + $gap + $i * ($gap+$bar_width) ;
	$x2= $x1 + $bar_width;
	$y1=$margins +$graph_height- intval($value * $ratio) ;
	$y2=$img_height-$margins;
	imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color);
	imagestring($img,0,$x1+3,$y1-10,$value,$bar_color);
	imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color);
}
Show the graph as a png image
 header("Content-type:image/png");
 imagepng($img);
The whole script is givenbelow, just copy and enjoy your own php graphs
<?php
	# ------- The graph values in the form of associative array
	$values=array(
		"Jan" => 110,
		"Feb" => 130,
		"Mar" => 215,
		"Apr" => 81,
		"May" => 310,
		"Jun" => 110,
		"Jul" => 190,
		"Aug" => 175,
		"Sep" => 390,
		"Oct" => 286,
		"Nov" => 150,
		"Dec" => 196
	);

	$img_width=450;
	$img_height=300; 
	$margins=20;

	# ---- Find the size of graph by substracting the size of borders
	$graph_width=$img_width - $margins * 2;
	$graph_height=$img_height - $margins * 2; 
	$img=imagecreate($img_width,$img_height);

	$bar_width=20;
	$total_bars=count($values);
	$gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1);

	# -------  Define Colors ----------------
	$bar_color=imagecolorallocate($img,0,64,128);
	$background_color=imagecolorallocate($img,240,240,255);
	$border_color=imagecolorallocate($img,200,200,200);
	$line_color=imagecolorallocate($img,220,220,220);

	# ------ Create the border around the graph ------

	imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color);
	imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color);

	# ------- Max value is required to adjust the scale	-------
	$max_value=max($values);
	$ratio= $graph_height/$max_value;

	# -------- Create scale and draw horizontal lines  --------
	$horizontal_lines=20;
	$horizontal_gap=$graph_height/$horizontal_lines;

	for($i=1;$i<=$horizontal_lines;$i++){
		$y=$img_height - $margins - $horizontal_gap * $i ;
		imageline($img,$margins,$y,$img_width-$margins,$y,$line_color);
		$v=intval($horizontal_gap * $i /$ratio);
		imagestring($img,0,5,$y-5,$v,$bar_color);

	}

	# ----------- Draw the bars here ------
	for($i=0;$i< $total_bars; $i++){ 
		# ------ Extract key and value pair from the current pointer position
		list($key,$value)=each($values); 
		$x1= $margins + $gap + $i * ($gap+$bar_width) ;
		$x2= $x1 + $bar_width; 
		$y1=$margins +$graph_height- intval($value * $ratio) ;
		$y2=$img_height-$margins;
		imagestring($img,0,$x1+3,$y1-10,$value,$bar_color);
		imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color);		
		imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color);
	}
	header("Content-type:image/png");
	imagepng($img);

?>
<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.5.js"></script>
    <script>
      function countChar(val) {
        var len = val.value.length;
        if (len >= 500) {
          val.value = val.value.substring(0, 500);
        } else {
          $('#charNum').text(500 - len);
        }
      };
    </script>
  </head>

  <body>
    <textarea id="field" onkeyup="countChar(this)"></textarea>
    <div id="charNum"></div>
  </body>

</html>
<head>
<title>Run JavaScript function at specific intervals of time</title>
<script type=”text/javascript”>
var count=0,chkfn=null;
function changeColor() {
// Call function with 1000 milliseconds gap
chkfn = setInterval(starttimer, 1000);
}
function starttimer() {
count += 1;
var oElem = document.getElementById(“divtxt”);
oElem.style.color = oElem.style.color == “red” ? “blue” : “red”;
document.getElementById(“pcount”).innerHTML = “Your Time Starts: ” + count;
}
function stoptimer() {
clearInterval(chkfn);
chkfn = null;
count = 0;
document.getElementById(“pcount”).innerHTML = ”;
}
</script>
</head>
<body>
<div id=”divtxt”>
<p id=”pcount” style=”font:bold 24px verdana”></p>
</div>
<button onclick=”changeColor();”>Start Timer</button>
<button onclick=”stoptimer();”>Stop Timer</button>
</body>
</html>
<head>
<title>Generate Random Colors using javascript</title>
<script type=”text/javascript”>
// Run function for every second of timer
setInterval(rgbcolors, 1000);
function rgbcolors() {
// rgb string generation
var col = “rgb(“
+ Math.floor(Math.random() * 255) + “,”
+ Math.floor(Math.random() * 255) + “,”
+ Math.floor(Math.random() * 255) + “)”;
//change the text color with the new random color
document.getElementById(“divstyle”).style.color = col;
}
</script>
</head>s
<body>
<form id=”form1″ runat=”server” >
<div id=”divstyle” style=”font:bold 24px verdana”>shaileshmanojsingh.wordpress.com</div>
</form>
</body>

</html>