through exception in mvc on send email - asp.net-mvc

I want to send email from an excel file.
When It get wrong email address it stop sending.
I want it send all email and at last show me wrong email that isn't able to send.
This my code for read Excel file:
if (!string.IsNullOrWhiteSpace(excel))
{
var src = excel;
DataSet ds = new DataSet();
string fileExtension = System.IO.Path.GetExtension(Server.MapPath("~/") + src);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("~/") + src;
string excelConnectionString = string.Empty;
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string fileLocation = Server.MapPath("~/") + src;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
// DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
}
And this is code for send email:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string excelname = "";
if (lang == "1")
{
excelname = "<div style='text-align:right;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
else
{
excelname = "<div style='text-align:left;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
exceltotal = excelname + text + newslink + attach;
//sender
message = string.Format(body, img, exceltotal, title, prehead, senderemail);
MailMessage email = new MailMessage();
email.To.Add(ds.Tables[0].Rows[i][2].ToString());
email.From = new MailAddress(senderemail);
email.Subject = maintitle;
email.Body = message + makedelivey(ds.Tables[0].Rows[i][2].ToString(), maintitle);
email.BodyEncoding = System.Text.Encoding.UTF8;
email.IsBodyHtml = true;
SmtpClient ssmtp = new SmtpClient();
ssmtp.Host = server;
ssmtp.Port = port;
ssmtp.UseDefaultCredentials = false;
ssmtp.Credentials = new System.Net.NetworkCredential(senderemail, senderpassword);
ssmtp.EnableSsl = false;
ssmtp.Send(email);
exceltotal = "";
message = "";
}
It read a text file and add some value from excel or database base on user selection.

I couldn't find line of code which sends email. But wherever you are sending the email inside the loop, make sure you enclose that code in try catch block. This ensures even if a mail send operation is failed, the error is handled and goes on with other mails. You can include your consolidate and formatting of failures issues in catch block.
var consolidateErrors = string.Empty;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Try
{
//Mail sending logic here
}
Catch(Exception ex)
{
consolidateErrors += YourErrorDetails;
}
}

Related

how to Update the value if already exists in database, if not then insert new record?

I've created a validation to check the value from excel file if row value it's already in the database. I want to create action if the value already exists then my record update, if not exist on databese then inserted as new record.
Here The full code.
[ValidateAntiForgeryToken]
public ActionResult ImportDataAgens(HttpPostedFileBase excelfileRekn)
{
if (excelfileRekn == null || excelfileRekn.ContentLength == 0)
{
ViewBag.Error = "Please Select File...";
return View("ImportDataAgens");
}
else
{
if (excelfileRekn.FileName.EndsWith("xls") || excelfileRekn.FileName.EndsWith("xlsx"))
{
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string filename = Path.GetFileName(excelfileRekn.FileName);
string DocFileNames = newFileName + "-" + filename;
string path = System.IO.Path.Combine(Server.MapPath("~/UploadFile/DataAgen/"), DocFileNames);
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
excelfileRekn.SaveAs(path);
//read data from file excel
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(path);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
List<DMInformasiDataAgen> listTempRekn = new List<DMInformasiDataAgen>();
for (int row = 3; row <= range.Rows.Count; row++)
{
DMInformasiDataAgen rk = new DMInformasiDataAgen();
/* var NewUserIDAgent = ((Excel.Range)range.Cells[row, 1]).Text;
var NewNamaAgen = ((Excel.Range)range.Cells[row, 2]).Text;
//rk.NamaAgen = NewNamaAgen;*/
rk.SandiBank = ((Excel.Range)range.Cells[row, 1]).Text;
rk.UserIDAgen = ((Excel.Range)range.Cells[row, 2]).Text;
rk.NamaAgen = ((Excel.Range)range.Cells[row, 3]).Text;
var NewNomorIdentifikasiAgen = ((Excel.Range)range.Cells[row, 4]).Text;
rk.NomorIdentifikasiAgen = NewNomorIdentifikasiAgen;
if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
{
int RowNo = row;
var hitung = listTempRekn.Count + 4;
ModelState.AddModelError("", "Nomor Identifikasi Sudah ada sebelumnya ! Pada baris ke " + hitung + " Pada EXCEL File !");
return View("ImportDataAgens");
}
rk.NomordanTanggalPerjanjian = ((Excel.Range)range.Cells[row, 5]).Text;
rk.TglPelaksanaan = ((Excel.Range)range.Cells[row, 6]).Value;
rk.JenisAgen = ((Excel.Range)range.Cells[row, 7]).Text;
rk.KlasifikasiAgen = ((Excel.Range)range.Cells[row, 8]).Text;
rk.JenisUsahaAgen = ((Excel.Range)range.Cells[row, 9]).Text;
rk.KodePos = ((Excel.Range)range.Cells[row, 10]).Text;
rk.LatitudeLongitudinal = ((Excel.Range)range.Cells[row, 11]).Text;
rk.KabupatenKota = ((Excel.Range)range.Cells[row, 12]).Text;
rk.ElectronicDevice = ((Excel.Range)range.Cells[row, 13]).Text;
rk.JaringanKantorBank = ((Excel.Range)range.Cells[row, 14]).Text;
rk.KategoriJaringanKantorBank = ((Excel.Range)range.Cells[row, 15]).Text;
rk.StatusPerkembanganAgen = ((Excel.Range)range.Cells[row, 16]).Text;
rk.Keterangan = ((Excel.Range)range.Cells[row, 17]).Text;
if (((Excel.Range)range.Cells[row, 18]).Value == null)
{
int RowNo = row;
var hitung = listTempRekn.Count + 4;
ModelState.AddModelError("", "Tolong periksa PERIODE Pada baris ke " + hitung + " Pada EXCEL File !");
return View("ImportDataAgens");
}
rk.Periode = ((Excel.Range)range.Cells[row, 18]).Value;
string valueA = System.Web.HttpContext.Current.User.Identity.Name;
rk.CreateBy = valueA;
rk.CreateDate = DateTime.Today;
if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
{
int RowNo = row;
var hitung = listTempRekn.Count + 4;
ModelState.AddModelError("", "The Number Of Agent Already Exist on " + hitung + " the Template EXCEL File !");
return View("ImportDataAgens");
}
if (ModelState.IsValid)
{
listTempRekn.Add(rk);
db.DMInformasiDataAgens.Add(rk);
db.SaveChanges();
var hitung = listTempRekn.Count;
//range.Rows.Count - 2;
TempData["AlertMessage"] = "Import Data Selesai " + hitung + " Records Sudah Tersimpan...";
}
}
return RedirectToAction("Index", "DataAgens");
}
else
{
ViewBag.Error = "File Type is incorrect <br>";
return View("ImportDataAgens");
}
}
}
Here the Code whe I check the already exist Value :
**if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
{
int RowNo = row;
var hitung = listTempRekn.Count + 4;
ModelState.AddModelError("", " The Number Of Agent Already Exist on " + hitung + " the Template EXCEL File !");
return View("ImportDataAgens");
}**
How to create action if the value already exists (Number Of Agent) then my record update, if not then insert new record ?
var chkItem = x.firstOrDefault(your condition);
if(chkItem != null)
{
//update your record.
}
else{
//insert into database
}

Bad Request model derivative autodesk api when translating dwg to obj format

I want to use autodesk model derivative api to show DWG file in forge viewer. In
result = _client.Execute(objReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode==System.Net.HttpStatusCode.Created)
{
}
I get badrequest.
public virtual ActionResult Index()
{
SetupViewer();
if (_bucketFound)
{
//upload file
RestRequest uploadReq = new RestRequest();
uploadReq.Resource = "oss/v2/buckets/"+_bucketName+"/objects/"+_filepath;
uploadReq.Method = Method.PUT;
uploadReq.AddHeader("Content-Type", _fileContentType);
uploadReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
var result= _client.Execute(uploadReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
String responseString = result.Content;
int len = responseString.Length;
int objectKeyIndex = responseString.IndexOf("\"objectKey\" : \"");
int index = responseString.IndexOf("urn:");
responseString = responseString.Substring(index, objectKeyIndex - index-5).Replace("urn:", "").Trim();
_fileUrn = "urn:"+responseString;
//convert urn to base64
string base64Urn = Base64Convertor.Base64Encode(_fileUrn);
// Remove ending '=' signs
// Use _ instead of /
// Use - insteaqd of +
base64Urn = base64Urn.Replace("=", "");
//translate to SVF format
//RestRequest svfReq = new RestRequest();
//svfReq.Resource = "modelderivative/v2/designdata/job";
//svfReq.Method = Method.POST;
//svfReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
//svfReq.AddParameter("Content-Type", "application/json;charset=utf-8", ParameterType.HttpHeader);
//string body = "{\"input\":{\"urn\":\"" + base64Urn + "\",\"compressedUrn\":true,\"rootFilename\":\""+_filepath+ "\"},\"output\":{\"formats\":[{\"type\":\"svf\",\"views\":[\"2d\"]}]}}";
//svfReq.AddParameter("application/json", body, ParameterType.RequestBody);
// translate to OBJ format
RestRequest objReq = new RestRequest();
objReq.Resource = "modelderivative/v2/designdata/job";
objReq.Method = Method.POST;
objReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
objReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
string body = "{\"input\":{\"urn\":\"" + base64Urn + "\"},\"output\":{\"formats\":[{\"type\":\"obj\"}]}}";
result = _client.Execute(objReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode==System.Net.HttpStatusCode.Created)
{
//check the transition complete
RestRequest checkTransitionCompleteGetReq = new RestRequest();
checkTransitionCompleteGetReq.Resource = "modelderivative/v2/designdata/"+base64Urn+"/manifest";
checkTransitionCompleteGetReq.Method = Method.GET;
checkTransitionCompleteGetReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
var result2 = _client.Execute(checkTransitionCompleteGetReq);
if (result2.StatusCode == System.Net.HttpStatusCode.OK)
{
ViewBag.BucketFound = result.Content;
}
}
}
}
return View();
}
void SetupViewer()
{
// Authentication
bool authenticationDone = false;
RestRequest authReq = new RestRequest();
authReq.Resource = "authentication/v1/authenticate";
authReq.Method = Method.POST;
authReq.AddHeader("Content-Type", "application/x-www-form-urlencoded");
authReq.AddParameter("client_id", ConfigurationManager.AppSettings["ClientId"]);
authReq.AddParameter("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
authReq.AddParameter("grant_type", "client_credentials");
authReq.AddParameter("scope", "bucket:create bucket:read data:write data:read");
IRestResponse result = _client.Execute(authReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
String responseString = result.Content;
int len = responseString.Length;
int index = responseString.IndexOf("\"access_token\":\"") + "\"access_token\":\"".Length;
responseString = responseString.Substring(index, len - index - 1);
int index2 = responseString.IndexOf("\"");
_accessToken = responseString.Substring(0, index2);
//Set the token.
RestRequest setTokenReq = new RestRequest();
setTokenReq.Resource = "utility/v1/settoken";
setTokenReq.Method = Method.POST;
setTokenReq.AddHeader("Content-Type", "application/x-www-form-urlencoded");
setTokenReq.AddParameter("access-token", _accessToken);
IRestResponse resp = _client.Execute(setTokenReq);
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
authenticationDone = true;
}
}
if (!authenticationDone)
{
ViewData["Message"] = "View and Data client authentication failed !";
_accessToken = String.Empty;
return;
}
RestRequest bucketReq = new RestRequest();
bucketReq.Resource = "oss/v2/buckets";
bucketReq.Method = Method.POST;
bucketReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
bucketReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
//bucketname is the name of the bucket.
string body = "{\"bucketKey\":\"" + _bucketName + "\",\"policyKey\":\"transient\"}";
bucketReq.AddParameter("application/json", body, ParameterType.RequestBody);
result = _client.Execute(bucketReq);
if (result.StatusCode == System.Net.HttpStatusCode.Conflict ||
result.StatusCode == System.Net.HttpStatusCode.OK)
{
// _bucketFound = true;
//Check bucket
RestRequest bucketGetReq = new RestRequest();
bucketGetReq.Resource = "oss/v2/buckets";
bucketGetReq.Method = Method.GET;
bucketGetReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
bucketGetReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
result = _client.Execute(bucketGetReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
_bucketFound = true;
ViewBag.BucketFound = "Found";
}
else
ViewBag.BucketFound = "NotFound";
}
else
{
ViewData["Message"] = "View and Data bucket could not be accessed !";
_bucketFound = false;
return;
}
}
Could you try this again, we had some down time from our side during that time, but everything should be back up and running for you. In case does not work I will take a look at your request.

Reading Windows event log using JNA provides me only part of the description available in Event Veiwer

This is my code Provide me details where am going wrong so that am
getting only the part of the description available
========================================================================
http://code.dblock.org/jna-reading-windows-event-log-entries-in-java
#SuppressWarnings("unused")
public void testReadEventLogEntries() throws CharacterCodingException {
final Charset charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
final CharsetEncoder encoder = charset.newEncoder();
final CharsetDecoder decoder = charset.newDecoder();
int i = 0;// loop contro variable
String type = null; // Type of the event
String user = null;
String str[] = { "System", "Application" };
while (i < 2) {
System.out.println("\n\n" + str[i]);
HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, str[i]);
IntByReference pnBytesRead = new IntByReference();
IntByReference pnMinNumberOfBytesNeeded = new IntByReference();
Memory buffer = new Memory(1024 * 64);
IntByReference pOldestRecord = new IntByReference();
int dwRecord = pOldestRecord.getValue();
int rc = 0;
while (true) { // Travesing the read log records
if (!Advapi32.INSTANCE.ReadEventLog(h,
WinNT.EVENTLOG_SEQUENTIAL_READ
| WinNT.EVENTLOG_FORWARDS_READ, 0, buffer,
(int) buffer.size(), pnBytesRead,
pnMinNumberOfBytesNeeded)) {
rc = Kernel32.INSTANCE.GetLastError();
if (rc == W32Errors.ERROR_INSUFFICIENT_BUFFER) {
buffer = new Memory(pnMinNumberOfBytesNeeded.getValue());
continue;
}
break;
}
int dwRead = pnBytesRead.getValue();
Pointer pevlr = buffer;
while (dwRead > 0) {
EVENTLOGRECORD record = new EVENTLOGRECORD(pevlr);
EventLogRecord event = new EventLogRecord(pevlr);
org.hyperic.sigar.win32.EventLogRecord sigar;
EventLog log = new EventLog();
if (record.EventType.intValue() == 1)
type = "Error";
else if (record.EventType.intValue() == 10)
type = "Failure Audit";
else if (record.EventType.intValue() == 8)
type = "Sucess Audit";
else if (record.EventType.intValue() == 4)
type = "Information";
else
type = "Warning";
ByteBuffer names = pevlr
.getByteBuffer(
record.size(),
(record.UserSidLength.intValue() != 0 ? record.UserSidOffset
.intValue() : record.StringOffset
.intValue())
- record.size());
names.position(0);
CharBuffer namesBuf = names.asCharBuffer();
String[] splits = namesBuf.toString().split("\0");
if (record.UserSidLength.intValue() != 0) {
ByteBuffer usersid = pevlr.getByteBuffer(
record.UserSidOffset.intValue(),
record.UserSidLength.intValue());
usersid.position(0);
CharBuffer sidBuf = usersid.asCharBuffer();
String[] sp = sidBuf.toString().split("\0");
// System.out.println(sp[0] + sp[1] + sp[2]);
/*
* dst.get user= new String(dst);
*/
} else {
user = "N/A";
}
System.out.println(type + "\t" + toDate(record) + "\t"
+ event.getSource() + "\t" + record.EventCategory
+ "\t" + record.EventID.shortValue() + "\t" + user
+ "\t" + splits[1]);
ByteBuffer strings = pevlr.getByteBuffer(
record.StringOffset.longValue(),
record.DataOffset.intValue()
- record.StringOffset.intValue());
CharBuffer stringsBuf = strings.asCharBuffer();
System.out.println("Desc: " + stringsBuf.toString());
dwRecord++;
dwRead -= record.Length.intValue();
pevlr = pevlr.share(record.Length.intValue());
}
}
i++;
}
}
// Method to convert the timestamp to formated date
public Date toDate(EVENTLOGRECORD record) {
Timestamp stamp = new Timestamp(record.TimeWritten.longValue() * 1000);
Date date = new Date(stamp.getTime());
return date;
}
}
Finally I figured out the solution....The description returned by the
above code is just the insertion strings needed to build the message.
Instead of using jna I used WMI which is simple to use and more handy
/**
* #param args
*/
public static void main(String[] args) throws COMException {
String computerName = ".";
String userName = "";
String password = "";
String namespace = "root/cimv2";
String Message = "";
String queryProcessor = "Select * from Win32_NTLogEvent where Logfile='System'or Logfile='Application'";
DispatchPtr dispatcher = null;
try {
ISWbemLocator locator = new ISWbemLocator(
"WbemScripting.SWbemLocator");
ISWbemServices wbemServices = locator.ConnectServer(computerName,
namespace, userName, password, "", "", 0, dispatcher);
ISWbemObjectSet wbemObjectSet = wbemServices.ExecQuery(
queryProcessor, "WQL", 0, null);
DispatchPtr[] results = new DispatchPtr[wbemObjectSet.getCount()];
IUnknown unknown = wbemObjectSet.get_NewEnum();
IEnumVariant enumVariant = (IEnumVariant) unknown
.queryInterface(IEnumVariant.class);
enumVariant.Next(wbemObjectSet.getCount(), results);
for (int i = 0; i < results.length; i++) {
ISWbemObject wbemObject = (ISWbemObject) results[i]
.queryInterface(ISWbemObject.class);
if (wbemObject.get("Message") != null) {
Message = (String) wbemObject.get("Message");
} else {
Message = "The description for Event ID ("
+ wbemObject.get("EventCode")
+ " ) in Source ( "
+ wbemObject.get("SourceName")
+ ") cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.";
}
System.out.println(wbemObject.get("Logfile") + "\t"
+ wbemObject.get("Type") + "\t"
+ toDate(wbemObject.get("TimeGenerated").toString())
+ "\t"
+ toTime(wbemObject.get("TimeGenerated").toString())
+ "\t" + wbemObject.get("EventCode") + "\t"
+ wbemObject.get("ComputerName") + "\t" + Message);
// System.out.println(wbemObject.GetObjectText_(0));
}
} catch (COMException e) {
e.printStackTrace();
}
}
public static String toDate(String time) throws COMException {
String date = time.substring(6, 8) + "-" + time.substring(4, 6) + "-"
+ time.substring(0, 4);
return date;
}
public static String toTime(String time) throws COMException {
String Generatedtime = time.substring(8, 10) + ":"
+ time.substring(10, 12) + ":" + time.substring(12, 14) + ":"
+ time.substring(16, 21) + "-" + "GMT" + time.substring(21, 25);
return Generatedtime;
}

mvc 4 asp.net - export data to .csv from a local .xls file

I would be grateful if you could please help me with the code below: I am fairly new to C# and Razor. I am trying to get data from an excel sheet and displaying it on the screen using a jQuery Jtable. I can get it to be displayed but its not exporting the data to CSV file. I am using MVC 4 Razor ASP.NET
here's my controller action code:
private void ExportToCsv(object sender, System.EventArgs e)
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
SQLDBBillingProvider sql = new SQLDBBillingProvider();
// var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);
// data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
//daa.Add(p.Field<string>("Track Statistics"));
//daa.Add(p.Field<string>("Track Name"));
TopPlayed top = new TopPlayed()
{
TrackID = p.Field<double>("ID").ToString(),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};
daa.Add(top);
}
var toptracks = new List<TopPlayed>();
// toptracks.Add(GetHeader());
int k = -5;
for (int i = 0; i < 5; i++)
{
//static data
var trackInfo = new TopPlayed();
trackInfo.TrackID = "abc" + i;
trackInfo.TrackName = "xyz" + i;
trackInfo.ArtistName = "" + i;
trackInfo.Times = "" + i;
toptracks.Add(trackInfo);
}
System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
gridvw.DataBind();
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel;name='Excel'";
Response.AddHeader("content-disposition", "attachment;filename=TopTracks.csv");
StringWriter swr = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(swr);
gridvw.RenderControl(tw);
Response.Write(swr.ToString());
Response.End();
}
Thanks in advance.
From an existing, working, project:
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
var sw = new StreamWriter(new MemoryStream());
// Write the strings here..
sw.WriteLine(...) etc
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
Just tweak the variables to suit your filename and data writing method.
e.g.
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
var sw = new StreamWriter(new MemoryStream());
// Write the data here..
HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw);
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
In the context of your original question it will look something like:
public ActionResult ExportToCsv()
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
SQLDBBillingProvider sql = new SQLDBBillingProvider();
// var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);
// data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
//daa.Add(p.Field<string>("Track Statistics"));
//daa.Add(p.Field<string>("Track Name"));
TopPlayed top = new TopPlayed()
{
TrackID = p.Field<double>("ID").ToString(),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};
daa.Add(top);
}
var toptracks = new List<TopPlayed>();
// toptracks.Add(GetHeader());
int k = -5;
for (int i = 0; i < 5; i++)
{
//static data
var trackInfo = new TopPlayed();
trackInfo.TrackID = "abc" + i;
trackInfo.TrackName = "xyz" + i;
trackInfo.ArtistName = "" + i;
trackInfo.Times = "" + i;
toptracks.Add(trackInfo);
}
System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
gridvw.DataBind();
HttpContext.Response.ClearContent();
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=filename=TopTracks.csv");
HttpContext.Response.AddHeader("Expires", "0");
var sw = new StreamWriter(new MemoryStream());
// Write the data here..
HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw);
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
}

Silverlight 3 File Dialog Box

Ok - I have a WCF Service which reads an excel file from a certain location and strips the data into an object. What I need is the ability to allow users of my program to Upload an excel sheet to the file location that my Service uses.
Alternitivley I could pass the Uploaded excel sheet to the service directly.
Can anyone help with this. My service code is:
public List<ImportFile> ImportExcelData(string FileName)
{
//string dataSource = Location + FileName;
string dataSource = Location;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
var data = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
var sheetName = data.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetName + "] WHERE Status = '4'", con);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Employees");
DataTable dt = ds.Tables[0];
var _impFiles = new List<ImportFile>();
foreach (DataRow row in dt.Rows)
{
var _import = new ImportFile();
_import.PurchaseOrder = row[4].ToString();
try
{
var ord = row[8].ToString();
DateTime dati = Convert.ToDateTime(ord);
_import.ShipDate = dati;
}
catch (Exception)
{
_import.ShipDate = null;
}
ImportFile additionalData = new ImportFile();
additionalData = GetAdditionalData(_import.PurchaseOrder);
_import.NavOrderNo = additionalData.NavOrderNo;
_import.IsInstall = additionalData.IsInstall;
_import.SalesOrderId = additionalData.SalesOrderId;
_import.ActivityID = additionalData.ActivityID;
_import.Subject = additionalData.Subject ;
_import.IsMatched = (_import.ShipDate != null & _import.NavOrderNo != "" & _import.NavOrderNo != null & _import.ShipDate > DateTime.Parse("01/01/1999") ? true : false);
_import.UpdatedShipToField = false;
_import.UpdatedShipToFieldFailed = false;
_import.CreateNote = false;
_import.CreateNoteFailed = false;
_import.CompleteTask = false;
_import.CompleteTaskFailed = false;
_import.FullyCompleted = 0;
_import.NotCompleted = false;
_impFiles.Add(_import);
}
oleda.Dispose();
con.Close();
//File.Delete(dataSource);
return _impFiles;
}
You will want to modify your service to accept a Stream instead of a filename, then you can save if off to a file (or parse it directly from the Stream, although I don't know how to do that).
Then in your Silverlight app you could do something like this:
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var fileStream = dialog.File.OpenRead();
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// don't forget to close the stream
fileStream.Close();
};
proxy.ImportExcelDataAsync(fileStream);
}
}
You could also have your WCF service accept a byte[] and do something like this.
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var length = dialog.File.Length;
var fileContents = new byte[length];
using (var fileStream = dialog.File.OpenRead())
{
if (length > Int32.MaxValue)
{
throw new Exception("Are you sure you want to load > 2GB into memory. There may be better options");
}
fileStream.Read(fileContents, 0, (int)length);
}
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// no need to close any streams this way
};
proxy.ImportExcelDataAsync(fileContents);
}
}
Update
Your service could look like this:
public List<ImportFile> ImportExcelData(Stream uploadedFile)
{
var tempFile = HttpContext.Current.Server.MapPath("~/uploadedFiles/" + Path.GetRandomFileName());
try
{
using (var tempStream = File.OpenWrite(tempFile))
{
uploadedFile.CopyTo(tempStream);
}
//string dataSource = Location + FileName;
string dataSource = tempFile;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() +
";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
}
finally
{
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
Thanks Bendewey that was great. Had to amend it slightly -
My Service:
var tempFile = #"c:\temp\" + Path.GetRandomFileName();
try
{
int length = 256;
int bytesRead = 0;
Byte[] buffer = new Byte[length];
// write the required bytes
using (FileStream fs = new FileStream(tempFile, FileMode.Create))
{
do
{
bytesRead = uploadedFile.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
}
while (bytesRead == length);
}
uploadedFile.Dispose();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
Thanks Again for your help

Resources