public static BlobKey KeyForBlobFromFile(FileInfo file) { MessageDigest md; try { md = MessageDigest.GetInstance("SHA-1"); } catch (NoSuchAlgorithmException) { Log.E(Database.Tag, "Error, SHA-1 digest is unavailable."); return(null); } byte[] sha1hash = new byte[40]; try { var fis = new FileInputStream(file); byte[] buffer = new byte[65536]; int lenRead = fis.Read(buffer); while (lenRead > 0) { md.Update(buffer, 0, lenRead); lenRead = fis.Read(buffer); } fis.Close(); } catch (IOException) { Log.E(Database.Tag, "Error readin tmp file to compute key"); } sha1hash = md.Digest(); BlobKey result = new BlobKey(sha1hash); return(result); }
/// <exception cref="System.IO.IOException"/> private static void CopyToZipStream(FilePath file, ZipEntry entry, ZipOutputStream zos) { InputStream @is = new FileInputStream(file); try { zos.PutNextEntry(entry); byte[] arr = new byte[4096]; int read = @is.Read(arr); while (read > -1) { zos.Write(arr, 0, read); read = @is.Read(arr); } } finally { try { @is.Close(); } finally { zos.CloseEntry(); } } }
/// <exception cref="System.IO.IOException"></exception> private void AssertFileContentsEqual(FilePath actFile, string @string) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); FileInputStream fis = null; byte[] buffer = new byte[100]; try { fis = new FileInputStream(actFile); int read = fis.Read(buffer); while (read > 0) { bos.Write(buffer, 0, read); read = fis.Read(buffer); } string content = Sharpen.Runtime.GetStringForBytes(bos.ToByteArray(), "UTF-8"); NUnit.Framework.Assert.AreEqual(@string, content); } finally { if (fis != null) { fis.Close(); } } }
// do nothing /// <summary>Read an entire local file into memory as a byte array.</summary> /// <remarks>Read an entire local file into memory as a byte array.</remarks> /// <param name="path">location of the file to read.</param> /// <param name="max"> /// maximum number of bytes to read, if the file is larger than /// this limit an IOException is thrown. /// </param> /// <returns>complete contents of the requested local file.</returns> /// <exception cref="System.IO.FileNotFoundException">the file does not exist.</exception> /// <exception cref="System.IO.IOException">the file exists, but its contents cannot be read. /// </exception> public static byte[] ReadFully(FilePath path, int max) { FileInputStream @in = new FileInputStream(path); try { long sz = Math.Max(path.Length(), 1); if (sz > max) { throw new IOException(MessageFormat.Format(JGitText.Get().fileIsTooLarge, path)); } byte[] buf = new byte[(int)sz]; int valid = 0; for (; ;) { if (buf.Length == valid) { if (buf.Length == max) { int next = @in.Read(); if (next < 0) { break; } throw new IOException(MessageFormat.Format(JGitText.Get().fileIsTooLarge, path)); } byte[] nb = new byte[Math.Min(buf.Length * 2, max)]; System.Array.Copy(buf, 0, nb, 0, valid); buf = nb; } int n = @in.Read(buf, valid, buf.Length - valid); if (n < 0) { break; } valid += n; } if (valid < buf.Length) { byte[] nb = new byte[valid]; System.Array.Copy(buf, 0, nb, 0, valid); buf = nb; } return(buf); } finally { try { @in.Close(); } catch (IOException) { } } }
/// <exception cref="System.IO.IOException"/> private static void CopyFileToStream(OutputStream @out, FilePath localfile, FileInputStream infile, DataTransferThrottler throttler, Canceler canceler) { byte[] buf = new byte[HdfsConstants.IoFileBufferSize]; try { CheckpointFaultInjector.GetInstance().AboutToSendFile(localfile); if (CheckpointFaultInjector.GetInstance().ShouldSendShortFile(localfile)) { // Test sending image shorter than localfile long len = localfile.Length(); buf = new byte[(int)Math.Min(len / 2, HdfsConstants.IoFileBufferSize)]; // This will read at most half of the image // and the rest of the image will be sent over the wire infile.Read(buf); } int num = 1; while (num > 0) { if (canceler != null && canceler.IsCancelled()) { throw new SaveNamespaceCancelledException(canceler.GetCancellationReason()); } num = infile.Read(buf); if (num <= 0) { break; } if (CheckpointFaultInjector.GetInstance().ShouldCorruptAByte(localfile)) { // Simulate a corrupted byte on the wire Log.Warn("SIMULATING A CORRUPT BYTE IN IMAGE TRANSFER!"); buf[0]++; } @out.Write(buf, 0, num); if (throttler != null) { throttler.Throttle(num, canceler); } } } catch (EofException) { Log.Info("Connection closed by client"); @out = null; } finally { // so we don't close in the finally if (@out != null) { @out.Close(); } } }
/// <exception cref="System.IO.IOException"/> public override int Read() { int result = -1; if (bytesRemaining > 0) { bytesRemaining -= 1; result = file.Read(); } return(result); }
/// <summary> /// Read a file with given path and return a byte-array with it's entire contents. /// </summary> public static byte[] ReadAllBytes(string path) { if (path == null) { throw new ArgumentNullException("path"); } var file = new JFile(path); if (!file.Exists() || !file.IsFile()) { throw new FileNotFoundException(path); } if (!file.CanRead()) { throw new UnauthorizedAccessException(path); } var stream = new FileInputStream(file); try { var array = new byte[file.Length()]; stream.Read(array, 0, array.Length); return(array); } finally { stream.Close(); } }
public static void ProcessBytes(string encodedPath, string fileName) { var strByte = 0; using (var encodedFile = new File(encodedPath)) { try { using (var finStream = new FileInputStream(encodedFile)) { var buffer = new byte[finStream.Available()]; finStream.Read(buffer, 0, finStream.Available()); for (var i = 0; i < buffer.Length; i++) { buffer[i] ^= (byte)Mask[strByte]; Mask[strByte] += 0x10; if (strByte < 15) { strByte++; } else { strByte = 0; } } using (var writer = new FileOutputStream(DataHolder.CachePath + $"/{fileName}.mp3")) writer.Write(buffer); } } catch (IOException e) { Console.WriteLine(e); } } }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode != Result.Ok) { return; } if (requestCode == PICK_IMAGE) { GoOnTapApplication.Config.IconSetUri = data.Data; // Read icon set ParcelFileDescriptor parcelFileDescriptor = ContentResolver.OpenFileDescriptor(data.Data, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.FileDescriptor; FileInputStream fileInputStream = new FileInputStream(fileDescriptor); MemoryStream memoryStream = new MemoryStream(); byte[] buffer = new byte[1024]; int count; while ((count = fileInputStream.Read(buffer, 0, buffer.Length)) > 0) { memoryStream.Write(buffer, 0, count); } fileInputStream.Close(); parcelFileDescriptor.Close(); GoOnTapApplication.Config.IconSetBytes = memoryStream.ToArray(); } }
/// <exception cref="System.IO.IOException"></exception> private static byte[] GetBytesFromFile(FilePath file) { InputStream @is = new FileInputStream(file); // Get the size of the file long length = file.Length(); // Create the byte array to hold the data byte[] bytes = new byte[(int)length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.Length && (numRead = @is.Read(bytes, offset, bytes.Length - offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.Length) { throw new IOException("Could not completely read file " + file.GetName()); } // Close the input stream and return bytes @is.Close(); return(bytes); }
public byte[] GetBytesFromFile(Java.IO.File f) { if (f == null) { return(null); } try { FileInputStream stream = new FileInputStream(f); Java.IO.ByteArrayOutputStream outs = new ByteArrayOutputStream(1000); //ByteArrayOutputStream out = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = stream.Read(b)) != -1) { outs.Write(b, 0, n); } stream.Close(); outs.Close(); return(outs.ToByteArray()); } catch (System.IO.IOException e) { } return(null); }
public static byte[] ReadFile(File file) { try { var input = new FileInputStream(file); var output = new ByteArrayOutputStream(); var buffer = new byte['Ѐ']; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } input.Close(); output.Close(); return(output.ToByteArray()); } catch (Exception e) { Log.Debug("Offliine", e.Message); } return(null); }
private void CopyWaveFile(string tempFile, string permanentFile) { long sampleRate = _recorderSamplerate; const int channels = 2; long byteRate = RecorderBpp * _recorderSamplerate * channels / 8; var data = new byte[_bufferSize]; try { var inputStream = new FileInputStream(tempFile); var outputStream = new FileOutputStream(permanentFile); var totalAudioLength = inputStream.Channel.Size(); var totalDataLength = totalAudioLength + 36; Debug.WriteLine("File size: " + totalDataLength); WriteWaveFileHeader(outputStream, totalAudioLength, totalDataLength, sampleRate, channels, byteRate); while (inputStream.Read(data) != -1) { outputStream.Write(data); } inputStream.Close(); outputStream.Close(); DeleteTempFile(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
/// <exception cref="System.IO.FileNotFoundException"/> /// <exception cref="System.IO.IOException"/> private void CreateAndAddJarToJar(JarOutputStream jos, FilePath jarFile) { FileOutputStream fos2 = new FileOutputStream(jarFile); JarOutputStream jos2 = new JarOutputStream(fos2); // Have to have at least one entry or it will complain ZipEntry ze = new ZipEntry("lib1.inside"); jos2.PutNextEntry(ze); jos2.CloseEntry(); jos2.Close(); ze = new ZipEntry("lib/" + jarFile.GetName()); jos.PutNextEntry(ze); FileInputStream @in = new FileInputStream(jarFile); byte[] buf = new byte[1024]; int numRead; do { numRead = @in.Read(buf); if (numRead >= 0) { jos.Write(buf, 0, numRead); } }while (numRead != -1); @in.Close(); jos.CloseEntry(); jarFile.Delete(); }
public override void OnWrite(PageRange[] pages, Android.OS.ParcelFileDescriptor destination, Android.OS.CancellationSignal cancellationSignal, WriteResultCallback callback) { InputStream input = null; OutputStream output = null; try { input = new FileInputStream(_filePath); output = new FileOutputStream(destination.FileDescriptor); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.Read(buf)) > 0) { output.Write(buf, 0, bytesRead); } callback.OnWriteFinished(new PageRange[] { PageRange.AllPages }); } catch (FileNotFoundException ee) { //Catch exception } catch (Exception e) { //Catch exception } finally { try { input.Close(); output.Close(); } catch (IOException e) { e.PrintStackTrace(); } } }
public static sbyte[] ReadBytes([NotNull] FilePath file) { int length = (int)file.Length(); // should only be zero if loading from a network or similar System.Diagnostics.Debug.Assert((length != 0)); sbyte[] bytes = new sbyte[length]; int totalBytesRead = 0; FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); while (totalBytesRead != length) { int bytesRead = inputStream.Read(bytes, totalBytesRead, length - totalBytesRead); if (bytesRead == -1) { break; } totalBytesRead += bytesRead; } } finally { if (inputStream != null) { inputStream.Close(); } } return(bytes); }
/** * Helps identify the source file */ private static String GetFileMD5(File f) { MessageDigest m; try { m = MessageDigest.GetInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } byte[] buf = new byte[2048]; try { InputStream is1 = new FileInputStream(f); while (true) { int bytesRead = is1.Read(buf); if (bytesRead < 1) { break; } m.update(buf, 0, bytesRead); } is1.Close(); } catch (IOException e) { throw new RuntimeException(e); } return("0x" + new Bigint(1, m.digest()).ToString(16)); }
/// <exception cref="System.Exception"/> public virtual void TestSymlink() { NUnit.Framework.Assert.IsFalse(del.Exists()); del.Mkdirs(); byte[] data = Runtime.GetBytesForString("testSymLink"); FilePath file = new FilePath(del, File); FilePath link = new FilePath(del, "_link"); //write some data to the file FileOutputStream os = new FileOutputStream(file); os.Write(data); os.Close(); //create the symlink FileUtil.SymLink(file.GetAbsolutePath(), link.GetAbsolutePath()); //ensure that symlink length is correctly reported by Java Assert.Equal(data.Length, file.Length()); Assert.Equal(data.Length, link.Length()); //ensure that we can read from link. FileInputStream @in = new FileInputStream(link); long len = 0; while (@in.Read() > 0) { len++; } @in.Close(); Assert.Equal(data.Length, len); }
public string DecriptFile(string filename, string name) { Java.IO.File extStore = Android.OS.Environment.GetExternalStoragePublicDirectory("Temp"); Android.Util.Log.Error("Decryption Started", extStore + ""); FileInputStream fis = new FileInputStream(extStore + "/" + filename); // createFile(filename, extStore); FileOutputStream fos = new FileOutputStream(extStore + "/" + "decrypted" + filename, false); System.IO.FileStream fs = System.IO.File.OpenWrite(extStore + "/" + name); Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding"); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(CipherMode.DecryptMode, skeySpec, iv); CipherOutputStream cos = new CipherOutputStream(fs, cipher); int b; byte[] d = new byte[1024 * 1024]; while ((b = fis.Read(d)) != -1) { cos.Write(d, 0, b); } System.IO.File.Delete(extStore + "/" + "decrypted" + filename); Android.Util.Log.Error("Decryption Ended", extStore + "/" + "decrypted" + name); return(extStore.ToString()); //return d; }
/// <exception cref="System.IO.IOException"></exception> public override void WriteTo(OutputStream os, ProgressMonitor pm) { if (onDiskFile == null) { base.WriteTo(os, pm); return; } if (pm == null) { pm = NullProgressMonitor.INSTANCE; } FileInputStream @in = new FileInputStream(onDiskFile); try { int cnt; byte[] buf = new byte[TemporaryBuffer.Block.SZ]; while ((cnt = @in.Read(buf)) >= 0) { os.Write(buf, 0, cnt); pm.Update(cnt / 1024); } } finally { @in.Close(); } }
public override void OnWrite (PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, Android.Print.PrintDocumentAdapter.WriteResultCallback callback) { InputStream input = null; OutputStream output = null; try { input = new FileInputStream (PathToDoc); output = new FileOutputStream (destination.FileDescriptor); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.Read (buf)) > 0) { output.Write (buf, 0, bytesRead); } callback.OnWriteFinished (new PageRange[]{ PageRange.AllPages }); } catch (System.IO.FileNotFoundException ee) { Insights.Report (ee); } catch (Exception e) { Insights.Report (e); } finally { try { input.Close (); output.Close (); } catch (Java.IO.IOException e) { e.PrintStackTrace (); } } }
void CopyWaveFile(string tempFile, string permanentFile) { FileInputStream inputStream = null; FileOutputStream outputStream = null; long totalAudioLength = 0; long totalDataLength = totalAudioLength + 36; long sampleRate = RECORDER_SAMPLERATE; int channels = 2; long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8; byte[] data = new byte[bufferSize]; try { inputStream = new FileInputStream(tempFile); outputStream = new FileOutputStream(permanentFile); totalAudioLength = inputStream.Channel.Size(); totalDataLength = totalAudioLength + 36; Debug.WriteLine("File size: " + totalDataLength); WriteWaveFileHeader(outputStream, totalAudioLength, totalDataLength, sampleRate, channels, byteRate); while (inputStream.Read(data) != -1) { outputStream.Write(data); } inputStream.Close(); outputStream.Close(); DeleteTempFile(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private byte[] ConvertUriToByteArray(Android.Net.Uri data, string name) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileInputStream fis; try { fis = new FileInputStream(new File(GetPath(data))); byte[] buf = new byte[1024]; int n; while (-1 != (n = fis.Read(buf))) { baos.Write(buf, 0, n); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Error in convert Byte Array" + e.ToString()); return(null); } byte[] bbytes = baos.ToByteArray(); return(bbytes); }
/// <exception cref="System.IO.IOException"></exception> protected internal static void CopyFile(FilePath src, FilePath dst) { FileInputStream fis = new FileInputStream(src); try { FileOutputStream fos = new FileOutputStream(dst); try { byte[] buf = new byte[4096]; int r; while ((r = fis.Read(buf)) > 0) { fos.Write(buf, 0, r); } } finally { fos.Close(); } } finally { fis.Close(); } }
public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) { try { using (InputStream input = new FileInputStream(path)) { using (OutputStream output = new FileOutputStream(destination.FileDescriptor)) { var buf = new byte[1024]; int bytesRead; while ((bytesRead = input.Read(buf)) > 0) { output.Write(buf, 0, bytesRead); } } } callback.OnWriteFinished(new[] { PageRange.AllPages }); } catch (FileNotFoundException fileNotFoundException) { System.Diagnostics.Debug.WriteLine(fileNotFoundException); } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception); } }
private void CopyWaveFile(string tempFile, string permanentFile) { long longSampleRate = _deviceService.AudioSampleRate; var channels = 2; long byteRate = RecorderBpp * longSampleRate * channels / 8; byte[] data = new byte[_bufferSize]; try { var input = new FileInputStream(tempFile); var output = new FileOutputStream(permanentFile); var totalAudioLen = input.Channel.Size(); var totalDataLen = totalAudioLen + 36; System.Diagnostics.Debug.WriteLine($"File Size: {totalDataLen}"); WriteWaveFileHeader(output, totalAudioLen, totalDataLen, longSampleRate, channels, byteRate); while (input.Read(data) != -1) { output.Write(data); } input.Close(); output.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
void CopyWaveFile(string tempFile, string permanentFile) { FileInputStream inputStream = null; FileOutputStream outputStream = null; long totalAudioLength = 0; long totalDataLength = totalAudioLength + 36; int channels = 2; long byteRate = _recorderBpp * recorderSampleRate * channels / 8; byte[] data = new byte[bufferSize]; try { inputStream = new FileInputStream(tempFile); outputStream = new FileOutputStream(permanentFile); totalAudioLength = inputStream.Channel.Size(); totalDataLength = totalAudioLength + 36; WriteWaveFileHeader(outputStream, totalAudioLength, totalDataLength, recorderSampleRate, channels, byteRate); while (inputStream.Read(data) != -1) { outputStream.Write(data); } inputStream.Close(); outputStream.Close(); DeleteTempFile(); } catch (Exception ex) { //Debug.WriteLine(ex.Message); } }
public void copy() { string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Notes3.db-wal"); // string path1 = "/data/user/0/com.companyname.Notes/files/Notes3.db"; File f = new File(path); // var fileex=f.Exists(); FileInputStream fis = null; FileOutputStream fos = null; fis = new FileInputStream(f); fos = new FileOutputStream("/mnt/sdcard/db_dump.db"); while (true) { int i = fis.Read(); if (i != -1) { fos.Write(i); } else { break; } } fos.Flush(); Toast.MakeText(Android.App.Application.Context, "DB dump OK", ToastLength.Short).Show(); fos.Close(); fis.Close(); }
void CopyWaveFile(string sourcePath, string destinationPath) { FileInputStream inputStream = null; FileOutputStream outputStream = null; long totalAudioLength = 0; long totalDataLength = totalAudioLength + 36; int channels = 2; long byteRate = 16 * sampleRate * channels / 8; var data = new byte[bufferSize]; try { inputStream = new FileInputStream(sourcePath); outputStream = new FileOutputStream(destinationPath); totalAudioLength = inputStream.Channel.Size(); totalDataLength = totalAudioLength + 36; WriteWaveFileHeader(outputStream, totalAudioLength, totalDataLength, sampleRate, channels, byteRate); while (inputStream.Read(data) != -1) { outputStream.Write(data); } inputStream.Close(); outputStream.Close(); } catch (Exception ex) { } }
public ActionResult Create([Bind(Include = "nombre,genero,duracion,director,sinopsis,lanzamiento,categoria,imagen")] pelicula pelicula) { if (isSession()) { if (ModelState.IsValid) { /*string theFileName = Path.GetFileName(pelicula.img.FileName); * byte[] thePictureAsBytes = new byte[pelicula.img.ContentLength]; * using (BinaryReader theReader = new BinaryReader(pelicula.img.InputStream)) * { * thePictureAsBytes = theReader.ReadBytes(pelicula.img.ContentLength); * } * string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes); * Console.Write("PRUEBA DAMIAN " + thePictureDataAsString); * pelicula.imagen = thePictureDataAsString;*/ using (var context = new cineDBEntities()) { HttpPostedFileBase file = Request.Files[0]; InputStream finput = new FileInputStream(file.InputStream); byte[] imageBytes = new byte[(int)file.InputStream.Length]; finput.Read(imageBytes, 0, imageBytes.Length); finput.Close(); String imageStr = Base64.ToBase64String(imageBytes); var std = new pelicula() { nombre = pelicula.nombre, genero = pelicula.genero, duracion = pelicula.duracion, director = pelicula.director, sinopsis = pelicula.sinopsis, lanzamiento = pelicula.lanzamiento, categoria = pelicula.categoria, imagen = imageStr }; context.peliculas.Add(std); try { context.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { foreach (var entityValidationErrors in ex.EntityValidationErrors) { foreach (var validationError in entityValidationErrors.ValidationErrors) { System.Diagnostics.Debug.WriteLine("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage); } } } } return(RedirectToAction("Index")); } return(View(pelicula)); } else { return(RedirectToAction("Login", "Login")); } }
private byte[] getByteArrayFromImage(String filePath) { byte[] bytes = null; try { Java.IO.File file = new Java.IO.File(filePath); FileInputStream fis = new FileInputStream(file); //create FileInputStream which obtains input bytes from a file in a file system //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; for (int readNum; (readNum = fis.Read(buf)) != -1;) { bos.Write(buf, 0, readNum); //no doubt here is 0 /*Writes len bytes from the specified byte array starting at offset * off to this byte array output stream.*/ } bytes = bos.ToByteArray(); } catch { return(bytes); } return(bytes); }
public String Read(File file) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); InputStream source = new FileInputStream(file); byte[] chunk = new byte[1024]; int count = 0; while((count = source.Read(chunk)) != -1) { buffer.write(chunk, 0, count); } return buffer.toString("UTF-8"); }
/// <summary> /// Read a file with given path and return a byte-array with it's entire contents. /// </summary> public static byte[] ReadAllBytes(string path) { if (path == null) throw new ArgumentNullException("path"); var file = new JFile(path); if (!file.Exists() || !file.IsFile()) throw new FileNotFoundException(path); if (!file.CanRead()) throw new UnauthorizedAccessException(path); var stream = new FileInputStream(file); try { var array = new byte[file.Length()]; stream.Read(array, 0, array.Length); return array; } finally { stream.Close(); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate (bundle); // Create your application here SetContentView(Resource.Layout.History); listView = FindViewById<ListView>(Resource.Id.listView1); db = new MoodDatabase(this); Button BackHome = FindViewById<Button> (Resource.Id.button1); BackHome.Click += delegate { //create an intent to go to the next screen Intent intent = new Intent(this, typeof(Home)); intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen StartActivity(intent); }; Button DeleteButton = FindViewById<Button> (Resource.Id.button2); DeleteButton.Click += delegate { //create an intent to go to the next screen db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData"); db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql); //restart this activity in order to update the view Intent intent = new Intent(this, typeof(History)); intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen StartActivity(intent); }; //query database and link to the listview cursor = db.ReadableDatabase.RawQuery("SELECT * FROM MoodData ORDER BY _id DESC", null); // cursor query //why this command is deprecated and what should be used instead: http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html //http://www.vogella.com/tutorials/AndroidSQLite/article.html //http://www.codeproject.com/Articles/792883/Using-Sqlite-in-a-Xamarin-Android-Application-Deve StartManagingCursor(cursor); // which columns map to which layout controls //string[] fromColumns = new string[] {"date", "time", "mood", "people", "what", "location"}; string[] fromColumns = new string[] {"date", "mood"}; int[] toControlIDs = new int[] {Android.Resource.Id.Text1, Android.Resource.Id.Text2}; // use a SimpleCursorAdapter, could use our own Layout for the view: https://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/ listView.Adapter = new SimpleCursorAdapter (this, Android.Resource.Layout.SimpleListItem2, cursor, fromColumns, toControlIDs); listView.ItemClick += OnListItemClick; //EXPORT BUTTON TO WRITE SQLITE DB FILE TO SD CARD Button ExportButton = FindViewById<Button> (Resource.Id.button3); ExportButton.Click += delegate { File sd = GetExternalFilesDir(null); File backupDB = new File(sd, "MoodData.db"); //this is where we're going to export to //this is the database file File data = GetDatabasePath("MoodData.db"); //Android.Widget.Toast.MakeText(this, data.AbsolutePath, Android.Widget.ToastLength.Short).Show(); OutputStream OS = new FileOutputStream(backupDB); InputStream IS = new FileInputStream(data); //the actual copying action byte[] dataByte = new byte[IS.Available()]; IS.Read(dataByte); OS.Write(dataByte); IS.Close(); OS.Close(); //http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29 //http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/ }; }
/** * Helps identify the source file */ private static String GetFileMD5(File f) { MessageDigest m; try { m = MessageDigest.GetInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } byte[] buf = new byte[2048]; try { InputStream is1 = new FileInputStream(f); while (true) { int bytesRead = is1.Read(buf); if (bytesRead < 1) { break; } m.update(buf, 0, bytesRead); } is1.Close(); } catch (IOException e) { throw new RuntimeException(e); } return "0x" + new Bigint(1, m.digest()).ToString(16); }
protected override void OnCreate(Bundle bundle) { base.OnCreate (bundle); // Create your application here SetContentView(Resource.Layout.History); db = new MoodDatabase(this); Button MoodTime = FindViewById<Button> (Resource.Id.buttonMoodTime); MoodTime.Click += delegate { //create an intent to go to the next screen Intent intent = new Intent(this, typeof(MoodTime)); StartActivity(intent); }; Button MoodPeople = FindViewById<Button> (Resource.Id.buttonMoodPeople); MoodPeople.Click += delegate { //create an intent to go to the next screen Intent intent = new Intent(this, typeof(MoodPeople)); StartActivity(intent); }; Button ExDB = FindViewById<Button> (Resource.Id.buttonExDB); ExDB.Click += delegate { //delete current DB and fill it with an example dataset db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData"); db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql); //we want histograms that show bad mood when you are alone and good mood when you are with people db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '07:30', 3, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '09:30', 3, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '11:30', 7, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '16:30', 1, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '20:30', 6, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '07:30', 3, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '09:30', 2, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '11:30', 7, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '16:30', 1, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '20:30', 6, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '09:30', 2, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '11:30', 7, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '13:30', 1, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '16:30', 8, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '18:30', 3, 0, 1, 1, 1023)"); //Feedback message Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short); toast.SetGravity (GravityFlags.Center, 0, 0); toast.Show (); }; Button BackHome = FindViewById<Button> (Resource.Id.button1); BackHome.Click += delegate { //create an intent to go to the next screen Intent intent = new Intent(this, typeof(Home)); intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen StartActivity(intent); }; Button DeleteButton = FindViewById<Button> (Resource.Id.button2); DeleteButton.Click += delegate { //create an intent to go to the next screen db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData"); db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql); //Feedback message Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short); toast.SetGravity (GravityFlags.Center, 0, 0); toast.Show (); //restart this activity in order to update the view Intent intent = new Intent(this, typeof(History)); intent.SetFlags(ActivityFlags.ClearTop); //remove the history StartActivity(intent); }; //EXPORT BUTTON TO WRITE SQLITE DB FILE TO SD CARD Button ExportButton = FindViewById<Button> (Resource.Id.button3); ExportButton.Click += delegate { //This is for exporting the db file File sd = GetExternalFilesDir(null); File backupDB = new File(sd, "MoodData.db"); //this is where we're going to export to //this is the database file File data = GetDatabasePath("MoodData.db"); //Android.Widget.Toast.MakeText(this, data.AbsolutePath, Android.Widget.ToastLength.Short).Show(); OutputStream OS = new FileOutputStream(backupDB); InputStream IS = new FileInputStream(data); //the actual copying action byte[] dataByte = new byte[IS.Available()]; IS.Read(dataByte); OS.Write(dataByte); IS.Close(); OS.Close(); //Now try to export everything as a csv file Android.Database.ICursor cursor; cursor = db.ReadableDatabase.RawQuery("SELECT * FROM MoodData ORDER BY _id DESC", null); // cursor query //only write a file if there are entries in the DB if (cursor.Count > 0) { backupDB = new File(sd, "MoodData.csv"); //this is where we're going to export to OS = new FileOutputStream(backupDB); //write a header in the beginning string header = "date; time; mood; people; what; location; pos1; pos2; pos3; pos4; pos5; neg1; neg2; neg3; neg4; neg5\n"; byte[] bytes = new byte[header.Length * sizeof(char)]; System.Buffer.BlockCopy(header.ToCharArray(), 0, bytes, 0, bytes.Length); OS.Write(bytes); for (int ii = 0; ii < cursor.Count; ii++) { //go through all rows cursor.MoveToPosition (ii); //now go through all columns for (int kk = 1; kk < cursor.ColumnCount-1; kk++) { //skip the first column since it is just the ID and the last since it's the question flags //[date] TEXT NOT NULL, [time] TEXT NOT NULL, [mood] INT NOT NULL, [people] INT NOT NULL, [what] INT NOT NULL, [location] INT NOT NULL, [pos1] INT, [pos2] INT , [pos3] INT, [pos4] INT, [pos5] INT, [neg1] INT, [neg2] INT , [neg3] INT, [neg4] INT, [neg5] INT, [QuestionFlags] INT NOT NULL)"; //the first two columns are strings, the rest is int string tempStr; if (kk < 3) { tempStr = cursor.GetString(kk); } else { int tempInt = cursor.GetInt(kk); tempStr = tempInt.ToString(); } if (kk == cursor.ColumnCount-2) //if last column, advance to next line tempStr += "\n"; else tempStr += "; "; //convert to byte and write bytes = new byte[tempStr.Length * sizeof(char)]; System.Buffer.BlockCopy(tempStr.ToCharArray(), 0, bytes, 0, bytes.Length); OS.Write(bytes); } } OS.Close(); //Encrypt File var zipTemp = new ZIPHelper(); zipTemp.Save(sd.AbsolutePath); System.Console.WriteLine("Path: " + sd.AbsolutePath ); //send via email var email = new Intent(Intent.ActionSend); email.SetType("text/plain"); //email.PutExtra(Android.Content.Intent.ExtraEmail, new string[]{"*****@*****.**"}); email.PutExtra(Android.Content.Intent.ExtraSubject, "R-U-OK Export"); email.PutExtra(Android.Content.Intent.ExtraText, "Beschreibung der Datenbank Einträge :\n[mood] Stimmung 0-8, -1 wenn die Erinnerung verpasst wurde\n[people] keiner-viele, 0-2 \n[what] Freizeit-Arbeit, 0-2 \n[location] Unterwegs/Daheim, 0-1 \n[pos1-5] und [neg1-5] sind die Affekt Fragen, bewertet zwischen 1-9. Einträge mit 0 sind nicht gefragt worden. Die Frage sind folgende:\nPos1: Wie fröhlich fühlen Sie sich?\nPos2: Wie optimistisch sind Sie?\nPos3: Wie zufrieden sind Sie?\nPos4: Wie entspannt sind Sie?\nPos5: 5te Frage fehlt noch\nNeg1: Wie traurig sind Sie?\nNeg2: Wie ängstlich sind Sie?\nNeg3: Wie einsam sind Sie?\nNeg4: Wie unruhig sind Sie?\nNeg5: Wie ärgerlich sind Sie?\n" ); //email.PutExtra(Android.Content.Intent.ExtraStream, Android.Net.Uri.Parse("file://" + backupDB.AbsolutePath)); email.PutExtra(Android.Content.Intent.ExtraStream, Android.Net.Uri.Parse("file://" + sd.AbsolutePath + "//MoodData.zip")); //System.Console.WriteLine(backupDB.AbsolutePath); StartActivity(Intent.CreateChooser(email, "Send email...")); } //Feedback message Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short); toast.SetGravity (GravityFlags.Center, 0, 0); toast.Show (); //http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29 //http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/ }; }