/// <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 = @in.GetChannel().Size(); if (sz > max) { throw new IOException(MessageFormat.Format(JGitText.Get().fileIsTooLarge, path)); } byte[] buf = new byte[(int)sz]; IOUtil.ReadFully(@in, buf, 0, buf.Length); return(buf); } finally { try { @in.Close(); } catch (IOException) { } } }
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); }
/// <summary>This loads a model batch from a file, then closes the file handler.</summary> /// <remarks>This loads a model batch from a file, then closes the file handler. Just a convenience.</remarks> /// <param name="filename">the file to load from</param> /// <param name="featurizer"> /// a function that gets run on every GraphicalModel, and has a chance to edit them (eg by adding /// or changing features) /// </param> /// <exception cref="System.IO.IOException"/> public ModelBatch(string filename, IConsumer <GraphicalModel> featurizer) { InputStream @is = new FileInputStream(filename); ReadFrom(@is, featurizer); @is.Close(); }
/// <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 static bool CopyFile(File sourceFile, File destFile) { if (!destFile.Exists()) { destFile.CreateNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).Channel; destination = new FileOutputStream(destFile).Channel; destination.TransferFrom(source, 0, source.Size()); } catch (Exception e) { //FileLog.e("tmessages", e); return(false); } finally { if (source != null) { source.Close(); } if (destination != null) { destination.Close(); } } return(false); }
/// <exception cref="System.IO.IOException"></exception> public static void CopyFile(FilePath sourceFile, FilePath destFile) { if (!destFile.Exists()) { destFile.CreateNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).GetChannel(); destination = new FileOutputStream(destFile).GetChannel(); destination.TransferFrom(source, 0, source.Size()); } finally { if (source != null) { source.Close(); } if (destination != null) { destination.Close(); } } }
/// <summary> /// Return the length of bytes in the given file after subtracting /// the trailer of 0xFF (OP_INVALID)s. /// </summary> /// <remarks> /// Return the length of bytes in the given file after subtracting /// the trailer of 0xFF (OP_INVALID)s. /// This seeks to the end of the file and reads chunks backwards until /// it finds a non-0xFF byte. /// </remarks> /// <exception cref="System.IO.IOException">if the file cannot be read</exception> private static long GetNonTrailerLength(FilePath f) { int chunkSizeToRead = 256 * 1024; FileInputStream fis = new FileInputStream(f); try { byte[] buf = new byte[chunkSizeToRead]; FileChannel fc = fis.GetChannel(); long size = fc.Size(); long pos = size - (size % chunkSizeToRead); while (pos >= 0) { fc.Position(pos); int readLen = (int)Math.Min(size - pos, chunkSizeToRead); IOUtils.ReadFully(fis, buf, 0, readLen); for (int i = readLen - 1; i >= 0; i--) { if (buf[i] != FSEditLogOpCodes.OpInvalid.GetOpCode()) { return(pos + i + 1); } } // + 1 since we count this byte! pos -= chunkSizeToRead; } return(0); } finally { fis.Close(); } }
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.Exception"/> public static void Main(string[] args) { Properties props = StringUtils.ArgsToProperties(args); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); string file = props.GetProperty("file"); string loadFile = props.GetProperty("loadFile"); if (loadFile != null && !loadFile.IsEmpty()) { Edu.Stanford.Nlp.Pipeline.CustomAnnotationSerializer ser = new Edu.Stanford.Nlp.Pipeline.CustomAnnotationSerializer(false, false); InputStream @is = new FileInputStream(loadFile); Pair <Annotation, InputStream> pair = ser.Read(@is); pair.second.Close(); Annotation anno = pair.first; System.Console.Out.WriteLine(anno.ToShorterString(StringUtils.EmptyStringArray)); @is.Close(); } else { if (file != null && !file.Equals(string.Empty)) { string text = IOUtils.SlurpFile(file); Annotation doc = new Annotation(text); pipeline.Annotate(doc); Edu.Stanford.Nlp.Pipeline.CustomAnnotationSerializer ser = new Edu.Stanford.Nlp.Pipeline.CustomAnnotationSerializer(false, false); TextWriter os = new TextWriter(new FileOutputStream(file + ".ser")); ser.Write(doc, os).Close(); log.Info("Serialized annotation saved in " + file + ".ser"); } else { log.Info("usage: CustomAnnotationSerializer [-file file] [-loadFile file]"); } } }
/// <exception cref="System.IO.IOException"></exception> public override byte[] ToByteArray() { if (onDiskFile == null) { return(base.ToByteArray()); } long len = Length(); if (int.MaxValue < len) { throw new OutOfMemoryException(JGitText.Get().lengthExceedsMaximumArraySize); } byte[] @out = new byte[(int)len]; FileInputStream @in = new FileInputStream(onDiskFile); try { IOUtil.ReadFully(@in, @out, 0, (int)len); } finally { @in.Close(); } return(@out); }
/** * 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)); }
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); } }
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.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); }
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); } }
public virtual void Test1() { FilePath packFile = JGitTestUtil.GetTestResourceFile("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack" ); InputStream @is = new FileInputStream(packFile); try { IndexPack pack = new IndexPack(db, @is, new FilePath(trash, "tmp_pack1")); pack.Index(new TextProgressMonitor()); PackFile file = new PackFile(new FilePath(trash, "tmp_pack1.idx"), new FilePath(trash , "tmp_pack1.pack")); NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904" ))); NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("540a36d136cf413e4b064c2b0e0a4db60f77feab" ))); NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259" ))); NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3" ))); NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("82c6b885ff600be425b4ea96dee75dca255b69e7" ))); NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("902d5476fa249b7abc9d84c611577a81381f0327" ))); NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("aabf2ffaec9b497f0950352b3e582d73035c2035" ))); NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("c59759f143fb1fe21c197981df75a7ee00290799" ))); } finally { @is.Close(); } }
/// <exception cref="System.IO.IOException"/> /// <exception cref="GeneralSecurityException"/> internal X509TrustManager LoadTrustManager() { X509TrustManager trustManager = null; KeyStore ks = KeyStore.GetInstance(type); lastLoaded = file.LastModified(); FileInputStream @in = new FileInputStream(file); try { ks.Load(@in, password.ToCharArray()); Log.Debug("Loaded truststore '" + file + "'"); } finally { @in.Close(); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.GetInstance(SSLFactory .Sslcertificate); trustManagerFactory.Init(ks); TrustManager[] trustManagers = trustManagerFactory.GetTrustManagers(); foreach (TrustManager trustManager1 in trustManagers) { if (trustManager1 is X509TrustManager) { trustManager = (X509TrustManager)trustManager1; break; } } return(trustManager); }
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 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); }
/// <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(); } }
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 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); }
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(); }
private async Task <OperationResult <MediaModel> > UploadPhoto(string path) { System.IO.Stream stream = null; FileInputStream fileInputStream = null; try { var photo = new Java.IO.File(path); fileInputStream = new FileInputStream(photo); stream = new StreamConverter(fileInputStream, null); var request = new UploadMediaModel(AppSettings.User.UserInfo, stream, System.IO.Path.GetExtension(path)); var serverResult = await Presenter.TryUploadMedia(request); return(serverResult); } catch (Exception ex) { AppSettings.Reporter.SendCrash(ex); return(new OperationResult <MediaModel>(new AppError(LocalizationKeys.PhotoProcessingError))); } finally { fileInputStream?.Close(); // ??? change order? stream?.Flush(); fileInputStream?.Dispose(); stream?.Dispose(); } }
/// <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(); } } }
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 void ExportDatabaseToSdCard() { Log.D(this, "Exporting database"); try { var backup = new Java.IO.File(context.GetExternalFilesDir("").AbsolutePath, "ION_External.database"); var original = new Java.IO.File(database.path); Log.D(this, "Backup: " + backup.AbsolutePath); if (original.Exists()) { var fis = new FileInputStream(original); var fos = new FileOutputStream(backup); Log.D(this, "Transfered: " + fos.Channel.TransferFrom(fis.Channel, 0, fis.Channel.Size()) + " bytes"); fis.Close(); fos.Flush(); fos.Close(); Log.D(this, "Successfully exported the database to the sd card."); } } catch (Exception e) { Log.E(this, "Failed to export database to SD card", e); } }
private IDictionary <string, OpenSshConfig.Host> Refresh() { lock (this) { long mtime = configFile.LastModified(); if (mtime != lastModified) { try { FileInputStream @in = new FileInputStream(configFile); try { hosts = Parse(@in); } finally { @in.Close(); } } catch (FileNotFoundException) { hosts = Sharpen.Collections.EmptyMap <string, OpenSshConfig.Host>(); } catch (IOException) { hosts = Sharpen.Collections.EmptyMap <string, OpenSshConfig.Host>(); } lastModified = mtime; } return(hosts); } }
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); } }
/// <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(); } }
/// <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); }
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 (); } } }
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/ }; }