What is ZRangeValid means - asp.net

This code is to read an excel file, what is ZRangeValid means and what is rs.fields(0).value referring to? Please explain my two questions
var strConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strXLPath + ";Extended Properties=\"Excel 12.0;HDR=YES;\";";
var conn = new ActiveXObject("ADODB.Connection");
conn.open(strConnString, "", "");
var rs = new ActiveXObject("ADODB.Recordset");
var rsrowCount = new ActiveXObject("ADODB.Recordset");
rs = conn.execute("select * from ZRangeValid");
if (rs.fields(0).value != 'YES') {
alert(strXLPath + " requested numbers spreadsheet is not valid.\nPlease validate the spreadsheet data and retry.")
rs = null;
rsSheet = null;
conn.close();
conn = null;
return false
}

Related

The process cannot access the file.xlsx' because it is being used by another process. While Exporting Data from ASPX to an EXCEL file

When I try to Export I got an Exception which says that the "Process cannot access the file "Mypath\Filename.xlsx" because it is being used by another process"
The Exception is Thrown when I try to Export and it is tracked back to the Line byte[] content = File.ReadAllBytes(fileName); So I don't Understand the Problem.
Am Not Using File stream to Read data
Here are the codes I Used
protected void BtnExport_Click(object sender, EventArgs e)
{
using (MydatabaseEntities dc = new MydatabaseEntities())
{
List<EmployeeMaster> emList = dc.EmployeeMasters.ToList();
StringBuilder sb = new StringBuilder();
if (emList.Count > 0)
{
string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xlsx");
string conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fileName + "; Extended Properties='Excel 12.0;HDR=yes'";
using (OleDbConnection con = new OleDbConnection(conString))
{
string strCreateTab = "Create table EmployeeData(" +
"[Employee ID] varchar(50)," +
"[Company Name] varchar(200)," +
"[Contact Name] varchar(200)," +
"[Contact Title] varchar(200)," +
"[Employee Address] varchar(200)," +
"[Postal Code] varchar(50))";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
OleDbCommand cmd = new OleDbCommand(strCreateTab, con);
cmd.ExecuteNonQuery();
string StrInsert = "Insert into EmployeeData([Employee ID],[Company Name]," + "[Contact Name],[Contact Title],[Employee Address], [Postal Code]" +
")values(?,?,?,?,?,?)";
OleDbCommand cmdIns = new OleDbCommand(StrInsert, con);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
foreach (var i in emList)
{
cmdIns.Parameters[0].Value = i.EmployeeId;
cmdIns.Parameters[1].Value = i.CompanyName;
cmdIns.Parameters[2].Value = i.ContactName;
cmdIns.Parameters[3].Value = i.ContactTitle;
cmdIns.Parameters[4].Value = i.EmployeeAddress;
cmdIns.Parameters[5].Value = i.PostalCode;
cmdIns.ExecuteNonQuery();
}
//create Downloadable File
byte[] content = File.ReadAllBytes(fileName);
HttpContext context = HttpContext.Current;
context.Response.BinaryWrite(content);
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=EmployeeData.xlsx");
context.Response.End();
con.Close();
}
}
}
}
}
So Help me Please
I'm really Happy that I was Able to Fix my Problem with a simple trick I tried. The Error I was Getting that The file is Already Open, was caused by the connection I didn't close before creating a downloadable file!! Here is the change I made in Bold. :-)
protected void BtnExport_Click(object sender, EventArgs e)
{
using (MydatabaseEntities dc = new MydatabaseEntities())
{
List<EmployeeMaster> emList = dc.EmployeeMasters.ToList();
StringBuilder sb = new StringBuilder();
if (emList.Count > 0)
{
string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xlsx");
string conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fileName + "; Extended Properties='Excel 12.0;HDR=yes'";
using (OleDbConnection con = new OleDbConnection(conString))
{
string strCreateTab = "Create table EmployeeData(" +
"[Employee ID] varchar(50)," +
"[Company Name] varchar(200)," +
"[Contact Name] varchar(200)," +
"[Contact Title] varchar(200)," +
"[Employee Address] varchar(200)," +
"[Postal Code] varchar(50))";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
OleDbCommand cmd = new OleDbCommand(strCreateTab, con);
cmd.ExecuteNonQuery();
string StrInsert = "Insert into EmployeeData([Employee ID],[Company Name]," + "[Contact Name],[Contact Title],[Employee Address], [Postal Code]" +
")values(?,?,?,?,?,?)";
OleDbCommand cmdIns = new OleDbCommand(StrInsert, con);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
foreach (var i in emList)
{
cmdIns.Parameters[0].Value = i.EmployeeId;
cmdIns.Parameters[1].Value = i.CompanyName;
cmdIns.Parameters[2].Value = i.ContactName;
cmdIns.Parameters[3].Value = i.ContactTitle;
cmdIns.Parameters[4].Value = i.EmployeeAddress;
cmdIns.Parameters[5].Value = i.PostalCode;
cmdIns.ExecuteNonQuery();
}
//create Downloadable File
**con.Close();**
byte[] content = File.ReadAllBytes(fileName);
HttpContext context = HttpContext.Current;
context.Response.BinaryWrite(content);
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=EmployeeData.xlsx");
context.Response.End();
}
}
}
}
}

try to send email message in C#

I am New in asp.net .plz help
I am trying to send email message in C# with this code
can any body tell me what is wrong with my code ??..it is building with out error but message didn't sent.
if ((!string.IsNullOrEmpty(base.Request["SECURETOKENID"]) && !string.IsNullOrEmpty(base.Request["EMAIL"])) && (base.Request["RESPMSG"] == "Approved"))
{
SqlConnection connection = new SqlConnection(Common.GetConnectionString("DBConnect"));
connection.Open();
SqlCommand command = new SqlCommand(string.Concat(new object[] { "UPDATE VIPPurchases SET PurchaseDate='", DateTime.Now, "', Status=1 WHERE PurchaseCode='", base.Request["SECURETOKENID"], "' AND Status=0" }), connection);
if (command.ExecuteNonQuery() == 1)
{
command = new SqlCommand("SELECT Ct.title, VI.VideoTitle FROM VIPView as VI INNER JOIN VIPPurchases as VP ON VI.catid = VP.VideoCode INNER JOIN categoryppv as Ct ON VP.VideoCode = Ct.catid WHERE VP.PurchaseCode='" + base.Request["SECURETOKENID"] + "' and VI.viewtype='3' AND VI.IsPublished='1'", connection);
string str = (string)command.ExecuteScalar();
command = new SqlCommand("SELECT Value FROM Settings WHERE Name='Email'", connection);
string addresses = (string)command.ExecuteScalar();
command = new SqlCommand("SELECT Fm.FilmmakerEmail, VI.VideoCode, VP.PurchaseCode FROM VIPPurchases as VP INNER JOIN VIPView as VI ON VP.VideoCode = VI.catid INNER JOIN Filmmakers as Fm ON VI.FilmmakerCode = Fm.FilmmakerCode where VP.PurchaseCode='" + base.Request["SECURETOKENID"] + "' and VI.viewtype='3' AND VI.IsPublished='1'", connection);
addresses = addresses + ", " + ((string)command.ExecuteScalar());
command = new SqlCommand("Select Value from Settings WHERE Name='SenderAddress'", connection);
string userName = (string)command.ExecuteScalar();
command = new SqlCommand("Select Value from Settings WHERE Name='SenderPassword'", connection);
string password = (string)command.ExecuteScalar();
command = new SqlCommand("Select Value from Settings WHERE Name='SMTP'", connection);
string str5 = (string)command.ExecuteScalar();
command = new SqlCommand("Select Value from Settings WHERE Name='Port'", connection);
int num = Convert.ToInt32((string)command.ExecuteScalar());
command = new SqlCommand("Select Value from Settings WHERE Name='SSL'", connection);
bool flag = command.ExecuteScalar() == "True";
SmtpClient client = new SmtpClient
{
UseDefaultCredentials = false,
Host = str5,
Port = Convert.ToInt32(num),
Credentials = new NetworkCredential(userName, password),
EnableSsl = flag
};
MailMessage message = new MailMessage
{
Subject = "platformathletics World - Inndividual Registration",
From = new MailAddress(userName)
};
message.To.Add(base.Request["EMAIL"]);
message.IsBodyHtml = true;
message.Body = "<h3>platformathletics World - (" + str + ") Purchase</h3><p>You are allowed to watch training video <b>" + str + "</b> for next 30 days (till " + DateTime.Now.AddDays(30.0).ToString("MMM dd, yyyy hh:mm tt") + "<sup style='color:red'>*</sup>) from now.</p><p>Your ticket number is <b>" + base.Request["SECURETOKENID"] + "</b>.</p><p>Put your ticket number <a href='http://" + HttpContext.Current.Request.Url.Host + "/VIPMovieList.aspx'>here</a> in return box to watch the video.</p><p><a href='http://" + HttpContext.Current.Request.Url.Host + "/login.aspx'>Login</a> or <a href='http:" + HttpContext.Current.Request.Url.Host + "/register.aspx'>register</a> to platformathletics Network to manage your My Pay Per View Purchases section.</p><br /><hr><br /><small>You could be in different time zone other than United States but your ticket will expire in exact 30 days from the time you receive this email.</small>";
client.Send(message);
message = new MailMessage
{
Subject = "platformathletics World - Inndividual Registration",
From = new MailAddress(userName)
};
message.To.Add(addresses);
message.IsBodyHtml = true;
message.Body = "<h3>platformathletics World - (" + str + ") Purchase</h3><p>Your video has been purchased. <i>" + base.Request["EMAIL"] + "</i> is allowed to watch <b>" + str + "</b> for 30 days.</p><p>Confirmation emails are also sent to " + base.Request["EMAIL"] + " and platformathletics Admin.";
client.Send(message);
this.ErrorPanel.Visible = false;
this.SuccessPanel.Visible = true;
}
Am I going on the right path??
Please help me..thanks
You should use try/catch when you actually send the message, you'll get a more descriptiive message of what's going wrong:
try
{
client.Send(message);
}
catch (Exception e)
{
//Handle exception
Console.Write(e.ToString()); //Or use another way to display the message.
}
Try this,
string mailServer;
int port;
string mailId, mailPass;
string subject;
string mailTo;
subject="something";
StringBuilder mailBody = new StringBuilder();
mailTo = "someone#gmail.com";
mailServer = "smtp.gmail.com";
mailId = "something#gmail.com";
myString.Length = 0;
myString.Append("<html><body><div>BODY CONTENT</div></body></html>");
mailPass = "xxxxxx";
port = 587;
MailMessage mail = new MailMessage(mailId, mailTo, subject, myString.ToString());
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(mailServer, port);
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(mailId, mailPass);
smtp.UseDefaultCredentials = false;
smtp.Credentials = nc;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
Change mailTo, mailId, mailPass according to yours.
I'd change :
this.ErrorPanel.Visible = false;
to
this.ErrorPanel.Visible = true;
See if that gives you an error.

ArgumentNull exception in asp.net web application

I have developed an asp.net application in which input will be given through an excel sheet.
This application is working fine in a system with WINDOWS XP and MS office 2008.
If i try to run the same application in a system with WINDOWS 7 and MS office 2010 i am getting a Argument Null Exception.
Code:
foreach (var dr in data)
{
LHSupdate = new LHSUpdate();
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Id"])))
{
AssociateID = Convert.ToString(dr["Associate Id"]);
}
LHSupdate.AssciateID = AssociateID;
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Name"])))
{
AssociateName = Convert.ToString(dr["Associate Name"]);
}
LHSupdate.Name = AssociateName;
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
if (designation != null)
{
foreach (var de in designation)
{
LHSupdate.Designation = Convert.ToString(de["Level"]);
}
}
else
{
LHSupdate.Designation = "";
}
LHSupdate.CourseName = Convert.ToString(dr["Trainings "]);
LHSupdate.CourseStatus = Convert.ToString(dr["Training Status"]);
LHSupdate.Score = Convert.ToString(dr["Credits"]);
LHSupdate.LearningMode = Convert.ToString(dr["Venue"]);
LHSupdate.StartDate = Convert.ToString(dr["Start Date"]);
LHSupdate.EndDate = Convert.ToString(dr["End Date"]);
lstLHS.Add(LHSupdate);
}
I am getting error in the line:
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
Code:
private DataSet Getdata()
{
string connectionString = "";
string getExcelSheetName = string.Empty;
if (fuLHSEntry.HasFile)
{
string fileName = Path.GetFileName(fuLHSEntry.PostedFile.FileName);
string fileExtension = Path.GetExtension(fuLHSEntry.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
fuLHSEntry.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
}
else if (fileExtension == ".xlsx" || fileExtension == ".xlsm")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 12.0;IMEX=2;HDR=Yes;" + Convert.ToChar(34).ToString();
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int count = 0;
foreach (DataRow dr in dtExcelSheetName.Rows)
{
getExcelSheetName = GetSheetName(dr);
if (!string.IsNullOrEmpty(getExcelSheetName))
{
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
if (getExcelSheetName.ToUpper().Contains("LEARNING"))
{
getExcelSheetName = "LEARNING";
}
else
{
getExcelSheetName = "LHS";
}
dAdapter.Fill(dsData, getExcelSheetName);
count++;
if (count == 2)
{
break;
}
}
}
con.Close();
}
return dsData;
}
Please help me in resolving this issue.
Thanks,
Raji
From your code it appears that the table can have two possible names.
Either give it always the same name that you're using later when reading:
dAdapter.Fill(dsData, "LHS");
Or you can take the table by index ignoring its name altogether:
var designation = dsData.Tables[0].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());

Strange! MySQL update not working without error

The below is my code to create account in my project. The code is working perfect till Response.Write(iduser) but the UPDATE command is not working. No error found using exception but MySQL's record is not updated.
try
{
string pet1 = "admin#testlite.php";
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=newtest;" + "UID=root;" + "PASSWORD=**********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcCommand cmd = new OdbcCommand("Select id_user from awm_accounts where email=?", MyConnection);
cmd.Parameters.Add("#val1", OdbcType.VarChar, 255).Value = pet1;
MyConnection.Open();
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
if (dr.Read())
{
int iduser = Convert.ToInt32(dr[0].ToString());
Account acct = new Account();
acct.Email = username.Text + domain.Text;
acct.MailIncomingLogin = username.Text + domain.Text;
acct.MailIncomingHost = "imap." + DropDownList1.SelectedValue;
acct.MailIncomingPassword = password.Text;
acct.MailIncomingPort = 993;
acct.MailOutgoingHost = "smtp." + DropDownList1.SelectedValue;
acct.MailOutgoingPort = 465;
acct.MailIncomingProtocol = IncomingMailProtocol.Imap4;
acct.MailOutgoingAuthentication = true;
acct.DefaultAccount = false;
acct.IDUser = 1;
integr.CreateUserFromAccount(acct);
Response.Write(iduser);
if (!IsPostBack)
{
cmd = new OdbcCommand("UPDATE awm_accounts SET id_user=? WHERE email=? ", MyConnection);
cmd.Parameters.Add("#tb_nickname", OdbcType.Int, 11).Value = iduser;
cmd.Parameters.Add("#tb_fullname", OdbcType.VarChar, 255).Value = username.Text + domain.Text;
cmd.ExecuteNonQuery();
}
}
MyConnection.Close();
}
catch (Exception exp)
{
Response.Write(exp);
}
I'm not sure about the Response.Write part but I am sure that you create a SQLCommand but never actually execute it.
Did you forget to put a cmd.executeNonScalar() in there?

ODBC Select all command

The following code works fine when the limit is 0,1 when I limit them to 0,30 I cannot retrieve records I am sure that my database has enough number of records.
But I doubt the syntax after dr[3].ToString(); How to retrieve all of them.
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=malla_softmail2;" + "UID=xxx;" + "PASSWORD=xxx;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select * from awm_test where user=? limit= 0, 1", MyConnection);
cmd.Parameters.Add("#email", OdbcType.VarChar, 255).Value = "hello";
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
// throw new Exception();
}
if (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
//string d = dr[3].ToString();
//string f = dr[4].ToString();
//string g = dr[5].ToString();
Response.Write(a);
Response.Write(b);
Response.Write(c);
//Response.Write(d);
//Response.Write(f);
//Response.Write(g);
You're only processing the first record returned by your query. Try:
while (dr.Read()) {
string firstField = dr[0].ToString();
string secondField = dr[1].ToString();
string thirdField = dr[2].ToString();
// ...
}
You just need to read the rows in a loop with while(dr.Read()) {...do stuff for each row...} - each dr.Read() moves to the next row.

Resources