Feeds:
Posts
Comments

Archive for the ‘Programming’ Category

Let we have a string[] array and a ArrayList of String. We would like to convert ArrayList to String[] .

static string[] userNameList;
ArrayList userNameAl = new ArrayList( );

userNameList = (string[])userNameAl.ToArray(typeof(string));

Advertisements

Read Full Post »

In Asp.Net 2.0 and Asp.Net 3.5 we have a Tag Inside Web.config file that is ConnectionString Tag.

<connectionStrings>
<add name=”MyConnStringconnectionString=”Server=ServerName;Database=DBName;Uid=UserId;Pwd=Passwd;providerName=”System.Data.SqlClient/>
</connectionStrings>

Now to get the Connection string defined in the web.config file you have to do like this in your .cs  file below code is based on C#

string Conn= ConfigurationManager.ConnectionStrings[“MyConnString“].ConnectionString;

In Vb.NET

Dim Conn as String = ConfigurationManager.ConnectionStrings(“MyConnString“).ConnectionString

Read Full Post »

This tutorial will show you how to delete a file on the disk using ASP.NET 2.0 and C#.NET

To delete a simple file on the disk, we will need to first import the System.IO namespace. The System.IO namespace contains the File.Delete() method and FileInfo type that we will use to perform our delete with.

using System.IO

We’ll put our code in the btnSubmit_Click() event.

When the btnSubmit_Click() event fires it first checks to see if the file exists using the FileInfo type. If it exists it runs the File.Delete() method to delete it, otherwise it throws a FileNotFoundException which is caught by one of the catch statements below the try block.

protected void btnSubmit_Click(object sender, EventArgs e)
{

try {

FileInfo TheFile = new FileInfo(MapPath(“.”) + “\\” + txtFile.Text);
if (TheFile.Exists) {
File.Delete(MapPath(“.”) + “\\” + txtFile.Text);
}

else {

throw new FileNotFoundException();
}

}
catch (FileNotFoundException ex) {

lblStatus.Text += ex.Message;

}
catch (Exception ex) {

lblStatus.Text += ex.Message;

}

}

We have one textbox, a Submit button, a label, and a checkbox on the front end for user interaction. The front end .aspx page looks something like this:

<table width=”600″ border=”0″ align=”center” cellpadding=”5″ cellspacing=”1″ bgcolor=”#cccccc”>

<tr>

<td width=”100″ align=”right” bgcolor=”#eeeeee”> File to Delete:</td>
<td align=”center” bgcolor=”#FFFFFF”>
<asp:TextBox ID=”txtFile” runat=”server”></asp:TextBox>
<br />
<asp:Button ID=”btnSubmit” runat=”server” Text=”Submit” OnClick=”btnSubmit_Click” /><br /> &nbsp;
<asp:label ID=”lblStatus” runat=”server”></asp:label></td>

</tr>

</table>

The flow for the code behind page is as follows.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnSubmit_Click(object sender, EventArgs e)
{

try {

FileInfo TheFile = new FileInfo(MapPath(“.”) + “\\” + txtFile.Text);
if (TheFile.Exists) {
File.Delete(MapPath(“.”) + “\\” + txtFile.Text);
}

else {

throw new FileNotFoundException();
}

}catch (FileNotFoundException ex) {

lblStatus.Text += ex.Message;

}
catch (Exception ex) {

lblStatus.Text += ex.Message;

}

}

Read Full Post »

Sometimes we may need to upload data files from user end to Server side. The following program will perform that task.

Here is the .aspx file code :

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”DataTransfer.aspx.cs” Inherits=”DataTransfer” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Data Transfer</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>

<asp:FileUpload ID=”FileUpload1″ runat=”server” /><br />
<asp:Button ID=”upButton” runat=”server” OnClick=”upButton_Click” Text=”File Upload” />
<asp:Label ID=”lblTransferMsg” runat=”server”></asp:Label><br />

</div>
</form>
</body>
</html>

Here is the .cs code::

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;

public partial class DataTransfer : System.Web.UI.Page
{

protected HtmlInputFile myInputFile;
SqlConnection connection = null;
static string fileNameWithLocation = “”;

protected void Page_Init(object sender, EventArgs e)
{
//connection = new SqlConnection(“Data Source=CSE;Initial Catalog=razibdb;Integrated Security=True”);
connection = new SqlConnection(“server=’SERVERNAME’;uid= ‘USERID’;” + “pwd=’PASSWORD’;database=DATABASE; Connect Timeout=10000”);
}

protected void Page_Load(object sender, EventArgs e)

{
}

protected void upButton_Click(object sender, EventArgs e)
{
HttpPostedFile myFile = FileUpload1.PostedFile;
if (myFile.FileName != “” && myFile.ContentLength > 0)
{
String ServerFileName = Path.GetFileName(myFile.FileName);
fileNameWithLocation = “C:\\” + ServerFileName;
myFile.SaveAs(fileNameWithLocation);

SendDataToTable( );
DeleteXLSFile( );
}
else
{
lblTransferMsg.ForeColor = System.Drawing.Color.Red;
lblTransferMsg.Text = “Select a File !!!”;
}
}

private void DeleteXLSFile( )
{
try
{
FileInfo theFile = new FileInfo(“C:\\a.xls”);
if (theFile.Exists)
File.Delete(“C:\\a.xls”);
else
throw new FileNotFoundException();
}
catch (FileNotFoundException fnfe)
{
Response.Write(fnfe.Message);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

private void SendDataToTable( )
{
DeleteDataFromTable( );
String strSQL = “”;
strSQL = “Insert into ReportTable Select * FROM OPENROWSET”;
strSQL += “(‘Microsoft.Jet.OLEDB.4.0’,’Excel 8.0;Database=” + fileNameWithLocation + “;”;
strSQL += “HDR = YES ‘,’SELECT * FROM [a$]’)”;

SqlCommand myCommand = new SqlCommand(strSQL, connection);
try
{
connection.Open( );
myCommand.ExecuteNonQuery( );
connection.Close( );

lblTransferMsg.ForeColor = System.Drawing.Color.Green;
lblTransferMsg.Text = “Transfer success”;
}
catch (Exception ex) { Response.Write(ex.ToString()); }

}

private void DeleteDataFromTable( )
{
String strSQL = “”;
strSQL = “DELETE FROM ReportTable”;
SqlCommand myCommand = new SqlCommand(strSQL, connection);
try
{
connection.Open( );
myCommand.ExecuteNonQuery( );
connection.Close( );
}
catch (Exception ex) { Response.Write(ex.ToString( )); }
}

//before uploading u have to create the table

Read Full Post »

If you’ve ever wanted to add an upload feature to your website that allows visitors to upload files to a the server, then this is the tutorial for you.

This code will open an OpenFileDialog box to allow the user to select a file.

<asp:TableCell>
    Select File:
    <input id="uplTheFile" type="file" runat="server" style="width: 476px; height: 26px" />
</asp:TableCell>

This code will add a button to the form to upload the file.

<asp:TableCell >
     <asp:Button ID="cmdUploadFile" value="Upload" runat="server" Text="Upload" OnClick="cmdUploadFile_Click" />
</asp:TableCell>

cmdUploadFile_Click Event (C#)

protected void cmdUploadFile_Click(object sender, EventArgs e)
{
string strFileNameOnServer = uplTheFile.PostedFile.FileName;
string appDataPath = HttpContext.Current.Server.MapPath(“~/App_Data”);

if (string.IsNullOrEmpty(strFileNameOnServer))
{
lblInformation.Text = “Error – a file name must be specified.”;
return;
}

if (uplTheFile.PostedFile != null)
{
try
{
uplTheFile.PostedFile.SaveAs(appDataPath + “\\” + strFileNameOnServer);
}
catch (Exception ex)
{
lblInformation.Text = “Error saving ” + strFileNameOnServer + “
. ” + ex.Message;
}
}
}

And it will work.

Read Full Post »

string srcTbl = “Table1”;
string tgtTbl = “Table2”;

DateTime inputDate = DateTime.ParseExact(From, “yyyyMMdd”, System.Globalization.CultureInfo.CurrentCulture);
string inDate = inputDate.ToShortDateString();

//here ‘From’ contains date in string format, i.e.  “20100125”

string deleteQuery = “DELETE FROM ” + tgtTbl + ” WHERE [Date]='” + inDate + “‘”;

string selectQuery = “SELECT name, addrs, city, [Date] FROM “+srcTbl + ” WHERE [Date]='” + inDate + “‘”;

string insertQry = “INSERT INTO ” + tgtTbl +”(name, addrs, city, [Date])”+ selectQuery1;

SqlCommand myCommand = new SqlCommand(insertQry, connection);
SqlCommand myCommandDel = new SqlCommand(deleteQuery, connection);

try
{
connection.Open();
myCommandDel.ExecuteNonQuery();
myCommand.ExecuteNonQuery();
connection.Close();
lblSuccessMsg.Text = “Inserted Successfully…”;
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}

Read Full Post »

Using Queries we can get rows and set that rows in our DataSet. But based on some rows we may need to calculate some values and if we want to add that values also in our dataset at runtime then we can do that in following way:

Suppose, we have a SQL query which select 5 fields from a table. Based upon 2 fields among those 5 fields we want to calculate percentage value and add that field at the last column of dataset.

SqlConnection connection = new SqlConnection(“server='” + server + “‘;” + “uid= ‘” + username + “‘;” + “pwd='” + password + “‘;” + “database=Attn; Connect Timeout=10000”);

string selectQuery = “SELECT Table1.[Date], Table1.[On duty], Table1.[Off duty], Table1.[Work Time], Table1.ATT_Time”

DataSet myDS = new DataSet(“MonthlyReport”);
DataTable dtMyTable = new DataTable(“EmpMonthlyReport”);

DataColumn myCol1;
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(selectQuery, connection);
DataRow myNewRow;
CrystalDecisions.CrystalReports.Engine.ReportDocument myReportDocument;
DataTable MyTable = new DataTable(“ETC_MR”);
DataColumn Col1;
DataRow NewRow;
Col1 = new DataColumn(“From”);

MyTable.Columns.Add(Col1);
NewRow = MyTable.NewRow();

MyTable.Rows.Add(NewRow);

MyTable.AcceptChanges();

try
{
connection.Open();
myReader = myCommand.ExecuteReader();
int fc = myReader.FieldCount;
int j=0;
for (int i = 0; i < fc; i++)
{
myCol1 = new DataColumn(myReader.GetName(i));
myCol1.DataType = myReader.GetFieldType(i);
if (myCol1.DataType.Equals(“string”)) { myCol1.MaxLength = 256; } else { }
myCol1.AllowDBNull = true;
dtMyTable.Columns.Add(myCol1);
}

dtMyTable.Columns.Add(“WHPercentage”, typeof(float));

float ATT_TimeResult = 0.0F, WorkTimeResult = 0.0F, pc = 0.0F;
float t1, t2;
while (myReader.Read())
{
myNewRow = dtMyTable.NewRow();
for (int i = 0; i < fc; i++)
{
myNewRow[i] = myReader[i];
j = i;
}

OnDuty = myReader[1].ToString();
OffDuty = myReader[2].ToString();

if ((string)myReader[4] != “”)
ATT_TimeResult = calcTime(myReader[4].ToString());

t1 = calcTime(OnDuty);
t2 = calcTime(OffDuty);
WorkTimeResult = (float)(t2 – t1);

if (WorkTimeResult > 0.0)
pc = ((float)ATT_TimeResult * 100) / (float)WorkTimeResult;
else
pc = 0.0F;

myNewRow[j + 1] = pc;//adding percentage at the last column

dtMyTable.Rows.Add(myNewRow);
dtMyTable.AcceptChanges();
count++;
ATT_TimeResult = 0.0F; WorkTimeResult = 0.0F;
}

myDS.Tables.Add(dtMyTable);
myDS.Tables.Add(MyTable);

myReportDocument = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
if (count > 0)
{
myReportDocument.Load(@Server.MapPath(“AttMonthlyReport.rpt”));
myReportDocument.SetDataSource(myDS);
myReportDocument.SetParameterValue(“rptMonth”, reportMonth);
CrystalReportViewer1.ReportSource = myReportDocument;
CrystalReportViewer1.DataBind();
}
else
{
myReportDocument.Load(@Server.MapPath(“NoData.rpt”));
CrystalReportViewer1.ReportSource = myReportDocument;
}

}
catch (Exception ce)
{
Response.Write(ce.ToString());
}
try
{
myReader.Close();
connection.Close();
}
catch (Exception cce)
{
Console.WriteLine(cce.ToString());
}

//split the time with ‘:’ and make that into float number; i.e. 08:30 –> 8.5
private float calcTime(string OnTime)
{
string[] splits = OnTime.Split(new char[] { ‘:’ });
int n1, n2;
float f3, f4;
n1 = Int32.Parse(splits[0]);
n2 = Int32.Parse(splits[1]);
f3 = (float)n2 / 60;
f4 = (float)n1 + f3;
return f4;
}

Read Full Post »