retrieve the email address from radio button data source options - c#

I have radio buttons from which I can select the type of data source to retrieve the email addresses of recipients.
if (RadioButton1.Checked)
{
sql.Open();
string s = "select * from address";
SqlCommand t = new SqlCommand(s, sql);
t.ExecuteNonQuery();
sql.Close();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT address FROM address1";
cmd.Connection = sql;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
sql.Open();
da.Fill(dt);
sql.Close();
foreach (DataRow row in dt.Rows)
{
Msg.To.Add(row["address"].ToString());
}
}
else if (RadioButton2.Checked)
{
string connectionString = "";
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload1.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT address FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dt);
con.Close();
foreach (DataRow row in dt.Rows)
{
Msg.To.Add(row["address"].ToString());
}
}
}
else if (RadioButton3.Checked)
{
if (FileUpload2.HasFile)
{
string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload2.SaveAs(fileLocation);
StreamReader sr = new StreamReader(fileLocation);
String line = sr.ReadToEnd();
string[] toAddressArray;
toAddressArray = line.Split(new char[] { ' ' });
foreach (string a in toAddressArray)
{
Msg.To.Add(a);
}
}
}
Now, what I want is when the recipient clicks the link in the html page which I have sent as mail body, I want to retrieve the mail id of the recipient which is from one of the three radio button data source options.
How to get the mail id?
Here is the complete code:
SqlConnection sql = new SqlConnection(ConfigurationManager.ConnectionStrings["mystring"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
getFiles();
if (!IsPostBack)
{
var list = getFiles();
dd1.DataSource = list;
dd1.DataTextField = "Key";
dd1.DataValueField = "Value";
dd1.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
{
SendHTMLMail();
}
void SendHTMLMail()
{
StreamReader reader = new StreamReader(dd1.SelectedItem.Value);
string readFile = reader.ReadToEnd();
Regex regx = new Regex("(?<!src=\")http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
string output = regx.ToString();
string count = 0.ToString();
output = readFile;
string username = Server.UrlEncode(this.txtUsername.Text);
output = regx.Replace(output, new MatchEvaluator((match) =>
{
var url = Uri.EscapeDataString(match.Value.ToString());
return $"http://localhost:61187/two?sender={username}&link={url}&count={count}";
}));
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress(txtUsername.Text);
Msg.Subject = txtSubject.Text;
Msg.Body = output.ToString();
Msg.IsBodyHtml = true;
if (fuAttachment.HasFile)
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
Msg.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
if (RadioButton1.Checked)
{
sql.Open();
string s = "select * from address";
SqlCommand t = new SqlCommand(s, sql);
t.ExecuteNonQuery();
sql.Close();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT address FROM address1";
cmd.Connection = sql;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
sql.Open();
da.Fill(dt);
sql.Close();
foreach (DataRow row in dt.Rows)
{
Msg.To.Add(row["address"].ToString());
}
}
else if (RadioButton2.Checked)
{
string connectionString = "";
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload1.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT address FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dt);
con.Close();
foreach (DataRow row in dt.Rows)
{
Msg.To.Add(row["address"].ToString());
}
}
}
else if (RadioButton3.Checked)
{
if (FileUpload2.HasFile)
{
string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload2.SaveAs(fileLocation);
StreamReader sr = new StreamReader(fileLocation);
String line = sr.ReadToEnd();
string[] toAddressArray;
toAddressArray = line.Split(new char[] { ' ' });
foreach (string a in toAddressArray)
{
Msg.To.Add(a);
}
}
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(txtUsername.Text, txtpwd.Text);
smtp.EnableSsl = true;
smtp.Send(Msg);
Msg = null;
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
}
public List<KeyValuePair<string, string>> getFiles()
{
DirectoryInfo di = new DirectoryInfo(HostingEnvironment.MapPath("/App_Data"));
var fi = di.EnumerateFiles("*.html", SearchOption.TopDirectoryOnly);
var files = new List<KeyValuePair<string, string>>();
foreach (FileInfo file in fi)
{
files.Add(new KeyValuePair<string, string>(file.Name, file.FullName));
}
return files;
}

Related

getoledbschematable requires an open and available connection.The connection's current state is closed

My code below gives me the following error as i typed in the title
What am I doing wrong here?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string huru = openFileDialog1.FileName;
this.textBox1.Text = huru;
string pathConn;
OleDbConnection conn;
DataTable spreadSheetData;
string sheetName = "";
OleDbCommand onlineConnection;
OleDbDataAdapter myDataAdapter;
DataTable dt = new DataTable();
if (huru.Substring(huru.Length - 3) == "lsx")
{
pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + huru
+ ";Extended Properties = \"Excel 12.0 Xml;HDR=YES\"; ";
}
else
{
pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + huru
+ ";Extended Properties=\"Excel 8.0;HDR=yes;\";";
}
conn = new OleDbConnection(pathConn);
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$"))
{
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", conn);
myDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
myDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
}
spreadSheetData starts falling null
my codes refer to Excel to DataGridView
1st answered by JohnG
and this video https://www.youtube.com/watch?v=CfNMPDJVjPI
Thanks for any help!
Your code should be something like this:
I have encapsulated your connection inside a using, so we are sure freeing resources. Also it's necessary to open the connection.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Prepare things
using(OleDbConnection conn = new OleDbConnection(pathConn))
{
conn.Open(); //Added this line
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
//Do staff
}
}
}
You must open your connection before using it :
conn = new OleDbConnection(pathConn);
conn.Open();
You should also use the "Using" statement to properly dispose the connection when not used anymore.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string huru = openFileDialog1.FileName;
this.textBox1.Text = huru;
string pathConn;
//OleDbConnection conn;
DataTable spreadSheetData;
string sheetName = "";
OleDbCommand onlineConnection;
OleDbDataAdapter myDataAdapter;
DataTable dt = new DataTable();
if (huru.Substring(huru.Length - 3) == "lsx")
{
pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + huru
+ ";Extended Properties = \"Excel 12.0 Xml;HDR=YES\"; ";
}
else
{
pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + huru
+ ";Extended Properties=\"Excel 8.0;HDR=yes;\";";
}
using(OleDbConnection conn = ew OleDbConnection(pathConn))
{
//conn = new OleDbConnection(pathConn);
conn.Open();
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$"))
{
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", conn);
myDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
myDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
}
}

how to loop through each row of datatable in order to execute a function one by one for each row

I have a table in the database having a single column and multiple rows. What I am doing is iterating through each row of that table and calling a function to send mail for each row. But the problem is that function is getting executed for all the rows simultaneously whereas I want to execute it one by one for each row. Here is the code-
protected void btnSubmit_Click(object sender, EventArgs e)
{
GetAllRecipient();
Msg = null;
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
public void SendHTMLMail(string emailAddress)
{
MailMessage Msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
Msg.To.Add(emailAddress);
StreamReader reader = new StreamReader(Server.MapPath("~/one.html"));
string readFile = reader.ReadToEnd();
Regex regx = new Regex("(?<!src=\")http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
string output = regx.ToString();
output = readFile;
Msg.Body = output.ToString();
Msg.IsBodyHtml = true;
int i = 0;
string username = Server.UrlEncode(this.txtUsername.Text);
output = regx.Replace(output, new MatchEvaluator((match) =>
{
var url = Uri.EscapeDataString(match.Value.ToString());
url = url.Replace("%3F", "&").Replace("%3D", "=");
return $"http://10.10.10.12/MI/two?sender={username}&link={url}&mailer_id={i}";
}));
Msg.From = new MailAddress(txtUsername.Text);
Msg.Subject = null;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(txtUsername.Text, txtpwd.Text);
smtp.EnableSsl = true;
smtp.Send(Msg);
}
public void GetAllRecipient()
{
if (RadioButton1.Checked)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT address FROM address1";
cmd.Connection = sql;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
sql.Open();
da.Fill(dt);
sql.Close();
// for (int a = 0; a < dt.Rows.Count; a++)
// {
foreach (DataRow row in dt.Rows)
{
SendHTMLMail(row["address"].ToString());
}
// }
}
else if (RadioButton2.Checked)
{
string connectionString = "";
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload1.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT address FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dt);
con.Close();
// for (int a = 0; a < dt.Rows.Count; a++)
// {
foreach (DataRow row in dt.Rows)
{
SendHTMLMail(row["address"].ToString());
}
// }
}
}
There is nothing in your code that demonstrates concurrency or parallelism. As it stands, it should be executing SendHTMLMail sequentially for each row and not concurrently. What makes you feel it is all happening at the same time? Also verify the implementation of SendHTMLMail is not async.

How to import data to GridView Using Linq To Excel

I want to import data to gridview from Excel. And I have done using System.Data.OleDb as
if (ExlSheet.HasFile)
{
string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
ExlSheet.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
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);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
gv.DataSource = dtExcelRecords;
gv.DataBind();
}
How to achieve the same using LinqToExcel
Try this
if (ExlSheet.HasFile)
{
string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
ExlSheet.SaveAs(fileLocation);
ExcelQueryFactory excelFile = new ExcelQueryFactory(fileLocation);
var data = from a in excelFile.Worksheet("Sheet1") select a;
var columnNames = excelFile.GetColumnNames("Sheet1");
DataTable dtExcelRecords = new DataTable();
foreach (var columnName in columnNames)
{
dtExcelRecords.Columns.Add(columnName);
}
foreach (var row in data)
{
DataRow dr = dtExcelRecords.NewRow();
foreach (var columnName in columnNames)
{
dr[columnName] = row[columnName];
}
dtExcelRecords.Rows.Add(dr);
}
gv.DataSource = dtExcelRecords;
gv.DataBind();
}

datatable won't update

I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("~/default.aspx");
if (Request .QueryString ["action"]=="edit")
{
Panel1.Visible = true;
}
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text=myReader ["Title"].ToString ();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
protected void btn_addpost_Click(object sender, EventArgs e)
{
string title= title_txt .Text ;
string body=bodytxt .Text ;
if (Request.QueryString["edit"] != null)
{
string message;
string filename = thumb_uploader.FileName;
string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
string[] ext = { ".jpg", ".png", ".jpeg" };
if (Array.IndexOf(ext, exup) < 0)
{
message = "not correct.";
}
if (thumb_uploader.FileBytes.Length / 1024 > 400)
{
message = "not currect.";
}
while (System.IO.File.Exists(path + "\\" + filename + exup))
{
filename += "1";
}
savepath = path + "\\" + filename;
if (thumb_uploader.HasFile)
{
thumb_uploader.SaveAs(savepath);
thumb = thumb_uploader.FileName;
SqlCommand command;
SqlDataAdapter da;
SqlConnection con3 = new SqlConnection();
con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
command = new SqlCommand();
command.Connection = con3;
da = new SqlDataAdapter();
da.SelectCommand = command;
command.CommandText = "UPDATE tbl_post SET Title=#title ,Body=#body ,Thumb=#thu Where Postid=" + Request.QueryString["edit"].ToString();
con3.Open();
command.Parameters.AddWithValue("#title", title );
command.Parameters.AddWithValue("#body", body );
command.Parameters.AddWithValue("#thu", thumb_uploader .FileName);
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
else
{
using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
{
string sql = "update tbl_post SET Title=#title ,Body=#body Where Postid=#postid" ;
using (SqlCommand command = new SqlCommand(sql, con3))
{
con3.Open();
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#body", body);
command.Parameters.AddWithValue("#postid", Request.QueryString["edit"].ToString());
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
}
}
}
I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
if (!Page.IsPostBack)
{
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text = myReader["Title"].ToString();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
}

External table is not in expected format

I have to upload a Excel Sheet in document library and have to show all the details of list in gridview. But I am getting the error: "external table is not in expected format":
My code is:
void uploadDocument()
{
try
{
string publicFSdocLibrary = "PublicFSdoc";
if (uploadDoc.HasFile)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSite = new SPSite("http://chdsez301298d:1000/sites/Test/"))
//using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb myWeb = oSite.OpenWeb())
{
SPListItem lstItem = SPContext.Current.ListItem;
myWeb.AllowUnsafeUpdates = true;
//SPList docList = myWeb.Lists[docLibrary];
SPFolder finalDocument = myWeb.Folders[publicFSdocLibrary];
// Prepare to upload
Boolean replaceExistingFiles = true;
string fileName = Path.GetFileName(uploadDoc.FileName);
filePath = Path.GetFullPath(uploadDoc.PostedFile.FileName);
// string newFilePath = getFilePath(filePath);
FileStream fileStream = System.IO.File.OpenRead(filePath);
// Upload document
SPFile spfile = finalDocument.Files.Add(getFileName(), fileStream, replaceExistingFiles);
SPListItem item = spfile.Item;
item["RequestNo"] = generateRequestNo();
item["AssessmentType"] = "Financial Solvency";
// Commit all changes
item.Update();
//Update document url to Assessment request list
myWeb.AllowUnsafeUpdates = false;
}
}
});
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
string getFileName()
{
string newFileName = generateRequestNo() + ".xlsx";
return newFileName;
}
void btnUpload_Click(object sender, EventArgs e)
{
uploadDocument();
getExcelData();
//savePublicFS();
//addAssesmentWfRequest();
//CloseForm();
//Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "window.close();", true);
}
void getExcelData()
{
try
{
if (uploadDoc.HasFile)
{
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
//string sheetName = "Sourcing Questionnaire";
string query = null;
string connString = "";
string fileName = Path.GetFileName(uploadDoc.FileName);
string strFileType = System.IO.Path.GetExtension(uploadDoc.FileName).ToString().ToLower();
string strNewPath = filePath;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
// query = "SELECT * FROM [" + sheetName + "$]";
query = "SELECT * FROM [abc$]";
//Create the connection object
conn = new OleDbConnection(connString);
//Open connection
if (conn.State == ConnectionState.Closed) conn.Open();
//Create the command object
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds.Tables[0];
gvdetails.DataBind();
da.Dispose();
conn.Close();
conn.Dispose();
//return ds;
}
}
catch (Exception)
{
throw;
}
}
private String generateRequestNo()
{
try
{
String requestNo = String.Empty;
if (txtSupplierName.Text.Length <= 4)
{
requestNo = txtSupplierName.Text
+ "-" + requestNumber()
+ DateTime.Today.ToString("ddMMyyyy");
}
else
{
requestNo = txtSupplierName.Text.Substring(0, 4)
+ "-" + requestNumber()
+ DateTime.Today.ToString("ddMMyyyy");
}
return requestNo;
}
catch (Exception)
{
throw;
}
}
private String requestNumber()
{
try
{
String number = String.Empty;
number = "FS-";
return number;
}
catch (Exception)
{
throw;
}
}
I am getting error in getExcelData() method at line cmd = new OleDbCommand(query, conn);
Please help me as I struck here since last week.

Categories

Resources