Wednesday, December 28, 2011

Query string in asp.net

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

Page.ClientScript.RegisterStartupScript(this.GetType(), "ale", "window.open('" + "Result.aspx?id=" + LoginId_lbl.Text + "&Project=" + selected_project + "',null,'height=200,width=200');", true);

id = Request.QueryString["id"];
proj = Request.QueryString["Project"];

Listbox item movement from right to left, Moveup and Movedown

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

protected void Button2_Click(object sender, EventArgs e)
{
ListItem[] myListItemArray = new ListItem[ListBox1.Items.Count];
ListBox1.Items.CopyTo(myListItemArray, 0);

foreach (ListItem myItem in myListItemArray)
{
ListBox2.Items.Add(myItem);
}
ListBox1.Items.Clear();
}

protected void moveRight_Click(object sender, EventArgs e)
{
for (int i = 0; i <= ListBox1.Items.Count-1; i++)
{
if (ListBox1.Items[i].Selected == true)
{
ListBox2.Items.Add(ListBox1.Items[i]);
}


}
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected == true)
{
ListItem li = ListBox1.Items[i];
ListBox1.Items.Remove(li);
}

}

}
protected void moveLeft_Click(object sender, EventArgs e)
{
for (int i = 0; i <= ListBox2.Items.Count - 1; i++)
{
if (ListBox2.Items[i].Selected == true)
{
ListBox1.Items.Add(ListBox2.Items[i]);
}


}
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected == true)
{
ListItem li = ListBox2.Items[i];
ListBox2.Items.Remove(li);
}

}


}
protected void Button3_Click(object sender, EventArgs e)
{
ListItem[] myListItemArray = new ListItem[ListBox2.Items.Count];
ListBox2.Items.CopyTo(myListItemArray, 0);

foreach (ListItem myItem in myListItemArray)
{
ListBox1.Items.Add(myItem);
}
ListBox2.Items.Clear();
}

protected void moveup_btn_Click(object sender, EventArgs e)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
if (ListBox2.Items[i].Selected)
{
if (i > 0 && !ListBox2.Items[i - 1].Selected)
{
ListItem bottom = ListBox2.Items[i];
ListBox2.Items.Remove(bottom);
ListBox2.Items.Insert(i - 1, bottom);
ListBox2.Items[i - 1].Selected = true;
}
}
}

}
protected void movedown_btn_Click(object sender, EventArgs e)
{
int startindex = ListBox2.Items.Count - 1;
for (int i = startindex; i > -1; i--)
{
if (ListBox2.Items[i].Selected)
{
if (i < startindex && !ListBox2.Items[i + 1].Selected)
{
ListItem bottom = ListBox2.Items[i];
ListBox2.Items.Remove(bottom);
ListBox2.Items.Insert(i + 1, bottom);
ListBox2.Items[i + 1].Selected = true;
}
}
}
}

Creating Sessions in asp.net

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

if (Session["selected_cols"] != null)
{
datacols = Convert.ToString(Session["selected_cols"]);

}

Session["selected_cols"] = temp;

Highlighting gridview rows when mouseover and mouseout

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

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex != -1)
{
e.Row.Attributes.Add("onMouseOver", "this.style.background='#D3D3D3'");
e.Row.Attributes.Add("onMouseOut", "this.style.background='#ffffff';this.style.color='#000066'");
e.Row.Attributes.Add("onClick", "this.style.background='#009ACD';this.style.color='white'");
}

}

Summing up the gridview column values

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

int total;
bool ck=false;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.Header)
{
if (e.Row.Cells[i].Text == "Field_Name")
{
ck = true;
}
}


if (e.Row.RowType == DataControlRowType.DataRow)
{
if (ck == true)
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Field_Name"));

}

if (e.Row.RowType == DataControlRowType.Footer)
{
if (ck_Off == true)
e.Row.Cells[GetColumnIndexByHeaderText(GridView1, "Field_Name")].Text = off_Total.ToString();
}

}

Getting Column Index in gridview

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

static public int GetColumnIndexByHeaderText(GridView aGridView, String ColumnText)
{
TableCell Cell;
for (int Index = 0; Index < aGridView.HeaderRow.Cells.Count; Index++)
{
Cell = aGridView.HeaderRow.Cells[Index];
if (Cell.Text.ToString() == ColumnText)
return Index;
}
return -1;
}

GetColumnIndexByHeaderText(GridView1, "Field_Name");

Class (.cs) file binding data to chart from database

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

public void chart(string sqlstr, string xval, string yval, Chart chartname)
{
ArrayList yVal_Overall = new ArrayList();
ArrayList xVal_Overall = new ArrayList();

string connectionInfo = ConfigurationManager.AppSettings["ConnectionInfo"];
MySqlConnection con = new MySqlConnection(connectionInfo);
con.Open();

cmd = new MySqlCommand(sqlstr, con);

dr = cmd.ExecuteReader();
while (dr.Read())
{
skillname = dr[xval].ToString();
queuecount = Convert.ToInt32(dr[yval]);
xVal_Overall.Add(skillname);
yVal_Overall.Add(queuecount);
}
dr.Close();
chartname.Series[0].Points.DataBindXY(xVal_Overall, yVal_Overall);

con.Close();

}


Datachart chart_class = new Datachart();
chart_class.chart("call chart", " Field_Name1", " Field_Name2", Chart1);

Class (.cs) file binding data to gridview from database

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


public void fileread(string sqlstr, GridView grdview)
{
try
{
string connectionInfo = ConfigurationManager.AppSettings["ConnectionInfo"];
MySqlConnection con = new MySqlConnection(connectionInfo);
con.Open();

cmd = new MySqlCommand(sqlstr, con);
dr = cmd.ExecuteReader();
grdview.DataSource = dr;
grdview.DataBind();
dr.Close();

con.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}

Dataread drgrd = new Dataread();
drgrd.fileread("select * from table", GridView1);

Database Connection Settings in Web.Config

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



Monday, August 29, 2011

Upload data files in a folder

--------------------------------
if (Directory.Exists(TextBox1.Text))
{
filePaths = Directory.GetFiles(TextBox1.Text);

foreach (string filepath in filePaths)
{
filename = Path.GetFileName(filepath);
dt = File.GetCreationTime(filepath);

cmd = new SqlCommand("select count(*) from Date where File_Name = '" + date + " " + filename + "'", con);

int userCount = (int)cmd.ExecuteScalar();
Label1.Text = userCount.ToString();
if (Label1.Text == "0")
{
datefn();
pathinsert = filepath;
pathinsert = pathinsert.Replace("\\", "/");
insertdata();
ListBox1.Items.Add(filename);
Label8.Text = "Total files added are " + ListBox1.Items.Count.ToString() + " and newly added files have been listed below";
}

}

}


protected void datefn()
{
cmd = new SqlCommand("insert into Date (File_Name,Date_Modified) values('" + date + " " + filename + "','" + dt + "')", con);
cmd.ExecuteNonQuery();
}
protected void insertdata()
{
try
{
// cmd = new SqlCommand("LOAD DATA LOCAL INFILE '" + pathinsert + "' INTO TABLE echi_db FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'", con);

cmd = new SqlCommand("BULK INSERT tabname FROM '" + pathinsert + "' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' )", con);
cmd.CommandTimeout = 60000;
cmd.ExecuteNonQuery();


filename = " " + filename;
cmd = new SqlCommand("update db set FileName='" + date + filename + "' where len(FileName)=1", con);
cmd.CommandTimeout = 60000;
cmd.ExecuteNonQuery();


}
catch
{

}
}

Count variable using AJAX Timer Control

------------------------------
int Counter = 60;
int i;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Counter"] = Counter;
}

}


protected void Timer1_Tick(object sender, EventArgs e)
{
i = (int)ViewState["Counter"];

if (i == 0)
{
i = Convert.ToInt32(TextBox1.Text);
ViewState["Counter"] = i;
fileread();

}
else
{
i--;
ViewState["Counter"] = i;

}
Label6.Text = "Time left to refresh : " + ViewState["Counter"].ToString();
}

Wednesday, August 24, 2011

Link for Sample files in .NET

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

https://skydrive.live.com/?cid=2c5f5b0560e374cb&id=2C5F5B0560E374CB!130

Tuesday, August 23, 2011

Process Kill using .NET

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

foreach (Process clsProcess in Process.GetProcesses())
{
string concheck = clsProcess.ToString();

clsProcess.Kill();

}

Execute command prompt in .NET

-----------------------------------
using System.Diagnostics;

System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;

cmd = new MySqlCommand("select * from table", con);
dr=cmd.ExecuteReader();
while (dr.Read())
{
path = dr["Fileloc"].ToString();

string[] words = path.Split(new Char[] { '\\' });
drive = words[0];
filename = words[1];

si.StartInfo.WorkingDirectory = drive + "\\";
si.StartInfo.Arguments = "/c " + filename;

si.Start();
string output = si.StandardOutput.ReadToEnd();

error_lbl.Text += si.StandardError.ReadToEnd()+"\n";
si.Close();

}
dr.Close();

Wednesday, August 3, 2011

Chart using ASP.NET

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

using System.Web.UI.DataVisualization.Charting;

ArrayList yVal_Overall = new ArrayList();
ArrayList xVal_Overall = new ArrayList();
overallcmd = new SqlCommand("Select * from Customer", con);
overallrdr = overallcmd.ExecuteReader();
while (overallrdr.Read())
{
agentname = overallrdr["Col1"].ToString();
overallcount = Convert.ToInt32(overallrdr["Col2"]);
xVal_Overall.Add(agentname);
yVal_Overall.Add(overallcount);

}

overallrdr.Close();

Chart1.Series[0]["PieLabelStyle"] = "Inside";
Chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
Chart1.Titles.Add("Points of Failure");
Chart1.Series[0].Points.DataBindXY(xVal_Overall, yVal_Overall);


//if (overallcount > 2)
//{
// Chart1.Series[0].Points[0]["Exploded"] = "true";
// Chart1.Series[0].Points[1]["Exploded"] = "true";
// Chart1.Series[0].Points[2]["Exploded"] = "true";

Run exe using asp.net

-------------------
using System.Diagnostics;

string batchpath = @"C:\run.bat";
System.Diagnostics.Process.Start(batchpath);

//System.Diagnostics.Process si = new System.Diagnostics.Process();
//si.StartInfo.WorkingDirectory = "c:\\";
//si.StartInfo.UseShellExecute = false;
//si.StartInfo.FileName = "cmd.exe";
//si.StartInfo.Arguments = "/c notepad.exe";
//si.StartInfo.CreateNoWindow = true;
//si.StartInfo.RedirectStandardInput = true;
//si.StartInfo.RedirectStandardOutput = true;
//si.StartInfo.RedirectStandardError = true;
//si.Start();
//string output = si.StandardOutput.ReadToEnd();
//si.Close();
//Response.Write(output);

Facebook API with ASP.NET

Links
------

http://www.kennetham.com/2010/07/21/facebook-api-asp-net/

http://computerbeacon.net/downloads/

Thursday, July 21, 2011

Data Adapter to retreive DB columns

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

MySqlDataAdapter adapter = new MySqlDataAdapter();
String listcmd = "SELECT * FROM venkat_db";
adapter.SelectCommand = new MySqlCommand(listcmd, listcon);
DataSet ds = new DataSet();
adapter.Fill(ds, "venkat_db");
DataTable item = ds.Tables[0];

foreach (DataColumn col in item.Columns)
{
ListBox1.Items.Add(col.ColumnName.ToString());

}

MySQL Connector using ASP.NET

-------------------------
1. Download MySQL Connector for .NET
2. Install the MSI
3. Add Web reference to your project
4. Create database connection with MySQL namespace

File Read and Write

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

StreamWriter writepath = new StreamWriter(@"C:\venkat\temp.txt");
filePaths = Directory.GetFiles(@"C:\venkat\" + date);

foreach (string fileName in filePaths)
{
filename = fileName;
}

rdr = new StreamReader(filename);
string textline = "";

while (rdr.Peek() != -1)
{
textline = textline + rdr.ReadLine();
textline = textline.Remove(textline.Length - 1, 1);
textline += "\n";
}
writepath.Write(textline.ToString());

Response.Write(textline);
writepath.Close();
rdr.Close();

Select row in Gridview

-------------------
GridViewRow row = GridView1.SelectedRow;
row.Cells[1].Text

Convert datetime format

------------------------
DateTime startdatestr = new DateTime();
startdatestr = Convert.ToDateTime(TextBox1.Text);
HiddenField1.Value = startdatestr.ToString("yyyyMMdd");

Grid view word wrap

-------------------
protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].Attributes.Add("style", "white-space:nowrap;");
}
}

Export DB to Excel

------------------
public void writer()
{
attachment = "attachment; filename=Export.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
return;

}

Gridview databind

-----------
GridView1.DataSource = getrecordrdr;
GridView1.DataBind();

Dynamic Navigation Menu add & remove

--------------------------------------
Menu4.Items[0].ChildItems[4].ChildItems.RemoveAt(1);
Menu4.Items[0].ChildItems.RemoveAt(7);

Data Read from DB

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

con = new SqlConnection("server=10.2.1.31;database= ;user id=sa;password=password;connection timeout=60000");
con.Open();

SqlCommand checkcmd = new SqlCommand("select * from Login where Login_ID=@userid", con);
checkcmd.Parameters.Add("@userid", TextBox1.Text);
SqlDataReader checkrdr = checkcmd.ExecuteReader();
while (checkrdr.Read())
{
loginID = checkrdr["Login_ID"].ToString();
ename = checkrdr["User_Name"].ToString();
}

checkrdr.Close();
con.Close();

Cookie Creation and Accession

--------------------------
HttpCookie userCookie;
userCookie = new HttpCookie("UserInfo");
userCookie.Values["username"] = ename;
userCookie.Values["loginID"] = loginID;
userCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(userCookie);

userCookie = Request.Cookies["UserInfo"];
username_lbl.Text = userCookie.Values["username"];

userCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(userCookie);
Response.Redirect("login.aspx");

File Data Uploader to DB

-------------------
string filename;
string date;
StreamReader rdr;

MySqlConnection con;
MySqlCommand cmd;
string[] filePaths;
DateTime dt;

protected void Timer1_Tick(object sender, EventArgs e)
{
con = new MySqlConnection("Server=10.2.1.31;Database= ;uid=root;pwd= ;Connection Timeout=6000");
con.Open();

date = DateTime.Now.ToString();
DateTime startdatestr = new DateTime();
startdatestr = Convert.ToDateTime(date);

date = startdatestr.ToString("MM-dd-yyyy");

Label1.Text = date;

if (Directory.Exists(@"C:\venkat\" + date))
{
filePaths = Directory.GetFiles(@"C:\venkat\" + date);

foreach (string fileName in filePaths)
{
dt = File.GetCreationTime(fileName);
filename = Path.GetFileName(fileName);
DropDownList1.Items.Add(date + " " + filename);
cmd = new MySqlCommand("select count(*),File_Name from Date where File_Name = '" + date + " " + filename + "'", con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Label1.Text = dr["count(*)"].ToString();
if (Label1.Text == "0")
{
dr.Close();
Response.Write(filename + " newly added" + "
");
datefn();
insertdata();
break;
}
else
{
dr.Close();
break;
}
}

}
}
else
{
Response.Write("No folder exist");
}

}