Search Results

Search found 197 results on 8 pages for 'readfile'.

Page 6/8 | < Previous Page | 2 3 4 5 6 7 8  | Next Page >

  • Extra white space, on HTML output, on PHP MVC

    - by user316841
    Hi, I'm getting extra white space, that is not CSS, or nothing like it on the view output: The HTML. I've checked for ? (removed, where I could), saved UTF8 without BOM. Checked for existent white space in the beginning of each file, even at end. This is the structure: index.php - this is the entry point; MODEL/ CONTROLLER/ VIEW/ Let's say, that trough method GET, its sent the var TPL with some value. Let's call it LIST, so it pulls the LIST model, with all data and then show the right template to the user, with the right data. I used and tested, with require_once, include_once, include, even tested with readfile (just to test). The LIST Template opens the header.tpl and footer.tpl; I also tryed to remove this both includes from LIST template, but still, the extra white space continued. This is where the extra white space is coming from. This controller is placed between controller activity runs here , this is where the extra white space is coming from: $model_works-getRows(); $rows = $model_works-rows; if ( !require_once('views/list_works.tpl.php') ) { echo "Error."; } // end if clause The list_works.tpl.php, is basicly HTML with tags; I've t tested by changing the extension to something else, like html. Also, just to remember that at top of this file, we are using require_once to open the header.tpl and at bottom the footer.tpl. I've tested by removing both and the extra white space was still generated. The extra white space is being generated here: EXTRA WHITE SPACE HERE Thanks a lot for looking, ;D

    Read the article

  • RSA C# Encrypt Java Decrypt

    - by user353030
    Hi guys, In my program (server side - Java) I've created keystore file, with command: keytool -genkey -alias myalias -keyalg RSA -validity 10000 -keystore my.keystore and exported related X509 certificate with: keytool -export -alias myalias -file cert.cer -keystore my.keystore After I saved cert.cer on client side (C#) and I write this code: X509Certificate2 x509 = new X509Certificate2(); byte[] rawData = ReadFile("mycert.cer"); x509.Import(rawData); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PublicKey.Key; byte[] plainbytes = System.Text.Encoding.ASCII.GetBytes("My Secret"); byte[] cipherbytes = rsa.Encrypt(plainbytes, true); String cipherHex = convertToHex(cipherContent); byte[] byteArray = encoding.GetBytes(cipherHex); .... I write this Java code on server side: keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream("C:\\my.keystore"), "mypass".toCharArray()); Key key = keyStore.getKey("myalias", "mypass".toCharArray()); if (key instanceof PrivateKey) { Certificate cert = keyStore.getCertificate("myalias"); PublicKey pubKey = cert.getPublicKey(); privKey = (PrivateKey)key; } byte[] toDecodeBytes = new BigInteger(encodeMessageHex, 16).toByteArray(); Cipher decCipher = Cipher.getInstance("RSA"); decCipher.init(Cipher.DECRYPT_MODE, privKey); byte[] decodeMessageBytes = decCipher.doFinal(toDecodeBytes); String decodeMessageString = new String(decodeMessageBytes); I receive this error: javax.crypto.BadPaddingException: Data must start with zero Can you help me, please? Thanks thanks,

    Read the article

  • Delphi: Alternative to using Assign/ReadLn for text file reading

    - by Ian Boyd
    i want to process a text file line by line. In the olden days i loaded the file into a StringList: slFile := TStringList.Create(); slFile.LoadFromFile(filename); for i := 0 to slFile.Count-1 do begin oneLine := slFile.Strings[i]; //process the line end; Problem with that is once the file gets to be a few hundred megabytes, i have to allocate a huge chunk of memory; when really i only need enough memory to hold one line at a time. (Plus, you can't really indicate progress when you the system is locked up loading the file in step 1). The i tried using the native, and recommended, file I/O routines provided by Delphi: var f: TextFile; begin Assign(filename, f); while ReadLn(f, oneLine) do begin //process the line end; Problem withAssign is that there is no option to read the file without locking (i.e. fmShareDenyNone). The former stringlist example doesn't support no-lock either, unless you change it to LoadFromStream: slFile := TStringList.Create; stream := TFileStream.Create(filename, fmOpenRead or fmShareDenyNone); slFile.LoadFromStream(stream); stream.Free; for i := 0 to slFile.Count-1 do begin oneLine := slFile.Strings[i]; //process the line end; So now even though i've gained no locks being held, i'm back to loading the entire file into memory. Is there some alternative to Assign/ReadLn, where i can read a file line-by-line, without taking a sharing lock? i'd rather not get directly into Win32 CreateFile/ReadFile, and having to deal with allocating buffers and detecting CR, LF, CRLF's. i thought about memory mapped files, but there's the difficulty if the entire file doesn't fit (map) into virtual memory, and having to maps views (pieces) of the file at a time. Starts to get ugly. i just want Assign with fmShareDenyNone!

    Read the article

  • Improve Efficiency for This Text Processing Code

    - by johnv
    I am writing a program that counts the number of words in a text file which is already in lowercase and separated by spaces. I want to use a dictionary and only count the word IF it's within the dictionary. The problem is the dictionary is quite large (~100,000 words) and each text document has also ~50,000 words. As such, the codes that I wrote below gets very slow (takes about 15 sec to process one document on a quad i7 machine). I'm wondering if there's something wrong with my coding and if the efficiency of the program can be improved. Thanks so much for your help. Code below: public static string WordCount(string countInput) { string[] keywords = ReadDic(); /* read dictionary txt file*/ /*then reads the main text file*/ Dictionary<string, int> dict = ReadFile(countInput).Split(' ') .Select(c => c) .Where(c => keywords.Contains(c)) .GroupBy(c => c) .Select(g => new { word = g.Key, count = g.Count() }) .OrderBy(g => g.word) .ToDictionary(d => d.word, d => d.count); int s = dict.Sum(e => e.Value); string k = s.ToString(); return k; }

    Read the article

  • Bubble sort algorithm implementations (Haskell vs. C)

    - by kingping
    Hello. I have written 2 implementation of bubble sort algorithm in C and Haskell. Haskell implementation: module Main where main = do contents <- readFile "./data" print "Data loaded. Sorting.." let newcontents = bubblesort contents writeFile "./data_new_ghc" newcontents print "Sorting done" bubblesort list = sort list [] False rev = reverse -- separated. To see rev2 = reverse -- who calls the routine sort (x1:x2:xs) acc _ | x1 > x2 = sort (x1:xs) (x2:acc) True sort (x1:xs) acc flag = sort xs (x1:acc) flag sort [] acc True = sort (rev acc) [] False sort _ acc _ = rev2 acc I've compared these two implementations having run both on file with size of 20 KiB. C implementation took about a second, Haskell — about 1 min 10 sec. I have also profiled the Haskell application: Compile for profiling: C:\Temp ghc -prof -auto-all -O --make Main Profile: C:\Temp Main.exe +RTS -p and got these results. This is a pseudocode of the algorithm: procedure bubbleSort( A : list of sortable items ) defined as: do swapped := false for each i in 0 to length(A) - 2 inclusive do: if A[i] > A[i+1] then swap( A[i], A[i+1] ) swapped := true end if end for while swapped end procedure I wonder if it's possible to make Haskell implementation work faster without changing the algorithm (there's are actually a few tricks to make it work faster, but neither implementations have these optimizations)

    Read the article

  • Content-disposition:inline header won't show images inline?

    - by hamstar
    I'm trying to show an image inline on a page. It is being served by a codeigniter controller. class Asset extends MY_Controller { function index( $folder, $file ) { $asset = "assets/$folder/$file"; if ( !file_exists( $asset ) ) { show_404(); return; } switch ( $folder ) { case 'css': header('Content-type: text/css'); break; case 'js': header('Content-type: text/javascript'); break; case 'images': $ext = substr( $file, strrpos($file, '.') ); switch ( $ext ) { case 'jpg': $ext = 'jpeg'; break; case 'svg': $ext = 'svg+xml'; break; } header('Content-Disposition: inline'); header('Content-type: image/'.$ext); } readfile( $asset ); } } When I load a image in Chrome of FF its pops up the download window. I know when the browser can't display the content inline it will force a download anyway, but these are PNG and GIF images which display in the browser fine otherwise. In IE it doesn't force a download but it displays the image in ASCII. If I comment out the entire image case it FF and Chrome both display the ASCII but not the image. I thought setting the content type would allow FF and Chrome to show the actual image, and also allow the location to be used as an src. The javascript and css shows fine of course. Anyone got any ideas how I can make the images show properly? Thanks :)

    Read the article

  • ZIP Numerous Blob Files

    - by Michael
    I have a database table that contains numerous PDF blob files. I am attempting to combine all of the files into a single ZIP file that I can download and then print. Please help! <?php include 'config.php'; include 'connect.php'; $session= $_GET[session]; $query = " SELECT $tbl_uploads.username, $tbl_uploads.description, $tbl_uploads.type, $tbl_uploads.size, $tbl_uploads.content, $tbl_members.session FROM $tbl_uploads LEFT JOIN $tbl_members ON $tbl_uploads.username = $tbl_members.username WHERE $tbl_members.session= '$session'"; $result = mysql_query($query) or die('Error, query failed'); while(list($username, $description, $type, $size, $content) = mysql_fetch_array($result)) { header("Content-length: $size"); header("Content-type: $type"); header("Content-Disposition: inline; filename=$username-$description.pdf"); echo $content; } $files = array('File 1 from database', 'File 2 from database'); $zip = new ZipArchive; $zip->open('file.zip', ZipArchive::CREATE); foreach ($files as $file) { $zip->addFile($file); } $zip->close(); header('Content-Type: application/zip'); header('Content-disposition: attachment; filename=filename.zip'); header('Content-Length: ' . filesize($zipfilename)); readfile($zipname); mysql_close($link); exit; ?>

    Read the article

  • php file force download

    - by droidus
    When I use this code to download this image (only used for testing purposes), I open the downloaded image, and all it gives me is an error. i tried it in chrome. opening it with windows photo viewer, it says that it can't display the picture because it is empty??? here is the code: <?PHP // Define the path to file $file = 'http://www.media.lonelyplanet.com/lpi/12553/12553-11/469x264.jpg'; if(!file) { // File doesn't exist, output error die('file not found'); } else { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } ?>

    Read the article

  • Delphi: Alternative to using Reset/ReadLn for text file reading

    - by Ian Boyd
    i want to process a text file line by line. In the olden days i loaded the file into a StringList: slFile := TStringList.Create(); slFile.LoadFromFile(filename); for i := 0 to slFile.Count-1 do begin oneLine := slFile.Strings[i]; //process the line end; Problem with that is once the file gets to be a few hundred megabytes, i have to allocate a huge chunk of memory; when really i only need enough memory to hold one line at a time. (Plus, you can't really indicate progress when you the system is locked up loading the file in step 1). The i tried using the native, and recommended, file I/O routines provided by Delphi: var f: TextFile; begin Reset(f, filename); while ReadLn(f, oneLine) do begin //process the line end; Problem withAssign is that there is no option to read the file without locking (i.e. fmShareDenyNone). The former stringlist example doesn't support no-lock either, unless you change it to LoadFromStream: slFile := TStringList.Create; stream := TFileStream.Create(filename, fmOpenRead or fmShareDenyNone); slFile.LoadFromStream(stream); stream.Free; for i := 0 to slFile.Count-1 do begin oneLine := slFile.Strings[i]; //process the line end; So now even though i've gained no locks being held, i'm back to loading the entire file into memory. Is there some alternative to Assign/ReadLn, where i can read a file line-by-line, without taking a sharing lock? i'd rather not get directly into Win32 CreateFile/ReadFile, and having to deal with allocating buffers and detecting CR, LF, CRLF's. i thought about memory mapped files, but there's the difficulty if the entire file doesn't fit (map) into virtual memory, and having to maps views (pieces) of the file at a time. Starts to get ugly. i just want Reset with fmShareDenyNone!

    Read the article

  • Can parser combinators be made efficient?

    - by Jon Harrop
    Around 6 years ago, I benchmarked my own parser combinators in OCaml and found that they were ~5× slower than the parser generators on offer at the time. I recently revisited this subject and benchmarked Haskell's Parsec vs a simple hand-rolled precedence climbing parser written in F# and was surprised to find the F# to be 25× faster than the Haskell. Here's the Haskell code I used to read a large mathematical expression from file, parse and evaluate it: import Control.Applicative import Text.Parsec hiding ((<|>)) expr = chainl1 term ((+) <$ char '+' <|> (-) <$ char '-') term = chainl1 fact ((*) <$ char '*' <|> div <$ char '/') fact = read <$> many1 digit <|> char '(' *> expr <* char ')' eval :: String -> Int eval = either (error . show) id . parse expr "" . filter (/= ' ') main :: IO () main = do file <- readFile "expr" putStr $ show $ eval file putStr "\n" and here's my self-contained precedence climbing parser in F#: let rec (|Expr|) (P(f, xs)) = Expr(loop (' ', f, xs)) and loop = function | ' ' as oop, f, ('+' | '-' as op)::P(g, xs) | (' ' | '+' | '-' as oop), f, ('*' | '/' as op)::P(g, xs) -> let h, xs = loop (op, g, xs) let op = match op with | '+' -> (+) | '-' -> (-) | '*' -> (*) | '/' -> (/) loop (oop, op f h, xs) | _, f, xs -> f, xs and (|P|) = function | '('::Expr(f, ')'::xs) -> P(f, xs) | c::xs when '0' <= c && c <= '9' -> P(int(string c), xs) My impression is that even state-of-the-art parser combinators waste a lot of time back tracking. Is that correct? If so, is it possible to write parser combinators that generate state machines to obtain competitive performance or is it necessary to use code generation?

    Read the article

  • PHP ZipArchive Empty in IE

    - by Jesse Bunch
    Hi, I am using PHP's ZipArchive class to create a zip file containing photos and then serve it up to the browser for download. Here is my code: /** * Grabs the order, packages the files, and serves them up for download. * * @param string $intEntryID * @return void * @author Jesse Bunch */ public static function download_order_by_entry_id($intUniqueID) { $objCustomer = PhotoCustomer::get_customer_by_unique_id($intUniqueID); if ($objCustomer): if (!class_exists('ZipArchive')): trigger_error('ZipArchive Class does not exist', E_USER_ERROR); endif; $objZip = new ZipArchive(); $strZipFilename = sprintf('%s/application/tmp/%s-%s.zip', $_SERVER['DOCUMENT_ROOT'], $objCustomer->getEntryID(), time()); if ($objZip->open($strZipFilename, ZIPARCHIVE::CREATE) !== TRUE): trigger_error('Unable to create zip archive', E_USER_ERROR); endif; foreach($objCustomer->arrPhotosRequested as $objPhoto): $filename = PhotoCart::replace_ee_file_dir_in_string($objPhoto->strHighRes); $objZip->addFile($filename,sprintf('/press_photos/%s-%s', $objPhoto->getEntryID(), basename($filename))); endforeach; $objZip->close(); header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($strZipFilename)).' GMT', TRUE, 200); header('Cache-Control: no-cache', TRUE); header('Pragma: Public', TRUE); header('Expires: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT', TRUE); header('Content-Length: '.filesize($strZipFilename), TRUE); header('Content-disposition: attachment; filename=press_photos.zip', TRUE); header('Content-Type: application/octet-stream', TRUE); ob_start(); readfile($strZipFilename); ob_end_flush(); exit; else: trigger_error('Invalid Customer', E_USER_ERROR); endif; } This code works really well with all browsers but IE. In IE, the file downloads correctly, but the zip archive is empty. When trying to extract the files, Windows tells me that the zip archive is corrupt. Has anyone had this issue before?

    Read the article

  • Why would fopen fail to open a file that exists?

    - by void
    I'm on Windows XP using Visual Studio 6 (yes I know it's old) building/maintaining a C++ DLL. I'm encountered a problem with fopen failing to open an existing file, it always returns NULL. I've tried: Checking errno and _doserrno by setting both to zero and then checking them again, both remain zero, and thus GetLastError() reports no errors. I know fopen isn't required to set errno when it encounters an error according to a C standard. Hardcoding the file path, which are not relative. Tried on another developers machine which the same result. The really strange thing is CreateFile works and the file can be read with ReadFile. We believe this works in a release build, however we are also seeing some very odd behaviour in other areas of the application and we're not sure if this is related. The code is below, I don't see anything odd it looks quite standard to me. The source file hasn't changed for just under half a year. HRESULT CDataHandler::LoadFile( CStdString szFilePath ) { //Code FILE* pFile; if ( NULL == ( pFile = fopen( szFilePath.c_str(), "rb") ) ) { return S_FALSE; } //More code }

    Read the article

  • Force Download Files Broken Headers wrong?

    - by Sinan
    if($_POST['mode']=="save") { $root = $_SERVER['DOCUMENT_ROOT']; $path = "/mcboeking/"; $path = $root.$path; $file_path = $_POST['path']; $file = $path.$file_path; if(!file_exists($file)) { die('file not found'); } else { header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-Type: application/force-download'); header("Content-Disposition: attachment; filename=\"".basename($file)."\";" ); header("Content-Length: ".filesize($file)); readfile($file);}} As soon as i download the file and open it i get an error message. When i try to open a .doc i get the message : file structure is invalid. And when i try to open a jpg : This file can not be opened. It may be corrupt or a file format that Preview does not recognize. But when i download PDF files, they open without any problem. Can someone help me? P.s. i tried different headers including : header('Content-Type: application/octet-stream');

    Read the article

  • File Handler returning garbled files.

    - by forcripesake
    For the past 3 months my site has been using a PHP file handler in combination with htaccess. Users accessing the uploads folder of the site would be redirected to the handler as such: RewriteRule ^(.+)\.*$ downloader.php?f=%{REQUEST_FILENAME} [L] The purpose of the file handler is pseudo coded below, followed by actual code. //Check if file exists and user is downloading from uploads directory; True. //Check against a file type white list and set the mime type(); $ctype = mime type; header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); // required for certain browsers header("Content-Type: $ctype"); header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($filename)); readfile("$filename"); As of yesterday, the handler started returning garbled files, unreadable images, and had to be bypassed. I'm wondering what settings could have gone awry to cause this.

    Read the article

  • Does SetFileBandwidthReservation affect memory-mapped file performance?

    - by Ghostrider
    Does this function affect Memory-mapped file performance? Here's the problem I need to solve: I have two applications competing for disk access: "reader" and "updater". Whole system runs on Windows Server 2008 R2 x64 "Updater" constantly accesses disk in a linear manner, updating data. They system is set up in such a way that updater always has infinite data to update. Consider that it is constantly approximating a solution of a huge set of equations that takes up entire 2TB disk drive. Updater uses ReadFile and WriteFile to process data in a linear fashion. "Reader" is occasionally invoked by user to get some pieces of data. Usually user would read several 4kb blocks from the drive and stop. Occasionally user needs to read up to 100mb sequentially. In exceptional cases up to several gigabytes. Reader maps files to memory to get data it needs. What I would like to achieve is for "reader" to have absolute priority so that "updater" would completely stop if needed so that "reader" could get the data user needs ASAP. Is this problem solvable by using SetPriorityClass and SetFileBandwidthReservation calls? I would really hate to put synchronization login in "reader" and "updater" and rather have the OS take care of priorities.

    Read the article

  • Duplicate elements when adding XElement to XDocument

    - by Andy
    I'm writing a program in C# that will go through a bunch of config.xml files and update certain elements, or add them if they don't exist. I have the portion down that updates an element if it exists with this code: XDocument xdoc = XDocument.Parse(ReadFile(_file)); XElement element = xdoc.Elements("project").Elements("logRotator") .Elements("daysToKeep").Single(); element.Value = _DoRevert; But I'm running into issues when I want to add an element that doesn't exist. Most of the time part of the tree is in place and when I use my code it adds another identical tree, and that causes the program reading the xml to blow up. here is how I am attempting to do it xdoc.Element("project").Add(new XElement("logRotator", new XElement("daysToKeep", _day))); and that results in a structure like this(The numToKeep tag was already there): <project> <logRotator> <daysToKeep>10</daysToKeep> </logRotator> <logRotator> <numToKeep>13</numToKeep> </logRotator> </project> but this is what I want <project> <logRotator> <daysToKeep>10</daysToKeep> <numToKeep>13</numToKeep> </logRotator> </project>

    Read the article

  • Python subprocess: 64 bit windows server PIPE doesn't exist :(

    - by Spaceman1861
    I have a GUI that launches selected python scripts and runs it in cmd next to the gui window. I am able to get my launcher to work on my (windows xp 32 bit) laptop but when I upload it to the server(64bit windows iss7) I am running into some issues. The script runs, to my knowledge but spits back no information into the cmd window. My script is a bit of a Frankenstein that I have hacked and slashed together to get it to work I am fairly certain that this is a very bad example of the subprocess module. Just wondering if i could get a hand :). My question is how do i have to alter my code to work on a 64bit windows server. :) from Tkinter import * import pickle,subprocess,errno,time,sys,os PIPE = subprocess.PIPE if subprocess.mswindows: from win32file import ReadFile, WriteFile from win32pipe import PeekNamedPipe import msvcrt else: import select import fcntl def recv_some(p, t=.1, e=1, tr=5, stderr=0): if tr < 1: tr = 1 x = time.time()+t y = [] r = '' pr = p.recv if stderr: pr = p.recv_err while time.time() < x or r: r = pr() if r is None: if e: raise Exception(message) else: break elif r: y.append(r) else: time.sleep(max((x-time.time())/tr, 0)) return ''.join(y) def send_all(p, data): while len(data): sent = p.send(data) if sent is None: raise Exception(message) data = buffer(data, sent) The code above isn't mine def Run(): print filebox.get(0) location = filebox.get(0) location = location.__str__().replace(listbox.get(ANCHOR).__str__(),"") theTime = time.asctime(time.localtime(time.time())) lastbox.delete(0, END) lastbox.insert(END,theTime) for line in CookieCont: if listbox.get(ANCHOR) in line and len(line) > 4: line[4] = theTime else: "Fill In the rip Details to record the time" if __name__ == '__main__': if sys.platform == 'win32' or sys.platform == 'win64': shell, commands, tail = ('cmd', ('cd "'+location+'"',listbox.get(ANCHOR).__str__()), '\r\n') else: return "Please use contact admin" a = Popen(shell, stdin=PIPE, stdout=PIPE) print recv_some(a) for cmd in commands: send_all(a, cmd + tail) print recv_some(a) send_all(a, 'exit' + tail) print recv_some(a, e=0) The Code above is mine :)

    Read the article

  • Downloading a file from a PHP page in C#

    - by FoxyShadoww
    Okay, we have a PHP script that creates an download link from a file and we want to download that file via C#. This works fine with progress etc but when the PHP page gives an error the program downloads the error page and saves it as the requested file. Here is the code we have atm: PHP Code: <?php $path = 'upload/test.rar'; if (file_exists($path)) { $mm_type="application/octet-stream"; header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Type: " . $mm_type); header("Content-Length: " .(string)(filesize($path)) ); header('Content-Disposition: attachment; filename="'.basename($path).'"'); header("Content-Transfer-Encoding: binary\n"); readfile($path); exit(); } else { print 'Sorry, we could not find requested download file.'; } ?> C# Code: private void btnDownload_Click(object sender, EventArgs e) { string url = "http://***.com/download.php"; WebClient client = new WebClient(); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); client.DownloadFileAsync(new Uri(url), @"c:\temp\test.rar"); } private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) { progressBar.Value = e.ProgressPercentage; } void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { MessageBox.Show(print); }

    Read the article

  • Handling Corrupted JPEGs in C#

    - by ddango
    We have a process that pulls images from a remote server. Most of the time, we're good to go, the images are valid, we don't timeout, etc. However, every once and awhile we see this error similar to this: Unhandled Exception: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderPa rameters encoderParams) at ConsoleApplication1.Program.Main(String[] args) in C:\images\ConsoleApplic ation1\ConsoleApplication1\Program.cs:line 24 After not being able to reproduce it locally, we looked closer at the image, and realized that there were artifacts, making us suspect corruption. Created an ugly little unit test with only the image in question, and was unable to reproduce the error on Windows 7 as was expected. But after running our unit test on Windows Server 2008, we see this error every time. Is there a way to specify non-strictness for jpegs when writing them? Some sort of check/fix we can use? Unit test snippet: var r = ReadFile("C:\\images\\ConsoleApplication1\\test.jpg"); using (var imgStream = new MemoryStream(r)) { using (var ms = new MemoryStream()) { var guid = Guid.NewGuid(); var fileName = "C:\\images\\ConsoleApplication1\\t" + guid + ".jpg"; Image.FromStream(imgStream).Save(ms, ImageFormat.Jpeg); using (FileStream fs = File.Create(fileName)) { fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); } } }

    Read the article

  • Haskell lazy I/O and closing files

    - by Jesse
    I've written a small Haskell program to print the MD5 checksums of all files in the current directory (searched recursively). Basically a Haskell version of md5deep. All is fine and dandy except if the current directory has a very large number of files, in which case I get an error like: <program>: <currentFile>: openBinaryFile: resource exhausted (Too many open files) It seems Haskell's laziness is causing it not to close files, even after its corresponding line of output has been completed. The relevant code is below. The function of interest is getList. import qualified Data.ByteString.Lazy as BS main :: IO () main = putStr . unlines =<< getList "." getList :: FilePath -> IO [String] getList p = let getFileLine path = liftM (\c -> (hex $ hash $ BS.unpack c) ++ " " ++ path) (BS.readFile path) in mapM getFileLine =<< getRecursiveContents p hex :: [Word8] -> String hex = concatMap (\x -> printf "%0.2x" (toInteger x)) getRecursiveContents :: FilePath -> IO [FilePath] -- ^ Just gets the paths to all the files in the given directory. Are there any ideas on how I could solve this problem? The entire program is available here: http://haskell.pastebin.com/PAZm0Dcb

    Read the article

  • Reverse reading WORD from a binary file?

    - by Angel
    Hi, I have a structure: struct JFIF_HEADER { WORD marker[2]; // = 0xFFD8FFE0 WORD length; // = 0x0010 BYTE signature[5]; // = "JFIF\0" BYTE versionhi; // = 1 BYTE versionlo; // = 1 BYTE xyunits; // = 0 WORD xdensity; // = 1 WORD ydensity; // = 1 BYTE thumbnwidth; // = 0 BYTE thumbnheight; // = 0 }; This is how I read it from the file: HANDLE file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); DWORD tmp = 0; DWORD size = GetFileSize(file, &tmp); BYTE *DATA = new BYTE[size]; ReadFile(file, DATA, size, &tmp, 0); JFIF_HEADER header; memcpy(&header, DATA, sizeof(JFIF_HEADER)); This is how the beginning of my file looks in hex editor: 0xFF 0xD8 0xFF 0xE0 0x00 0x10 0x4A 0x46 0x49 0x46 0x00 0x01 0x01 0x00 0x00 0x01 When I print header.marker, it shows exactly what it should (0xFFD8FFE0). But when I print header.length, it shows 0x1000 instead of 0x0010. The same thing is with xdensity and ydensity. Why do I get wrong data when reading a WORD? Thank you.

    Read the article

  • HTML5 audio with PHP script does not work on iPad/Iphone

    - by saulob
    Ok, I'm trying to play an HTML audio code on iPad but does not work. I created one PHP script to send to the MP3 request to the HTML5 audio code mp3_file_player.php?n=mp3file.mp3 The player is here: http://www.avault.com/news/podcast-news/john-romero-podcast-episode-80/ You will see that works on every HTML5 supported browser even on my iPod Touch. But does not work on iPad/iPhone, even on Safari on Mac OSX (I tried on Safari/Windows, worked fine) This is my PHP code: header("X-Powered-By: "); header("Accept-Ranges: bytes"); header("Content-Length: ". (string)(filesize($episode_filename)) .""); header("Content-type: audio/mpeg"); readfile($episode_filename); exit(); Everything works fine, the MP3 has the same headers like reading the mp3 directly. HTTP Headers from direct file access: (Status-Line) HTTP/1.1 200 OK Date Mon, 31 May 2010 20:27:31 GMT Server Apache/2.2.9 Last-Modified Wed, 26 May 2010 13:39:19 GMT Etag "dac0039-41d91f8-4877f669cefc0" Accept-Ranges bytes Content-Length 50656162 Content-Range bytes 18390614-69046775/69046776 Keep-Alive timeout=15, max=100 Connection Keep-Alive Content-Type audio/mpeg HTTP Header from my PHP script: (Status-Line) HTTP/1.1 200 OK Date Mon, 31 May 2010 20:27:08 GMT Server Apache/2.2.9 Accept-Ranges bytes Content-Length 69046776 Keep-Alive timeout=15, max=100 Connection Keep-Alive Content-Type audio/mpeg The only thing different it's the Content-Range, I even tried to add it, but if I use it the player will not work on my Ipod Touch. So I removed. Thank you very much.

    Read the article

  • Building a system that allows users to see a video only once

    - by Bart van Heukelom
    My client wants to distribute a video to some people, specifically car dealers, but he doesn't want the video to end up on Youtube or something like that. Therefore he wants the recipients of the video to be able to see it only once. My idea to implement this is: Generate a unique key per viewer Send each viewer a link to a page with a Flash based video player, with their key in the URL Have Flash get the video from the server. On the server the key is checked and the file sent (using php's readfile or something equivalent). Then the key is invalidated. I was thinking this wouldn't take more than a day to build. I know that if you want somebody to be able to play something, you implicitly give them the power to record it as well, but the client just wants me to make it as hard as possible. Do you think this is secure enough for the intended audience? Anything else I can do to add some security without exceeding the development time of 1 day? I'm also interested in ready made solutions, if they exist.

    Read the article

  • PHP Outputting File Attachments with Headers

    - by OneNerd
    After reading a few posts here I formulated this function which is sort of a mishmash of a bunch of others: function outputFile( $filePath, $fileName, $mimeType = '' ) { // Setup $mimeTypes = array( 'pdf' => 'application/pdf', 'txt' => 'text/plain', 'html' => 'text/html', 'exe' => 'application/octet-stream', 'zip' => 'application/zip', 'doc' => 'application/msword', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'gif' => 'image/gif', 'png' => 'image/png', 'jpeg' => 'image/jpg', 'jpg' => 'image/jpg', 'php' => 'text/plain' ); // Send Headers //-- next line fixed as per suggestion -- header('Content-Type: ' . $mimeTypes[$mimeType]); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); header('Cache-Control: private'); header('Pragma: private'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); readfile($filePath); } I have a php page (file.php) which does something like this (lots of other code stripped out): // I run this thru a safe function not shown here $safe_filename = $_GET['filename']; outputFile ( "/the/file/path/{$safe_filename}", $safe_filename, substr($safe_filename, -3) ); Seems like it should work, and it almost does, but I am having the following issues: When its a text file, I am getting a strange symbol as the first letter in the text document When its a word doc, it is corrupt (presumably that same first bit or byte throwing things off). I presume all other file types will be corrupt - have not even tried them Any ideas on what I am doing wrong? Thanks - UPDATE: changed line of code as suggested - still same issue.

    Read the article

  • Force download working, but showing invalid when trying to open locally.

    - by Cody Robertson
    Hi, I wrote this function and everything works well till i try to open the downloaded copy and it shows that the file is invalid. Here is my function function download_file() { //Check for download request: if(isset($_GET['file'])) { //Make sure there is a file before doing anything if(is_file($this->path . basename($_GET['file']))) { //Below required for IE: if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } //Set Headers: header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $this->path . basename($_GET['file'])) . ' GMT'); header('Content-Type: application/force-download'); header('Content-Disposition: inline; filename="' . basename($_GET['file']) . '"'); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($this->path . basename($_GET['file']))); header('Connection: close'); readfile($this->path . basename($_GET['file'])); exit(); } } }

    Read the article

< Previous Page | 2 3 4 5 6 7 8  | Next Page >