I want to store .flv files in the database and not in the file system.
This is what I can do right now:
Successfully convert .wmv and .mpeg to .flv with ffmpeg.
Store images in SQL Server and show them on my page with an httphandler.
Same with .avi and .mpeg videos. (It's up to the user's software if he can view it though)
Play .flv files in the browser if the file is located in the file system and not in the database.
What I can't do is:
Stream .flv videos to JW Player directly from the database. (Stored as binary data)
I've searched the internet for two days now but I can't get it to work. It feels as if I'm almost there though. The JW Player opens up and starts to "buffer", but nothing happens.
I know there's no easy answer but if anyone has done this before, or something similar, I'd like to know how you did. I feel I've got too much code to post it all here.
Thanks in advance!
I got it to work but I have no idea as to how efficient it is. Is it better to stream from the file system than from the database in terms of connections, efficency, load etc.
I could use some pointers on this!
I'm using JW Player here, hence "swfobject.js" and "player.swf"
httpHandler:
public class ViewFilm : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
// Check if id was given
if (context.Request.QueryString["id"] != null)
{
string movId = context.Request.QueryString["id"];
// Connect to DB and get the item id
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("GetItem", con))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter sqlParam = cmd.Parameters.Add("#itemId", SqlDbType.Int);
sqlParam.Value = movId;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
dr.Read();
// Add HTTP header stuff: cache, content type and length
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetLastModified(DateTime.Now);
context.Response.AppendHeader("Content-Type", "video/x-flv");
context.Response.AppendHeader("Content-Length", ((byte[])dr["data"]).Length.ToString());
context.Response.BinaryWrite((byte[])dr["data"]);
}
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
public bool IsReusable
{
get { return false; }
}
}
javascript
The function adds a player to <div id="video1"> and can be called e.g when a user clicks a button.
<script type='text/javascript' src='swfobject.js'></script>
<script type="text/javascript" language="javascript">
function vid() {
var s1 = new SWFObject('player.swf', 'player1', '480', '270', '9');
s1.addParam('allowfullscreen', 'true');
s1.addParam('allowscriptaccess', 'always');
s1.addVariable('file', encodeURIComponent('ViewFilm.ashx?id=10'));
s1.addVariable('type', 'video');
s1.write(document.getElementById("video1"));
}
</script>
Not sure exactly how literally to take "stream directly from the database", but would it work to set the source "file" for the JW Player to "ServeFLV.aspx?id=123", and have ServeFLV.aspx retrieve the bytes from the database, and write them out to the response with no markup?
If you're using SQL Server 2008 you could use varbinary(MAX) FILESTREAM which would allow the files to be managed by the database but still give you access to a FileStream from .NET.
Related
Due to the limitation of the system, i am not allowed to use htmlagilitypack as i dont have the rights to refer the library. So i can only use native asp.net programming language to parse page.
e.g. i want to scrap this page https://sg.linkedin.com/job/google/jobs/ to get the list of google jobs ( just an example, i am not really planning to get this list but my own company's) , i see they are under how can i extra these jobs description and name.
My current codes are
System.Net.WebClient client = new System.Net.WebClient();
try{
System.IO.Stream myStream = client.OpenRead("https://sg.linkedin.com/job/google/jobs/");
System.IO.StreamReader sr = new System.IO.StreamReader(myStream);
string htmlContent = sr.ReadToEnd();
//do not know how to carry on
}catch(Exception e){
Response.Write(e.Message);
}
how can i carry on?
You can fetch that page and use a regular expression to isolate the useful parts. If you get real lucky, you may have a valid XML file:
var html = new WebClient().DownloadString("https://sg.linkedin.com/job/google/jobs/");
var jobs = new XmlDocument();
jobs.LoadXml(Regex.Replace(Regex.Match(html,
#"<ul class=""jobs"">[\s\S]*?</ul>").Value,
#"itemscope | itemprop="".*?""", "")); // clean invalid attributes
foreach (XmlElement job in jobs.SelectNodes("//li[#class='job']"))
{
Console.WriteLine(job.SelectSingleNode(".//a[#class='company']").InnerText);
Console.WriteLine(job.SelectSingleNode(".//h2/a").InnerText);
Console.WriteLine(job.SelectSingleNode(".//p[#class='abstract']").InnerText);
Console.WriteLine();
}
How do I upload a file to an Acumatica Screen through HTTP virtual path?
For example, I would like to upload mysite.com/files/abc.pdf to the Sales orders screen.
Below is a code snippet to achieve your goal.It is reading file from HTTP URL and attaching it to one of the existing Case.
//Graph for file management
PX.SM.UploadFileMaintenance filegraph = PXGraph.CreateInstance<PX.SM.UploadFileMaintenance>();
//Since you need file from HTTP URL - below is a sample
WebRequest request = WebRequest.Create("http://www.pdf995.com/samples/pdf.pdf");
using (System.IO.Stream dataStream = request.GetResponse().GetResponseStream())
{
using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
{
dataStream.CopyTo(mStream);
byte[] data = mStream.ToArray();
//Create file info, you may check different overloads as per your need
PX.SM.FileInfo fileinfo = new PX.SM.FileInfo("case.pdf", null, data);
if (filegraph.SaveFile(fileinfo))
{
if (fileinfo.UID.HasValue)
{
// To attach the file to case screen - example
CRCaseMaint graphCase = PXGraph.CreateInstance<CRCaseMaint>();
//Locate existing case
graphCase.Case.Current = graphCase.Case.Search<CRCase.caseCD>("<Case to which you want to attach file>");
//To Attach file
PXNoteAttribute.SetFileNotes(graphCase.Case.Cache, graphCase.Case.Current, fileinfo.UID.Value);
//To Attach note
PXNoteAttribute.SetNote(graphCase.Case.Cache, graphCase.Case.Current, "<Note you wish to specify>");
//Save case
graphCase.Save.Press();
}
}
}
}
I am using a .txt file to log exceptions thrown from various methods in my asp.net (4.0) project. I have a page which reads texts from that file on every 10 minutes. If there are Read and Write attempts at the same time, will it throw any exception? If you have any better technique to handle such problem, please let me know. Currently, i'm using the following code-
Writing to the file
using (StreamWriter Writer = new StreamWriter(LogFilePath, true))
{
Writer.WriteLine(ErrorMsg);
}
Reading from the file
using (FileStream fs=File.OpenRead(LogFilePath))
{
using (StreamReader reader = new StreamReader(fs))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Response.Write(line + "</br>");
}
}
}
Is these approaches are safe?
Thank you.
As people already suggested, the simplest way is to use external libraries, which handle locking of the file.
However, if you still want to use your own code to do that, make sure you're synchronizing access to the file, using lock:
lock(lockObj)
{
using (StreamWriter Writer = new StreamWriter(LogFilePath, true))
{
Writer.WriteLine(ErrorMsg);
}
}
where lockObj is
static object lockObj = new object();
I am working with Spring MVC 3 and JasperReports. I've created some great PDF and Xls reports without a problem. What I would like to do is display the created HTML report on screen for the user as a preview of the report they are getting, wrapped in the website template. Is there a way to do this?
I haven't found any tutorials/articles on this subject, I did find a book on JasperReports 3.5 for Java Developers that kind a addressed this. (I'm a noob on this so bear with me.) My understanding of this is that I have to redirect the input stream to the browser. I figure that there must be an easier way! And a way to strip the HTML report header and footer from it.
Any help would be appreciated!
Instead of using another framework to solve my problem. I solved it like this:
#RequestMapping(value = "/report", method = RequestMethod.POST)
public String htmlReport(#RequestParam(value = "beginDate") Date begin,
#RequestParam(value = "endDate", required = false) Date end,
ModelMap map) {
try {
// Setup my data connection
OracleDataSource ds = new OracleDataSource();
ds.setURL("jdbc:oracle:thin:user/password#10.10.10.10:1521:tst3");
Connection conn = ds.getConnection();
// Get the jasper report object located in package org.dphhs.tarts.reports
// Load it
InputStream reportStream = this.getClass().getResourceAsStream("reports/tartsCostAllocation.jasper");
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportStream);
// Populate report with data
JasperPrint jasperPrint =
JasperFillManager.fillReport(jasperReport, new HashMap(), conn);
// Create report exporter to be in Html
JRExporter exporter = new JRHtmlExporter();
// Create string buffer to store completed report
StringBuffer sb = new StringBuffer();
// Setup report, no header, no footer, no images for layout
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
// When report is exported send to string buffer
exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sb);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
// Export the report, store to sb
exporter.exportReport();
// Use Jsoup to clean the report table html to output to browser
Whitelist allowedHtml = new Whitelist();
allowedHtml.addTags("table", "tr", "td", "span");
allowedHtml.addTags("table", "style", "cellpadding", "cellspacing", "border", "bgcolor");
allowedHtml.addAttributes("tr", "valign");
allowedHtml.addAttributes("td", "colspan", "style");
allowedHtml.addAttributes("span", "style");
String html = Jsoup.clean(sb.toString(), allowedHtml);
// Add report to map
map.addAttribute("report", html);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "costallocation/report";
}
I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.