Friday, March 13, 2009

get data from .txt file and insert into sql table.

protected void button_click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("ACCOUNT", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("CUSTOMER", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("TRADES", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("SHARES", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("COMMISSION", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("TRADES1", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("SHARES1", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("COMMISSION1", typeof(System.String));
dt.Columns.Add(dc);

string con = "Data Source=SERVERNAME;Database=DATABASENAME;Persist Security Info=True;User ID=USERNAME;Password=PWD";
SqlConnection myConnection = new SqlConnection(con);
const string strSQL = "select * from praveen";
SqlCommand myCommand = new SqlCommand(strSQL, myConnection);
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
SqlCommandBuilder cb = new SqlCommandBuilder(myAdapter);
myConnection.Open();

System.IO.StreamReader sr = new System.IO.StreamReader(@"C:/Documents and Settings/nitin.dhiman/Desktop/NYSE_MERGE_ORDER_LOG.doc");
string line;
int i = 0;
while (sr.Peek() != -1)
{
i++;
line = sr.ReadLine();
if (line.Contains("MTD TRADES"))
{
flage = 1;
}
if (line.Contains("/PAGE"))
{
flage = 0;
}
if (line.Contains("TOTALS"))
{
flage = 0;
}
if (flage == 1)
{
if (line == "" || line == " " || line == " ACCOUNT CUSTOMER TRADES SHARES COMMISSION TRADES SHARES COMMISSION " || line == "---------- ------------------------------ ---------- --------------- --------------- --------- --------------- --------------- " || line == " ---------- MTD TRADES ---------- ---------- MTD SETTLES ---------- ")
{

}
else
{
string value = line;
value = value.Replace(" ", "~");
value = value.Replace("~~~~~~~~~", "~");
value = value.Replace("~~~~~~~~", "~");
value = value.Replace("~~~~~~~", "~");
value = value.Replace("~~~~~~", "~");
value = value.Replace("~~~~~", "~");
value = value.Replace("~~~~", "~");
value = value.Replace("~~~", "~");
value = value.Replace("~~", "~");
string[] text = value.Split('~');

DataRow dr = dt.NewRow();
dr[0] = text[0];
dr[1] = text[1];
dr[2] = text[2];
dr[3] = text[3];
dr[4] = text[4];
dr[5] = text[5];
dr[6] = text[6];
dr[7] = text[7];
dt.Rows.Add(dr);

myAdapter.Update(dt);
dt.AcceptChanges();
}
}
}
Response.Write(i);
}

get data from xml file.

call following function:


public void abc()
{
StreamReader stream1 = new StreamReader("C:\\Inetpub\\wwwroot\\PR\\TreeNormal\\books.xml");
XmlTextReader reader = null;
reader = new XmlTextReader(stream1);

while (reader.Read())
{
// Do some work here on the data.
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element.
Response.Write("<" + reader.Name);
Response.Write(">
");
break;
case XmlNodeType.Text: //Display the text in each element.
Response.Write("
" + reader.Value);
break;
case XmlNodeType.EndElement: //Display end of element.
Response.Write(" Response.Write(">
");
break;
}

//Response.Write(reader.Name + " ");
}

while (reader.Read())
{
// Do some work here on the data.
//Console.WriteLine(reader.Name);
Response.Write(reader.Name);
}



}

Bind TreeView to sql database.

Call the following function in page_load event:


void fill_Tree()
{
//Database db = DatabaseFactory.CreateDatabase("ConStr");
//string sqlCommandName = "Select * from ParentTable";
//DbCommand dbCmd = db.GetSqlStringCommand(sqlCommandName);
//SqlDataReader Sdr = dbCmd.ExecuteReader();

/ SqlCon = new SqlConnection("Data Source=DATABASENAME;Initial Catalog=GKTraining;Persist Security Info=True;User ID=USERID;Password=gK@t#a!n!^T)");

SqlCon.Open();

/*
* Query the database
*/

SqlCommand SqlCmd = new SqlCommand("Select * from a_tbl_parent", SqlCon);

/*
*Define and Populate the SQL DataReader
*/

SqlDataReader Sdr = SqlCmd.ExecuteReader();

/*
* Dispose the SQL Command to release resources
*/

SqlCmd.Dispose();

/*
* Initialize the string ParentNode.
* We are going to populate this string array with our ParentTable Records
* and then we will use this string array to populate our TreeView1 Control with parent records
*/

string[,] ParentNode = new string[100, 2];

/*
* Initialize an int variable from string array index
*/

int count = 0;

/*
* Now populate the string array using our SQL Datareader Sdr.

* Please Correct Code Formatting if you are pasting this code in your application.
*/

while (Sdr.Read())
{

ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("ParentID")).ToString();
ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("ParentName")).ToString();

}

/*
* Close the SQL datareader to release resources
*/

Sdr.Close();

/*
* Now once the array is filled with [Parentid,ParentName]
* start a loop to find its child module.
* We will use the same [count] variable to loop through ChildTable
* to find out the number of child associated with ParentTable.
*/

for (int loop = 0; loop < count; loop++)
{

/*
* First create a TreeView1 node with ParentName and than
* add ChildName to that node
*/

TreeNode root = new TreeNode();
root.Text = ParentNode[loop, 1];
root.Target = "_blank";

/*
* Give the url of your page
*/

root.NavigateUrl = "mypage.aspx";

/*
* Now that we have [ParentId] in our array we can find out child modules

* Please Correct Code Formatting if you are pasting this code in your application.

*/

SqlCommand Module_SqlCmd = new SqlCommand("Select * from a_tbl_child where ParentId =" + ParentNode[loop, 0], SqlCon);

SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();

while (Module_Sdr.Read())
{

// Add children module to the root node

TreeNode child = new TreeNode();

child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString();

child.Target = "_blank";

//child.NavigateUrl = "your_page_Url.aspx";
child.NavigateUrl = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString()+".aspx";

root.ChildNodes.Add(child);

}

Module_Sdr.Close();

// Add root node to TreeView
TreeView1.Nodes.Add(root);

}

/*
* By Default, when you populate TreeView Control programmatically, it expends all nodes.
*/
TreeView1.CollapseAll();
SqlCon.Close();

}

Asp calendar DayRender event.

Hi,

Here is the asp:calendar DayRender event example:



protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
string fontWeight = "normal";
if (isThereEvent(e.Day.Date))
fontWeight = "bold";

string color = "black";
if (e.Day.IsOtherMonth)
color = this.Calendar1.OtherMonthDayStyle.ForeColor.Name;

e.Cell.Text = String.Format("<a href="http://www.blogger.com/Default.aspx?day=%7B0:d%7D" style="text-decoration: none;">{1}</a>", e.Day.Date, e.Day.Date.Day);
}

private bool isThereEvent(DateTime date)
{
DateTime today = DateTime.Now;
DateTime tomorrow = today.AddDays(1);
DateTime anotherDay = today.AddDays(3);

// there are events today
if ((date.DayOfYear == today.DayOfYear) && (date.Year == today.Year))
return true;

// there are events tomorrow
if ((date.DayOfYear == tomorrow.DayOfYear) && (date.Year == tomorrow.Year))
return true;

// there are events on another day
if ((date.DayOfYear == anotherDay.DayOfYear) && (date.Year == anotherDay.Year))
return true;

return false;
}

Thursday, March 12, 2009

Data Scraping.

Call following function for scraping:


protected void GetValueofFirstPage()
{
DataTable dt = new DataTable();
dt = CreateTable();
string strURL = "http://wsa2009.expoplanner.com/plsearch.wcs?searchby=all&seekword=null&alpha=all&filter=";
String strResult;
WebResponse objResponse;
WebRequest objRequest = HttpWebRequest.Create(strURL);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
//strResult = sr.ReadToEnd();

while ((strResult = sr.ReadLine()) != null)
{
if (strResult.Contains("Booth"))
{
flage = 1; ;
}
if (flage == 1)
{
if (strResult.Contains("href") && strResult.Contains("?"))
{
DataRow dr = dt.NewRow();
string[] str = strResult.Split('>');
string[] path = str[0].Split('\"');
str[1] = str[1].Replace("ANCHOR TAG END ~<~/~A~", "");
dr[0] = str[1];
dr[1] = "http://wsa2009.expoplanner.com/" + path[1];
dt.Rows.Add(dr);
Response.Write(str[1] + ' ' + path[1]);
Response.Write("LINE BREAK <~B~R~/~>");
//Session["dt"] = dt.ToString();
Session["dt"] = dt;
}
}
}

sr.Close();
flage = 0;
}
grd.DataSource = dt;
grd.DataBind();
}

Managing treeview in asp.net

TreeView1.Nodes.Clear();


TreeNode ndHome = new TreeNode("Home", "Home", "~/closebox.png", "~/Home.aspx", "");
TreeNode ndSplitter = new TreeNode("Splitter", "Splitter", "~/closebox.png", "~/Splitter.aspx", "");
TreeNode ndCheckPage = new TreeNode("Check Page", "Check Page",
"~/closebox.png", "~/CheckPage.htm", "");
TreeNode ndSearch = new TreeNode("Search", "Search", "~/closebox.png", "~/Search.aspx", "");
TreeNode ndAdvancedSearch = new TreeNode("Advanced Search", "Advanced Search",
"~/closebox.png", "~/AdvancedSearch.aspx", "");
TreeNode ndTxtChk = new TreeNode("TextBox", "TextBox", "~/closebox.png", "~/TextCheck.aspx", "");
TreeNode ndLogout = new TreeNode("Logout", "Logout", "~/closebox.png", "~/Logout.aspx", "");
TreeNode ndExtra = new TreeNode("Extra", "Extra", "~/closebox.png", "#", "");
TreeView1.Nodes.Add(ndHome);
TreeView1.Nodes[0].ChildNodes.Add(ndCheckPage);
TreeView1.Nodes.Add(ndSplitter);
//TreeView1.Nodes[0].ChildNodes.Add(ndAdvancedSearch);
TreeView1.Nodes.Add(ndSearch);
TreeView1.Nodes[2].ChildNodes.Add(ndAdvancedSearch);
TreeView1.Nodes.Add(ndLogout);
TreeView1.Nodes.Add(ndExtra);
TreeView1.Nodes[4].ChildNodes.Add(ndTxtChk);

Read data from xml file.

public void abc()
{
StreamReader stream1 = new StreamReader("C:\\Inetpub\\wwwroot\\PR\\TreeNormal\\books.xml");
XmlTextReader reader = null;
reader = new XmlTextReader(stream1);

while (reader.Read())
{
// Do some work here on the data.
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element.
Response.Write("<" + reader.Name); Response.Write(">
");
break;
case XmlNodeType.Text: //Display the text in each element.
Response.Write("
" + reader.Value);
break;
case XmlNodeType.EndElement: //Display end of element.
Response.Write("
");
break;
}

//Response.Write(reader.Name + " ");
}

while (reader.Read())
{
// Do some work here on the data.
//Console.WriteLine(reader.Name);
Response.Write(reader.Name);
}
}

Incorporate Google Map to page.

SCRIPT START HERE src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAchOdSzCPe0fgAm8Ow24YYhQZMjxVy-0fy3B1JroJth17tbEUrRQwDlqM1PUlwiawvBO4RMVpYVIfLA"
type="text/javascript"
/SCRIPT END HERE

2ND SCRIPT TAG START HERE

var map = null;
var geocoder = null;

function load()
{
if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

geocoder = new GClientGeocoder();
var address =document.getElementById('TextBox1').value;

showAddress(address);
}
return false;
}
function showAddress(address)
{
if (geocoder)
{
geocoder.getLatLng(address,function(point) {
if (!point) {alert(address + " not Valid Address ");}
else {
map.setCenter(point, 13);

var baseIcon = new GIcon();
baseIcon.shadow = "images/star_location.gif";

baseIcon.iconSize = new GSize(19, 18);
baseIcon.shadowSize = new GSize(19, 18);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
function createMarker(point, index) {
// Create a lettered icon for this point using our icon class
var letter = String.fromCharCode("A".charCodeAt(0) + index);
var icon = new GIcon(baseIcon);
icon.image = "images/star_location.gif";
var marker = new GMarker(point, icon);

GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(address);});
return marker;
}

map.addOverlay(createMarker(point, 13));
}
}
);
}
}
/2ND SCRIPT TAG END HERE.


//DIV IN HTML PAGE

divSTART id="map" style="width: 600px; height: 600px;">
/divEND

//BUTTON BODY:

asp:button id="Button1" onclientclick="javascript:return load();" runat="server" text="Button"

Google Search in asp.net page.

asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server"
//put the following line in script:

putScriptHere src="http://www.google.com/jsapi?key=ABQIAAAAchOdSzCPe0fgAm8Ow24YYhQZMjxVy-0fy3B1JroJth17tbEUrRQwDlqM1PUlwiawvBO4RMVpYVIfLA"
type="text/javascript"

//put following also in script tag

google.load("search", "0");

function OnLoad() {
// Create a search control
var searchControl = new google.search.SearchControl();

// Add in a full set of searchers
var localSearch = new google.search.LocalSearch();
searchControl.addSearcher(localSearch);
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.VideoSearch());
searchControl.addSearcher(new google.search.BlogSearch());

// Set the Local Search center point
localSearch.setCenterPoint("New Delhi, INDIA");

// Tell the searcher to draw itself and tell it where to attach
searchControl.draw(document.getElementById("searchcontrol"));

// Execute an inital search
searchControl.execute("");
}
google.setOnLoadCallback(OnLoad);


divSTART id="searchcontrol"
Loading.../divEND
/asp:content

javascript to find day difference.

HTML START
HEAD START HERE
SCRIPT START HERE language="javascript" type="text/javascript"
today = new Date();
todayEpoch = today.getTime();

target = new Date("1 Jan, 2009");
targetEpoch = target.getTime();

daysLeft = Math.floor(((targetEpoch - todayEpoch) / (60*60*24)) / 1000);
SCRIPT END HERE

HEAD END
BODY START HERE
FROM START method="get" action="http://www.google.com/search"

DoD inspection in

SCRIPT START HERE document.write(daysLeft); SCRIPT TAG END HERE

days. Are you ready?

FORM END
BODY END
HTML END

Create bound control column in a grid.

public void createBoundCols()
{
DataTable dt = ds.Tables[0];

int countDt = 0;
foreach (DataColumn col in dt.Columns)
{
if (countDt < 12)
{
BoundField bfield = new BoundField();
bfield.DataField = col.ColumnName;
bfield.HeaderText = col.ColumnName;
GrdDynamic.Columns.Add(bfield);
countDt = countDt + 1;
}

}

CommandField cf = new CommandField();
cf.HeaderText = "print";

cf.ShowSelectButton = true;
cf.SelectText = "Print";
cf.Visible = true;


GrdDynamic.Columns.Add(cf);

}



// and on grid row command so that we can fire the event associated with the created bound column.



protected void GrdDynamic_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);

// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = GrdDynamic.Rows[index];
int rowid = Convert.ToInt32(row.Cells[0].Text.ToString());
Response.Redirect("RecordDetails.aspx?rID=" + rowid);

}
}

print all data on a page.

Hi,

Here is the javascript code to print all the data on the page:

scriptSTART language="javascript" type="text/javascript"

function printdoc()
{
var div=document.getElementById("DivPrint");

//to hide the undesired DIV from print page.
div.style.display='none';
window.print();
return true;
}

/scriptEND


asp:button id="btnPrint" runat="server" width="90px" text="Print" onclientclick="printdoc();"

Export to excel, word in .net

Hi,

Here is the code to export the grid data to excel or word:

// create an enum
public enum ExportType
{

EXCEL,

PDF,

WORD
}

//source can be DataSet, DataTable and etc
public void ExportDataGrid(object source, ExportType type)
{
try
{
// setting temporarily datagrid
DataGrid dg = new DataGrid();
dg.ID = "GridView1";
dg.DataSource = source;
dg.AutoGenerateColumns = true;
dg.AllowPaging = false;
dg.AllowSorting = false;
dg.DataBind();
// export selected format
Response.Clear();
Response.Buffer = true;
switch ((type))
{
case ExportType.EXCEL:
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "ExportedGridData"));
break;
case ExportType.PDF:
break;
// TODO
case ExportType.WORD:
Response.ContentType = "application/ms-word";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.doc", "ExportedGridData"));
break;
}
Response.Charset = "";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
dg.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
catch (Exception ex)
{
if ((ex.Message != "Thread was being aborted."))
{
Response.Write(("Error occur while exporting excel. For more information:" + ex.Message));
}
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.EXCEL);
}
}
protected void btnExportToWord_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.WORD);
}
}

protected void btnExportToPDF_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.PDF);
}
}

Get 1st day of week using C#.

Hi,

Here is the code to get date on 1st day of week, we just need to call this function with date:


private static DateTime firstDayOfWeek(DateTime day, DayOfWeek weekStarts)
{
DateTime d = day;
while (d.DayOfWeek != weekStarts)
{
d = d.AddDays(-1);
}

return d;
}


and to call this function:


DateTime myDate = firstDayOfWeek(DateTime.Now, DayOfWeek.Sunday);

from Excel file to Sql table.

Hello again,

Here is the code to fill sql table from data in excel file:

protected void button_click(object sender, EventArgs e)
{
string sqlTblName = "nitinSongs";
string excelFileName = "WT_codes.xls";
string workBook = "[nitin$]";
string exlConStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("WT_codes.xls") + ";" + "Extended Properties=Excel 8.0;";
string sqlConStr = "Data Source=SERVER NAME;Database=DATABASE NAME;Persist Security Info=True;User ID=LOGINID;Password=PASSWORD";

SqlConnection sqlCon = new SqlConnection(sqlConStr);
SqlCommand sqlCom = new SqlCommand("DELETE FROM " + sqlTblName, sqlCon);
sqlCon.Open();
sqlCom.ExecuteNonQuery();
sqlCon.Close();

OleDbConnection oleCon = new OleDbConnection(exlConStr);
OleDbCommand oleCom = new OleDbCommand("select * from " + workBook, oleCon);
oleCon.Open();
OleDbDataReader dr = oleCom.ExecuteReader();
SqlBulkCopy bCopy = new SqlBulkCopy(sqlConStr);
bCopy.DestinationTableName = sqlTblName;
bCopy.WriteToServer(dr);
oleCon.Close();
}