Itext, access denied on htmlworker.parseToList - asp.net

I have spent far too long trying to work out why I am getting an access denied here so I am
really hoping someone can help?
I am using itextsharp, the latest version downloaded today.
I am parsing an html page within my own project so I can convert it to pdf, but everytime I run
it I get an access denied on path c:\
For starters I cannot work out why it's trying to access the c drive other than the website directory which it definitely has access to.
And I have tried adding network service with full permission to everything but it didn't work.
I even impersonated an admin user in the web config but I still got access denied.
My code is:
string download = new WebClient().DownloadString("http://" + HttpContext.Current.Request.Url.Host + "/pagetoparse.aspx?user=" + userName);
string tempFolder = HttpContext.Current.Server.MapPath("pdfs");
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
string fileName = Path.Combine(tempFolder, "test3.pdf");
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
using (StringReader stringReader = new StringReader(download))
{
List<IElement> parsedList = HTMLWorker.ParseToList(stringReader, null);//<-- fails here!
document.Open();
foreach (object item in parsedList)
{
document.Add((IElement)item);
}
document.Close();
}
}
catch (Exception exc)
{
Console.Error.WriteLine(exc.Message);
}
return document;
It must be obvious, what I am doing wrong??
Bex

Arrrgh! And the answer is:
An empty image tag! It tried to parse it as a path!!

Related

Cannot upload large (>50MB) files to SharePoint 2010 document library

I'm trying to upload a large file to a document library, but it fails after just a few seconds. The upload single document fails silently, upload multiple just shows a failed message. I've turned up the file size limit on the web application to 500MB, and the IIS request length to the same (from this blog), and increased the IIS timeout for good measure. Are there any other size caps that I've missed?
Update I've tried a few files of various sizes, anything 50MB or over fails, so I assume something somewhere is still set to the webapp default.
Update 2 Just tried uploading using the following powershell:
$web = Get-SPWeb http://{site address}
$folder = $web.GetFolder("Site Documents")
$file = Get-Item "C:\mydoc.txt" // ~ 150MB
$folder.Files.Add("SiteDocuments/mydoc.txt", $file.OpenRead(), $false)
and get this exception:
Exception calling "Add" with "3" argument(s): "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL 'http://{site address}/SiteDocuments/mydoc.txt' in this Web."
which strikes me as odd as of course the file wouldn't exist until it's been uploaded? N.B. while the document library has the name Site Documents, it has the URL SiteDocuments. Not sure why...
Are you sure you updated the right webapp? Is the filetype blocked by the server? Is there adequate space in your content database? I would check ULS logs after that and see if there is another error since it seems you hit the 3 spots you would need too update.
for uploading a large file, you can use the PUT method instead of using the other ways to upload a document.
by using a put method you will save the file into content database directly. see the example below
Note: the disadvantage of the code below is you cannot catch the object that is responsible for uploading directly, on other word, you cannot update the additional custom properties of the uploaded document directly.
public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)
{
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = “PUT”;
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false;
}
//Return the final upload status
return isUploaded;
}
and here are an example of calling this method
UploadFileToDocumentLibrary(#”C:\test.txt”, #”http://home-vs/Shared Documents/textfile.pdf”);

Uploading Image Access to C drive denied

so i have this code:
try
{
if ((uplImage.FileName != ""))
{
//to allow only jpg gif and png files to be uploaded.
string extension = Path.GetExtension(uplImage.PostedFile.FileName);
if (((extension == ".jpg") || ((extension == ".gif") || (extension == ".png"))))
{
DALBio bio = new DALBio();
byte[] raw;
FileStream fs = new FileStream(uplImage.PostedFile.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
raw = new byte[fs.Length];
fs.Read(raw, 0, Convert.ToInt32(fs.Length));
bio.PlayerID = Session["playerID"].ToString();
bio.Pending = 'Y';
bio.Photo = raw;
DALBio.insertImage(bio);
}
}
}
catch (Exception e1)
{
Label1.Text = e1.InnerException.ToString();
}
and the program breaks on the FileStream fs = new FileStream line.
at first my image was in my downloads folder and it said access to c:\prog(x86)\filefolder\file\folder\and so on was denied
so i moved it to my images folder, and i got the same error to a different folder on c.
my google searches have said it oculd be a permissions thing (if its UAC, that makes no sense, i have all permissions possible across the board). another thing is it could be a change in my web.config file about application settings, however without any examples or better insight than what i did get from those searches, i am lost.
You have to give account under which ASP.NET worker process runs "write" permissions. Ordinary it's Network Services account.

Image to be loaded into pdf file created from Sharepoint Server Images Folder

I am using ItextSharp Library to generate pdf files on a button click on my SharePoint Site. I want to use a logo on the pdf whose image resides on the Images Folder of Sharepoint. I am unable to do that.
Can someone help me with it.
Below is the code that I am using which is getting the instance from window32 which I dont want.
protected void button1_OnClick(object sender, EventArgs e)
{
Font Arial = FontFactory.GetFont("Arial", 12, BaseColor.GREEN);
Font Verdana = FontFactory.GetFont("Verdana", 16, Font.BOLDITALIC, new BaseColor(125, 88, 15));
string imagepath = SPContext.Current.Web + "/_layouts/Images/Image1.png";
using (var ms = new MemoryStream())
{
using (var document = new Document(PageSize.A4,50,50,15,15))
{
PdfWriter.GetInstance(document, ms);
document.Open();
Paragraph img = new Paragraph();
Image jpg = Image.GetInstance(imagepath); --- Getting an error here stating "Could not find a part of the path 'c:\windows\system32\inetsrv\CustomSystem\_layouts\Images\Image1.png'"
img.Add(jpg );
}
}
}
Please help!
I'm not too familiar with SharePoint development but you're problem is with this line:
string imagepath = SPContext.Current.Web + "/_layouts/Images/Image1.png";
This string must be an absolute path path such as c:\www\sites\image.png, not a relative one which it is right now. I can tell its relative because when you ask ASP.Net to get something for you but you don't specify a path it looks in %WINDOWS%.
I don't know how you're using SPContext.Current.Web but according to the docs calling .ToString() on it returns the title of the website which is what would happen if you concatenated it with a string like you are. My guess is that you don't need that but could be wrong.
If the layouts folder is a subfolder of the folder that the file you are working on is in then you should be able to use Server.MapPath to get the absolute path:
string imagepath = Server.MapPath("_layouts/Images/Image1.png");
i have done like this in my sharepoint site
string url = "http://fspl-dsktp-038:8000/Style%20Library/FSPL/CorporateLogo.png";
//iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Server.MapPath("images") + "//images/FSPL LOGO.png");
iTextSharp.text.Image logo =iTextSharp.text.Image.GetInstance(url);
logo.ScaleAbsolute(90, 90);
Imagecell.AddElement(logo);
gvTable.AddCell(Imagecell);

How do I stream .flv files from SQL database

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.

FileUpload problem with Struts on server

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.

Resources