Silverlight 3 File Dialog Box - silverlight-3.0

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

Related

SharePoint Helper Class: WebRequest to HttpClient

I have a scenario where I need to use an OnPrem-SharePoint for File Upload/Download. It's SharePoint 2016 and I found a helper class from the old days that uses WebRequests to communicate. I must use the same class in my .net 7 Minimal API project. It works but I don't like the tech debt I have to carry by using WebRequests. There are quite a few methods there but I need help converting these main ones and I can manage the rest as they are somewhat copy-paste:
public partial class SharePointService : ISharePointService
{
private const string AuthUrl = "https://accounts.accesscontrol.windows.net/{0}/tokens/OAuth/2";
private readonly SPAppInit spAppInit;
public SharePointService(SPAppInit spAppInit) => this.spAppInit = spAppInit;
public SPAuthToken? GetAuthToken()
{
var postParameters = new[]
{
new KeyValuePair<string, string>("grant_type", spAppInit.GrantType),
new KeyValuePair<string, string>("client_id", $"{spAppInit.AppClientId}#{spAppInit.TenantId}"),
new KeyValuePair<string, string>("client_secret", spAppInit.AppSecret),
new KeyValuePair<string, string>("resource", $"00000000-0000-0aaa-ce00-000000000000/{spAppInit.TenantName}#{spAppInit.TenantId}"),
};
var postData = postParameters.Aggregate("", (current, t) => current + HttpUtility.UrlEncode(t.Key) + "=" + HttpUtility.UrlEncode(t.Value) + "&");
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(string.Format(AuthUrl, spAppInit.TenantId));
myHttpWebRequest.Method = "POST";
var data = Encoding.ASCII.GetBytes(postData);
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.ContentLength = data.Length;
var requestStream = myHttpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
var responseStream = myHttpWebResponse.GetResponseStream();
var myStreamReader = new StreamReader(responseStream, Encoding.Default);
var result = myStreamReader.ReadToEnd();
var authToken = JsonSerializer.Deserialize<SPAuthToken>(result, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
myStreamReader.Close();
responseStream.Close();
myHttpWebResponse.Close();
return authToken;
}
public string GetRequestDigest(string authToken)
{
const string endpoint = "/_api/contextInfo";
var request = (HttpWebRequest)WebRequest.Create(spAppInit.SPSiteUrl + endpoint);
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.Headers["Authorization"] = $"Bearer {authToken}";
//request.Accept = "application/json;odata=verbose";
request.ContentLength = 0;
using var response = (HttpWebResponse)request.GetResponse();
using var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
// parse the ContextInfo response
var resultXml = XDocument.Parse(result);
// get the form digest value
var e = from r in resultXml.Descendants()
where r.Name == XName.Get("FormDigestValue", "http://schemas.microsoft.com/ado/2007/08/dataservices")
select r;
return e.First().Value;
}
public string CreateFolder(string authToken, string requestDigest, string folderName)
{
var request = (HttpWebRequest)WebRequest.Create($"{spAppInit.SPSiteUrl}/_api/web/getfolderbyserverrelativeurl('{spAppInit.SPDocLibServerRelativeUrl}/')/folders");
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.Headers["Authorization"] = $"Bearer {authToken}";
request.Headers["X-RequestDigest"] = requestDigest;
request.Accept = "application/json;";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
var requestParams = CreateRequest(folderName);
var json = JsonSerializer.Serialize(requestParams);
streamWriter.Write(json);
}
using var response = (HttpWebResponse)request.GetResponse();
using var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
var folderCreationResponse = JsonSerializer.Deserialize<SPFolderCreationResponse>(result, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return folderCreationResponse?.ServerRelativeUrl ?? string.Empty;
}
public void UploadLargeFile(string authToken, string formDigest, string sourcePath, string targetFolderUrl, int chunkSizeBytes = 2048)
{
using var client = new WebClient();
client.BaseAddress = spAppInit.SPSiteUrl;
client.Headers.Add("X-RequestDigest", formDigest);
client.Headers.Add("content-type", "application/json;odata=verbose");
client.Headers.Add("Authorization", $"Bearer {authToken}");
var fileName = Path.GetFileName(sourcePath);
var createFileRequestUrl = $"{spAppInit.SPSiteUrl}/_api/web/getFolderByServerRelativeUrl('{targetFolderUrl}')/files/add(url='{fileName}',overwrite=true)";
client.UploadString(createFileRequestUrl, "POST");
var targetUrl = Path.Combine(targetFolderUrl, fileName);
var firstChunk = true;
var uploadId = Guid.NewGuid();
var offset = 0L;
using var inputStream = File.OpenRead(sourcePath);
var buffer = new byte[chunkSizeBytes];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
if (firstChunk)
{
var endpointUrl = $"{spAppInit.SPSiteUrl}/_api/web/getFileByServerRelativeUrl('{targetUrl}')/startUpload(uploadId=guid'{uploadId}')";
client.UploadData(endpointUrl, buffer);
firstChunk = false;
}
else if (inputStream.Position == inputStream.Length)
{
var endpointUrl = $"{spAppInit.SPSiteUrl}/_api/web/getFileByServerRelativeUrl('{targetUrl}')/finishUpload(uploadId=guid'{uploadId}',fileOffset={offset})";
var finalBuffer = new byte[bytesRead];
Array.Copy(buffer, finalBuffer, finalBuffer.Length);
client.UploadData(endpointUrl, finalBuffer);
}
else
{
var endpointUrl = $"{spAppInit.SPSiteUrl}/_api/web/getFileByServerRelativeUrl('{targetUrl}')/continueUpload(uploadId=guid'{uploadId}',fileOffset={offset})";
client.UploadData(endpointUrl, buffer);
}
offset += bytesRead;
Console.WriteLine("%{0:P} completed", offset / (float)inputStream.Length);
}
}
public void UploadLargeFileUsingBytes(string authToken, string formDigest, string fileName, byte[] fileBytes, string targetFolderUrl, int chunkSizeBytes = 2048)
{
if (fileBytes.Length < chunkSizeBytes)
{
UploadSmallFile(authToken, formDigest, targetFolderUrl, fileName, fileBytes);
}
else
{
using var client = new WebClient();
client.BaseAddress = spAppInit.SPSiteUrl;
client.Headers.Add("X-RequestDigest", formDigest);
client.Headers.Add("content-type", "application/json;odata=verbose");
client.Headers.Add("Authorization", $"Bearer {authToken}");
var createFileRequestUrl = $"{spAppInit.SPSiteUrl}/_api/web/GetFolderByServerRelativeUrl('{targetFolderUrl}')/files/add(url='{fileName}',overwrite=true)";
client.UploadString(createFileRequestUrl, "POST");
var targetUrl = Path.Combine(targetFolderUrl, fileName);
var firstChunk = true;
var uploadId = Guid.NewGuid();
var offset = 0L;
using var inputStream = ReadFileStreamFromByte(fileBytes);
var buffer = new byte[chunkSizeBytes];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
if (firstChunk && inputStream.Length > chunkSizeBytes)
{
var endpointUrl = $"{spAppInit.SPSiteUrl}/_api/web/GetFileByServerRelativeUrl('{targetUrl}')/startUpload(uploadId=guid'{uploadId}')";
client.UploadData(endpointUrl, buffer);
firstChunk = false;
}
else if (inputStream.Position == inputStream.Length)
{
var endpointUrl = $"{spAppInit.SPSiteUrl}/_api/web/GetFileByServerRelativeUrl('{targetUrl}')/finishUpload(uploadId=guid'{uploadId}',fileOffset={offset})";
var finalBuffer = new byte[bytesRead];
Array.Copy(buffer, finalBuffer, finalBuffer.Length);
client.UploadData(endpointUrl, finalBuffer);
}
else
{
var endpointUrl = $"{spAppInit.SPSiteUrl}/_api/web/GetFileByServerRelativeUrl('{targetUrl}')/continueUpload(uploadId=guid'{uploadId}',fileOffset={offset})";
client.UploadData(endpointUrl, buffer);
}
offset += bytesRead;
Console.WriteLine("%{0:P} completed", offset / (float)inputStream.Length);
}
}
}
}
I don't like pasting the whole project. However, even after being very selective, this is still a lot of code, but its communication code that I do not understand as I started with the newer HttpClient only as (some random HttpClient injection in my API):
services.AddCustomHttpClient<ILetterServiceApi, LetterServiceApi>(Constants.ApiServiceNamedClientLetter, baseAddress!);
Where AddCustomHttpClient is,
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCustomHttpClient<TInterface, TImplementation>(this IServiceCollection services, string serviceName, string baseAddress)
where TInterface: class
where TImplementation: class, TInterface
{
services.AddHttpClient<TInterface, TImplementation>(serviceName, config =>
{
config.BaseAddress = new Uri(baseAddress);
config.Timeout = new TimeSpan(0, 0, 30);
})
.AddHttpMessageHandler<RequestHandler>();
return services;
}
}
I have made a lot of modern modifications to the code and also Am in the process of converting this class (in a remote assembly) to conform to the .Net Core's .AddSharePoint() DI pattern, and for that, I need to get rid of obsolete (HttpWebRequest)WebRequest
Update:
I managed to convert a rather simple method:
private SPFolderResponse? GetFolderFiles(string authToken, string requestDigest, string folderName)
{
using var client = new HttpClient();
var serverRelativeFolderUrl = $"{spAppInit.RelativeUrl}/{folderName}";
var folderApiUrl = $"{spAppInit.SiteUrl}/_api/web/GetFolderByServerRelativeUrl('/{serverRelativeFolderUrl}')/Files";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-RequestDigest", requestDigest);
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {authToken}");
var result = client.GetStringAsync(folderApiUrl).GetAwaiter().GetResult();
var response = JsonSerializer.Deserialize<SPFolderResponse>(result, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return response;
}
But the other ones like the Token, Digest and Upload ones are still dodgy...

through exception in mvc on send email

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;
}
}

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");
}

Stream file from ftp in localhost working in azure no

Hi I using VisualStudio 2012 and I have created web site which reads info (from .csv) from external ftp site. When I running it on local host everything works fine, but then I deployed it to azure web sites it is not working, just show zeros everywhere were should be numbers. (Dont get info from ftp)
public static List<ApiClient.Models.StatsList> GetStatsData(string Ticket, DateTime start, DateTime end, int CampaignId, String CampaignName)
{
//--------------------------------------------------------------------------------------------------------
//Gets stats from GetAdsStats service (included: Banner id, impressions, and clicks)
//--------------------------------------------------------------------------------------------------------
List<ApiClient.Models.StatsList> FullList = GetAdStatsService.GetAdsStats(Ticket, start, end, CampaignId);
List<LikesDislikesList> LikeDislike = new List<LikesDislikesList>();
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
string day;
string month;
if (DateTime.Today.AddDays(-1).Day.ToString().Count() == 1)
{
day = "0" + DateTime.Today.AddDays(-1).Day;
}
else
{
day = DateTime.Today.AddDays(-1).Day.ToString();
}
if (DateTime.Today.Month.ToString().Count() == 1)
{
month = "0" + DateTime.Today.Month;
}
else
{
month = DateTime.Today.Month.ToString();
}
try
{
string uri = "ftp://siteAdres" + CampaignName.Replace(" ", "_") + "_Optimizing_events_" + day + "-" + month + "-" + DateTime.Today.Year + ".csv";
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return FullList;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader csvStream = new StreamReader(response.GetResponseStream());
//--------------------------------------------------------------------------------------------------------
//Read Likes/Dislikes from csv file stream
//--------------------------------------------------------------------------------------------------------
using (var rd = csvStream)
{
int iname = -1;
int ilikes = -1;
int idislikes = -1;
while (!rd.EndOfStream)
{
var raw = rd.ReadLine().Split((char)9);
if (rd.Peek() == -1)
{
break;
}
if (ilikes == -1 || idislikes == -1)
{
for (int i = 0; i < raw.Length; i++)
{
if (raw[i] == "Event name")
iname = i;
if (raw[i] == "Custom Event 14")
ilikes = i;
if (raw[i] == "Custom Event 15")
{
idislikes = i;
raw = rd.ReadLine().Split((char)9);
}
}
}
else
{
LikeDislike.Add(new LikesDislikesList() { Likes = Convert.ToInt32(raw[ilikes]), Dislikes = Convert.ToInt32(raw[idislikes]), Name = raw[iname] });
}
}
}
response.Close();
}
catch(Exception ex)
{
log4net.Config.XmlConfigurator.Configure();
log.Warn("GetAdStatsService.cs " + ex);
}
//--------------------------------------------------------------------------------------------------------
//Add like/dislike values for certain banners
//--------------------------------------------------------------------------------------------------------
foreach (var element in FullList)
{
foreach (var el in LikeDislike)
{
if (element.name == el.Name)
{
element.Likes = el.Likes;
element.Dislikes = el.Dislikes;
}
}
}
return FullList;
}
}
}
Check FtpWebResponse.StatusCode before calling response.GetResponseStream(). You are probably having come kind of connection error. My guess would be firewall settings on your Azure VM.

Read Image stored in Oracle using Long DataType

I want to read the image stored in Oracle Long datatype.
Number of images are stored in a remote Oracle database in a column with datatype long. I just need to retrieve those images and show them on my aspx page.
I could retrieve the image from database but when tried to caste it to byte array, it threw error that, string can not be converted to byte[]'.
Anybody have any suggestions on how to retrieve these images stored in long column in database.
byte[] signatureBlobReceived = cls_TBL_BROKER_BL.GetInstance().GetSignatureBlobFromAccountNumber_BL(strCRNnumber);
return File(signatureBlobReceived, "image/jpeg");
public byte[] GetSignatureBlobFromAccountNumber_BL()
{
object SignatureBlob = null;
Database db = DatabaseFactory.CreateDatabase("imageConnectionString");
DbCommand dbc = db.GetSqlStringCommand(ConfigurationSettings.AppSettings["signqry"].ToString());
dbc.CommandType = CommandType.Text;
SignatureBlob = db.ExecuteScalar(dbc);
byte[] array = Encoding.ASCII.GetBytes(Convert.ToString(SignatureBlob));
string aa = string.Empty;
return array;
}
Query used is:
<add key="signqry" value="SELECT image FROM table1"/> `
Try this (odp.net)
string connStr = "User Id=user;Password=pwd;Data Source=mySID;";
OracleConnection _conn = new OracleConnection(connStr);
_conn.Open();
string sel = #"select long_raw_col from long_raw_test";
OracleCommand cmd = new OracleCommand(sel, _conn);
cmd.InitialLONGFetchSize = 5000;
OracleDataReader reader = cmd.ExecuteReader();
int rows = 0;
// loop through rows from table
while (reader.Read())
{
rows++;
byte[] buf = new byte[5000];
long bytesRead = reader.GetBytes(reader.GetOrdinal("long_raw_col"), 0, buf, 0, 5000);
FileStream fs = new FileStream("C:\\test\\test_long" + rows + ".dat", FileMode.Create);
fs.Write(buf, 0, (int)bytesRead);
fs.Close();
Console.WriteLine("Row " + rows + ": Read " + bytesRead + " bytes from table, see test_long" + rows + ".dat");
}
This example just reads the long raw data from Oracle into a byte array, then outputs to a file. Note the InitalLONGFetchSize > 0.
I use this class :my database is informix and the images are stored in Byte type .Hope this can help you.
public class MyPhoto
{
public static Stream RetrievePhoto()
{
DBConnection DAL_Helper = new DBConnection(ConfigurationSettings.AppSettings["connection"].ToString());
Byte[] myByteBuff;
Stream myImgStream;
string qry = "----------";
DataTable dt = DAL_Helper.Return_DataTable(qry);
try
{
if (dt.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
{
myByteBuff = (Byte[])((object)(dt.Rows[0][0]));
myImgStream = new MemoryStream(myByteBuff);
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
catch (Exception ex)
{
myImgStream = RetrievePhotoNoProfile();
}
return myImgStream;
}
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream)
{
return ((MemoryStream)stream).ToArray();
}
else
{
return ReadFully(stream);
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
private static Stream RetrievePhotoNoProfile()
{
string noprofileimgPath = HttpContext.Current.Server.MapPath("~/images/noprofile.png");
System.IO.FileStream fs = new System.IO.FileStream(noprofileimgPath, System.IO.FileMode.Open, FileAccess.Read);
byte[] ba = new byte[fs.Length];
fs.Read(ba, 0, (int)fs.Length);
Stream myImgStream = new MemoryStream(ba);
fs.Close();
return myImgStream;
}
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}

Resources