Пример #1
0
        /// <summary>Reverts the worktree after an unsuccessful merge.</summary>
        /// <remarks>
        /// Reverts the worktree after an unsuccessful merge. We know that for all
        /// modified files the old content was in the old index and the index
        /// contained only stage 0. In case if inCore operation just clear
        /// the history of modified files.
        /// </remarks>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        /// <exception cref="NGit.Errors.CorruptObjectException">NGit.Errors.CorruptObjectException
        ///     </exception>
        /// <exception cref="NGit.Errors.NoWorkTreeException">NGit.Errors.NoWorkTreeException
        ///     </exception>
        private void CleanUp()
        {
            if (inCore)
            {
                modifiedFiles.Clear();
                return;
            }
            DirCache          dc       = db.ReadDirCache();
            ObjectReader      or       = db.ObjectDatabase.NewReader();
            Iterator <string> mpathsIt = modifiedFiles.Iterator();

            while (mpathsIt.HasNext())
            {
                string           mpath = mpathsIt.Next();
                DirCacheEntry    entry = dc.GetEntry(mpath);
                FileOutputStream fos   = new FileOutputStream(new FilePath(db.WorkTree, mpath));
                try
                {
                    or.Open(entry.GetObjectId()).CopyTo(fos);
                }
                finally
                {
                    fos.Close();
                }
                mpathsIt.Remove();
            }
        }
Пример #2
0
        public virtual void TestReadWriteMergeMsg()
        {
            NUnit.Framework.Assert.AreEqual(db.ReadSquashCommitMsg(), null);
            NUnit.Framework.Assert.IsFalse(new FilePath(db.Directory, Constants.SQUASH_MSG).Exists
                                               ());
            db.WriteSquashCommitMsg(squashMsg);
            NUnit.Framework.Assert.AreEqual(squashMsg, db.ReadSquashCommitMsg());
            NUnit.Framework.Assert.AreEqual(Read(new FilePath(db.Directory, Constants.SQUASH_MSG
                                                              )), squashMsg);
            db.WriteSquashCommitMsg(null);
            NUnit.Framework.Assert.AreEqual(db.ReadSquashCommitMsg(), null);
            NUnit.Framework.Assert.IsFalse(new FilePath(db.Directory, Constants.SQUASH_MSG).Exists
                                               ());
            FileOutputStream fos = new FileOutputStream(new FilePath(db.Directory, Constants.
                                                                     SQUASH_MSG));

            try
            {
                fos.Write(Sharpen.Runtime.GetBytesForString(squashMsg, Constants.CHARACTER_ENCODING
                                                            ));
            }
            finally
            {
                fos.Close();
            }
            NUnit.Framework.Assert.AreEqual(db.ReadSquashCommitMsg(), squashMsg);
        }
        /// <summary>Create an HttpFS Server to talk to the MiniDFSCluster we created.</summary>
        /// <exception cref="System.Exception"/>
        private void CreateHttpFSServer()
        {
            FilePath homeDir = TestDirHelper.GetTestDir();

            NUnit.Framework.Assert.IsTrue(new FilePath(homeDir, "conf").Mkdir());
            NUnit.Framework.Assert.IsTrue(new FilePath(homeDir, "log").Mkdir());
            NUnit.Framework.Assert.IsTrue(new FilePath(homeDir, "temp").Mkdir());
            HttpFSServerWebApp.SetHomeDirForCurrentThread(homeDir.GetAbsolutePath());
            FilePath   secretFile = new FilePath(new FilePath(homeDir, "conf"), "secret");
            TextWriter w          = new FileWriter(secretFile);

            w.Write("secret");
            w.Close();
            // HDFS configuration
            FilePath hadoopConfDir = new FilePath(new FilePath(homeDir, "conf"), "hadoop-conf"
                                                  );

            if (!hadoopConfDir.Mkdirs())
            {
                throw new IOException();
            }
            string        fsDefaultName = nnConf.Get(CommonConfigurationKeysPublic.FsDefaultNameKey);
            Configuration conf          = new Configuration(false);

            conf.Set(CommonConfigurationKeysPublic.FsDefaultNameKey, fsDefaultName);
            // Explicitly turn off XAttr support
            conf.SetBoolean(DFSConfigKeys.DfsNamenodeXattrsEnabledKey, false);
            FilePath     hdfsSite = new FilePath(hadoopConfDir, "hdfs-site.xml");
            OutputStream os       = new FileOutputStream(hdfsSite);

            conf.WriteXml(os);
            os.Close();
            // HTTPFS configuration
            conf = new Configuration(false);
            conf.Set("httpfs.hadoop.config.dir", hadoopConfDir.ToString());
            conf.Set("httpfs.proxyuser." + HadoopUsersConfTestHelper.GetHadoopProxyUser() + ".groups"
                     , HadoopUsersConfTestHelper.GetHadoopProxyUserGroups());
            conf.Set("httpfs.proxyuser." + HadoopUsersConfTestHelper.GetHadoopProxyUser() + ".hosts"
                     , HadoopUsersConfTestHelper.GetHadoopProxyUserHosts());
            conf.Set("httpfs.authentication.signature.secret.file", secretFile.GetAbsolutePath
                         ());
            FilePath httpfsSite = new FilePath(new FilePath(homeDir, "conf"), "httpfs-site.xml"
                                               );

            os = new FileOutputStream(httpfsSite);
            conf.WriteXml(os);
            os.Close();
            ClassLoader cl  = Sharpen.Thread.CurrentThread().GetContextClassLoader();
            Uri         url = cl.GetResource("webapp");

            if (url == null)
            {
                throw new IOException();
            }
            WebAppContext context = new WebAppContext(url.AbsolutePath, "/webhdfs");

            Org.Mortbay.Jetty.Server server = TestJettyHelper.GetJettyServer();
            server.AddHandler(context);
            server.Start();
        }
Пример #4
0
        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 void AfterCameraSelection(Intent data)
        {
            Bitmap       thumbnail = (Bitmap)data.Extras.Get("data");
            string       fileName  = DateTime.Now.Ticks + ".jpg";
            MemoryStream bytes     = new MemoryStream();

            thumbnail.Compress(Bitmap.CompressFormat.Png, 0, bytes);
            Java.IO.File destination = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory,
                                                        fileName);
            FileOutputStream fo;

            try
            {
                destination.CreateNewFile();
                fo = new FileOutputStream(destination);
                fo.Write(bytes.ToArray());
                fo.Close();
                thumbnail.Recycle();

                AddPicRequest(fileName, bytes);
            }
            catch (Exception)
            {
            }
        }
Пример #6
0
        public static void copy(Stream inputStream, File output)
        {
            OutputStream outputStream        = null;
            var          bufferedInputStream = new BufferedInputStream(inputStream);

            try {
                outputStream = new FileOutputStream(output);
                int    read  = 0;
                byte[] bytes = new byte[1024];
                while ((read = bufferedInputStream.Read(bytes)) != -1)
                {
                    outputStream.Write(bytes, 0, read);
                }
            } finally {
                try {
                    if (inputStream != null)
                    {
                        inputStream.Close();
                    }
                } finally {
                    if (outputStream != null)
                    {
                        outputStream.Close();
                    }
                }
            }
        }
Пример #7
0
        void WriteAudioDataToFile()
        {
            var data = new byte[bufferSize];

            rawFilePath = GetTempFileName();

            FileOutputStream outputStream = null;

            try
            {
                outputStream = new FileOutputStream(rawFilePath);
            }
            catch (Exception ex)
            {
                throw new FileLoadException($"unable to create a new file: {ex.Message}");
            }

            if (outputStream != null)
            {
                while (audioRecord.RecordingState == RecordState.Recording)
                {
                    audioRecord.Read(data, 0, bufferSize);

                    outputStream.Write(data);
                }

                outputStream.Close();
            }
        }
Пример #8
0
        public static bool SaveGame(Upgrades upgrades)
        {
            string content = (upgrades.Motyka + ";" + upgrades.Nawoz + ";" + upgrades.Rolnik + ";" + upgrades.Opryski + ";" + upgrades.Traktor + ";" + upgrades.MotykaStaraCena + ";"
                              + upgrades.NawozStaraCena + ";" + upgrades.RolnikStaraCena + ";" + upgrades.OpryskiStaraCena + ";" + upgrades.TraktorStaraCena + ";" + upgrades.Pieniadze);

            byte[] text = Encoding.ASCII.GetBytes(content);
            File   path;
            File   file;

            OutputStream ofile;
            string       filename = "Angame.sav";

            try
            {
                path = Android.OS.Environment.ExternalStorageDirectory;
                file = new File(path.AbsolutePath + "/" + "Angame", filename);
                file.Mkdir();
                file.Delete();
                file.CreateNewFile();
                ofile = new FileOutputStream(file);
                ofile.Write(text);
                ofile.Close();
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Пример #9
0
        public void UnZip()
        {
            byte[] buffer = new byte[65536];
            var fileInputStream = System.IO.File.OpenRead(_zipFile);

            var zipInputStream = new ZipInputStream(fileInputStream);
            ZipEntry zipEntry = null;
            int j = 0;
            int bestRead = 0;
            while ((zipEntry = zipInputStream.NextEntry) != null)
            {
                OnContinue?.Invoke(zipEntry.Name + ", " + bestRead);
                if (zipEntry.IsDirectory)
                {
                    DirChecker(zipEntry.Name);
                }
                else
                {
                    if (System.IO.File.Exists(_location + zipEntry.Name)) System.IO.File.Delete(_location + zipEntry.Name);
                    var foS = new FileOutputStream(_location + zipEntry.Name, true);
                    int read;
                    while ((read = zipInputStream.Read(buffer)) > 0)
                    {
                        if (read > bestRead) bestRead = read;
                        foS.Write(buffer, 0, read);
                    }
                    foS.Close();
                    zipInputStream.CloseEntry();
                }
            }
            zipInputStream.Close();
            fileInputStream.Close();
        }
        public File GetFileFromContentUri(string url)
        {
            File file = null;

            System.IO.Stream inputStream  = null;
            FileOutputStream outputStream = null;

            try
            {
                // inputStream = Resources.OpenRawResource(resource);
                inputStream  = this.Context.ContentResolver.OpenInputStream(Android.Net.Uri.Parse(url));
                file         = File.CreateTempFile("PDF", null);
                outputStream = new FileOutputStream(file);

                byte[] buffer = new byte[8 * 1024];
                int    bytesRead;
                while ((bytesRead = inputStream.Read(buffer)) > 0)
                {
                    outputStream.Write(buffer, 0, bytesRead);
                }
            }
            catch (IOException ex)
            {
                throw ex;
            }
            finally
            {
                inputStream.Close();
                outputStream.Close();
            }
            return(file);
        }
 private void CopyTestImageToSdCard(Java.IO.File testImageOnSdCard)
 {
     new Thread(new Runnable(() =>
     {
         try
         {
             Stream is_           = Assets.Open(TEST_FILE_NAME);
             FileOutputStream fos = new FileOutputStream(testImageOnSdCard);
             byte[] buffer        = new byte[8192];
             int read;
             try
             {
                 while ((read = is_.Read(buffer, 0, buffer.Length)) != -1)
                 {
                     fos.Write(buffer, 0, read);
                 }
             }
             finally
             {
                 fos.Flush();
                 fos.Close();
                 is_.Close();
             }
         }
         catch (Java.IO.IOException e)
         {
             L.W("Can't copy test image onto SD card");
         }
     })).Start();
 }
Пример #12
0
            private async Task RunAsync()
            {
                var buffer = _image.GetPlanes()[0].Buffer;

                byte[] bytes = new byte[buffer.Remaining()];
                buffer.Get(bytes);

                using (var output = new FileOutputStream(_file))
                {
                    try
                    {
                        output.Write(bytes);
                        output.Close();
                        output.Dispose();

                        bytes = null;
                        buffer.Clear();
                        buffer.Dispose();

                        var mediaFile = new MediaFile(_file.AbsolutePath);

                        await CrossMultiPictures.Current.ResizeAndRotateAsync(mediaFile, _mediaOptions, _currentRotation);

                        CallBack?.Invoke(this, mediaFile);
                    }
                    catch (IOException ex)
                    {
                        ex.PrintStackTrace();
                    }
                    finally
                    {
                        _image.Close();
                    }
                }
            }
Пример #13
0
        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)
            {
            }
        }
Пример #14
0
        /// <exception cref="System.Exception"/>
        private FilePath GetFileCommand(string clazz)
        {
            string   classpath = Runtime.GetProperty("java.class.path");
            FilePath fCommand  = new FilePath(workSpace + FilePath.separator + "cache.sh");

            fCommand.DeleteOnExit();
            if (!fCommand.GetParentFile().Exists())
            {
                fCommand.GetParentFile().Mkdirs();
            }
            fCommand.CreateNewFile();
            OutputStream os = new FileOutputStream(fCommand);

            os.Write(Sharpen.Runtime.GetBytesForString("#!/bin/sh \n"));
            if (clazz == null)
            {
                os.Write(Sharpen.Runtime.GetBytesForString(("ls ")));
            }
            else
            {
                os.Write(Sharpen.Runtime.GetBytesForString(("java -cp " + classpath + " " + clazz
                                                            )));
            }
            os.Flush();
            os.Close();
            FileUtil.Chmod(fCommand.GetAbsolutePath(), "700");
            return(fCommand);
        }
Пример #15
0
        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();
        }
Пример #16
0
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == ImageWithTouch.ClearImagePathProperty.PropertyName)
            {
                Control.Clear();
            }
            else if (e.PropertyName == ImageWithTouch.SavedImagePathProperty.PropertyName)
            {
                Bitmap curDrawingImage = Control.GetImageFromView();

                Byte[] imgBytes = ImageHelper.BitmapToBytes(curDrawingImage);
                var    f        = new File(Element.SavedImagePath);

                f.CreateNewFile();

                FileOutputStream fo = new FileOutputStream(f);
                fo.Write(imgBytes);

                fo.Close();
            }
            else
            {
                UpdateControl(true);
            }
        }
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void WritePrivateKey(string name)
        {
            FileOutputStream fos = new FileOutputStream(name);

            WritePrivateKey(fos);
            fos.Close();
        }
Пример #18
0
        private void copyDataBase()
        {
            Stream iStream = Assets.Open("database/cache.db");
            string dbPath  = "/data/data/hitec.Droid/files/cache.db";
            //path  "/data/data/camping.Droid/files/cache.db"

            var oStream = new FileOutputStream(dbPath);

            bool exists = System.IO.File.Exists(dbPath);
            long size   = 0;

            Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(dbPath));

            using (var fd = ContentResolver.OpenFileDescriptor(uri, "r"))
                size = fd.StatSize;

            if (size == 0)
            {
                byte[] buffer = new byte[2048];
                int    length = 2048;
                //    length = Convert.ToInt16(length2);

                while (iStream.Read(buffer, 0, length) > 0)
                {
                    oStream.Write(buffer, 0, length);
                }
                oStream.Flush();
                oStream.Close();
                iStream.Close();
            }
        }
        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);
            }
        }
        void WriteAudioDataToFile()
        {
            byte[] data = new byte[bufferSize];

            try
            {
                var outputStream = new FileOutputStream(tempFileName);
                try
                {
                    while (isRecording)
                    {
                        recorder.Read(data, 0, bufferSize);
                        outputStream.Write(data);
                    }
                }
                finally
                {
                    outputStream.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #21
0
        /// <summary>
        /// Downloads the resource with the specified URI to a local file.
        /// </summary>
        public void DownloadFile(URL address, string fileName)
        {
            URLConnection connection   = null;
            InputStream   inputStream  = null;
            OutputStream  outputStream = new FileOutputStream(fileName);

            try
            {
                connection  = OpenConnection(address);
                inputStream = connection.InputStream;
                var buffer = new byte[BUFFER_SIZE];
                int len;

                while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0)
                {
                    outputStream.Write(buffer, 0, len);
                }

                outputStream.Flush();
            }
            finally
            {
                if (inputStream != null)
                {
                    inputStream.Close();
                }
                var httpConnection = connection as HttpURLConnection;
                if (httpConnection != null)
                {
                    httpConnection.Disconnect();
                }
                outputStream.Close();
            }
        }
Пример #22
0
        private static string GetFileFromUrl(string fromUrl, string toFile)
        {
            try
            {
                URL           url        = new URL(fromUrl);
                URLConnection connection = url.OpenConnection();
                connection.Connect();

                //int fileLength = connection.GetContentLength();

                // download the file
                InputStream  input  = new BufferedInputStream(url.OpenStream());
                OutputStream output = new FileOutputStream(toFile);

                var  data  = new byte[1024];
                long total = 0;
                int  count;
                while ((count = input.Read(data)) != -1)
                {
                    total += count;
                    ////PublishProgress((int)(total * 100 / fileLength));
                    output.Write(data, 0, count);
                }

                output.Flush();
                output.Close();
                input.Close();
            }
            catch (Exception e)
            {
                Log.Error("YourApp", e.Message);
            }
            return(toFile);
        }
        public void Save(string filename, MemoryStream stream)
        {
            var root = Android.OS.Environment.DirectoryDownloads;
            var file = new Java.IO.File(root, filename);
            if (file.Exists()) file.Delete();
            try
            {
                var outs = new FileOutputStream(file);
                outs.Write(stream.ToArray());
                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                var f = e;
            }
            //if (file.Exists())
            //{
            //    var path = Android.Net.Uri.FromFile(file);
            //    var extension =
            //        Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
            //    var mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            //    var intent = new Intent(Intent.ActionOpenDocument);
            //    intent.SetDataAndType(path, mimeType);

            //    Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            //}
        }
Пример #24
0
        /// <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();
                }
            }
        }
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void WriteSECSHPublicKey(string name, string comment)
        {
            FileOutputStream fos = new FileOutputStream(name);

            WriteSECSHPublicKey(fos, comment);
            fos.Close();
        }
Пример #26
0
        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);
            }
        }
Пример #27
0
        /// <exception cref="System.Exception"/>
        public virtual void TestJobSubmissionFailure()
        {
            Org.Mockito.Mockito.When(resourceMgrDelegate.SubmitApplication(Matchers.Any <ApplicationSubmissionContext
                                                                                         >())).ThenReturn(appId);
            ApplicationReport report = Org.Mockito.Mockito.Mock <ApplicationReport>();

            Org.Mockito.Mockito.When(report.GetApplicationId()).ThenReturn(appId);
            Org.Mockito.Mockito.When(report.GetDiagnostics()).ThenReturn(failString);
            Org.Mockito.Mockito.When(report.GetYarnApplicationState()).ThenReturn(YarnApplicationState
                                                                                  .Failed);
            Org.Mockito.Mockito.When(resourceMgrDelegate.GetApplicationReport(appId)).ThenReturn
                (report);
            Credentials  credentials = new Credentials();
            FilePath     jobxml      = new FilePath(testWorkDir, "job.xml");
            OutputStream @out        = new FileOutputStream(jobxml);

            conf.WriteXml(@out);
            @out.Close();
            try
            {
                yarnRunner.SubmitJob(jobId, testWorkDir.GetAbsolutePath().ToString(), credentials
                                     );
            }
            catch (IOException io)
            {
                Log.Info("Logging exception:", io);
                NUnit.Framework.Assert.IsTrue(io.GetLocalizedMessage().Contains(failString));
            }
        }
        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);
            }
        }
Пример #29
0
        /// <summary>Convenience function to write the current state of the modelBatch out to a file, without factors.</summary>
        /// <param name="filename">the file to write the batch to</param>
        /// <exception cref="System.IO.IOException"/>
        public virtual void WriteToFileWithoutFactors(string filename)
        {
            FileOutputStream fos = new FileOutputStream(filename);

            WriteToStreamWithoutFactors(fos);
            fos.Close();
        }
Пример #30
0
        private void SaveExcel(MemoryStream stream)
        {
            string exception = string.Empty;
            string root = null;
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
            myDir.Mkdir();

            Java.IO.File file = new Java.IO.File(myDir, "report.xlsx");

            if (file.Exists()) file.Delete();

            try
            {
                FileOutputStream outs = new FileOutputStream(file);
                outs.Write(stream.ToArray());

                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                exception = e.ToString();
            }
        }
Пример #31
0
        /// <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();
            }
        }
Пример #32
0
        protected override string RunInBackground(params string[] @params)
        {
            string strongPath = Android.OS.Environment.ExternalStorageDirectory.Path;
            string filePath   = System.IO.Path.Combine(strongPath, "download.jpg");
            int    count;

            try
            {
                URL           url        = new URL(@params[0]);
                URLConnection connection = url.OpenConnection();
                connection.Connect();
                int          LengthOfFile = connection.ContentLength;
                InputStream  input        = new BufferedInputStream(url.OpenStream(), LengthOfFile);
                OutputStream output       = new FileOutputStream(filePath);
                byte[]       data         = new byte[1024];
                long         total        = 0;
                while ((count = input.Read(data)) != -1)
                {
                    total += count;
                    PublishProgress("" + (int)((total / 100) / LengthOfFile));
                    output.Write(data, 0, count);
                }
                output.Flush();
                output.Close();
                input.Close();
            }
            catch (Exception e)
            {
            }
            return(null);
        }
Пример #33
0
        public virtual void TestRecoveryMode()
        {
            // edits generated by nnHelper (MiniDFSCluster), should have all op codes
            // binary, XML, reparsed binary
            string           edits = nnHelper.GenerateEdits();
            FileOutputStream os    = new FileOutputStream(edits, true);
            // Corrupt the file by truncating the end
            FileChannel editsFile = os.GetChannel();

            editsFile.Truncate(editsFile.Size() - 5);
            string editsParsedXml = folder.NewFile("editsRecoveredParsed.xml").GetAbsolutePath
                                        ();
            string editsReparsed   = folder.NewFile("editsRecoveredReparsed").GetAbsolutePath();
            string editsParsedXml2 = folder.NewFile("editsRecoveredParsed2.xml").GetAbsolutePath
                                         ();

            // Can't read the corrupted file without recovery mode
            NUnit.Framework.Assert.AreEqual(-1, RunOev(edits, editsParsedXml, "xml", false));
            // parse to XML then back to binary
            NUnit.Framework.Assert.AreEqual(0, RunOev(edits, editsParsedXml, "xml", true));
            NUnit.Framework.Assert.AreEqual(0, RunOev(editsParsedXml, editsReparsed, "binary"
                                                      , false));
            NUnit.Framework.Assert.AreEqual(0, RunOev(editsReparsed, editsParsedXml2, "xml",
                                                      false));
            // judgment time
            NUnit.Framework.Assert.IsTrue("Test round trip", FileUtils.ContentEqualsIgnoreEOL
                                              (new FilePath(editsParsedXml), new FilePath(editsParsedXml2), "UTF-8"));
            os.Close();
        }
Пример #34
0
        public void PlayAudio(byte[] audioRecording, string fileExtension)
        {
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var file = new File(documents);
            var tempAudioFile = File.CreateTempFile(Guid.NewGuid().ToString(), fileExtension, file);
            tempAudioFile.DeleteOnExit();

            var stream = new FileOutputStream(tempAudioFile);
            stream.Write(audioRecording);
            stream.Close();

            // Tried passing path directly, but kept getting 
            // "Prepare failed.: status=0x1"
            // so using file descriptor instead
            var fileStream = new FileInputStream(tempAudioFile);
            _mediaPlayer.Reset();
            _mediaPlayer.SetDataSource(fileStream.FD);
            _mediaPlayer.Prepare();
            _mediaPlayer.Start();
        }
Пример #35
0
        public void Save(string fileName, String contentType, MemoryStream stream)
        {
            string exception = string.Empty;
            string root = null;
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
            myDir.Mkdir();

            Java.IO.File file = new Java.IO.File(myDir, fileName);

            if (file.Exists()) file.Delete();

            try
            {
                FileOutputStream outs = new FileOutputStream(file);
                outs.Write(stream.ToArray());

                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                exception = e.ToString();
            }
            if (file.Exists() && contentType != "application/html")
            {
                Android.Net.Uri path = Android.Net.Uri.FromFile(file);
                string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                Intent intent = new Intent(Intent.ActionView);
                intent.SetDataAndType(path, mimeType);
                Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));

            }
        }
Пример #36
0
 public static void copy(Stream inputStream, File output)
 {
     OutputStream outputStream = null;
     var bufferedInputStream = new BufferedInputStream(inputStream);
     try {
     outputStream = new FileOutputStream(output);
     int read = 0;
     byte[] bytes = new byte[1024];
     while ((read = bufferedInputStream.Read(bytes)) != -1){
         outputStream.Write(bytes, 0, read);
     }
     } finally {
     try {
         if (inputStream != null) {
             inputStream.Close();
         }
     } finally {
         if (outputStream != null) {
             outputStream.Close();
         }
     }
     }
 }
Пример #37
0
        // actually pushes a note to sdcard, with optional subdirectory (e.g. backup)
        private static int doPushNote(Note note)
        {
            Note rnote = new Note();
            try {
                File path = new File(Tomdroid.NOTES_PATH);

                if (!path.Exists())
                    path.Mkdir();

                TLog.i(TAG, "Path {0} Exists: {1}", path, path.Exists());

                // Check a second time, if not the most likely cause is the volume doesn't exist
                if(!path.Exists()) {
                    TLog.w(TAG, "Couldn't create {0}", path);
                    return NO_SD_CARD;
                }

                path = new File(Tomdroid.NOTES_PATH + "/"+note.getGuid() + ".note");

                note.createDate = note.getLastChangeDate().Format3339(false);
                note.cursorPos = 0;
                note.width = 0;
                note.height = 0;
                note.X = -1;
                note.Y = -1;

                if (path.Exists()) { // update existing note

                    // Try reading the file first
                    string contents = "";
                    try {
                        char[] buffer = new char[0x1000];
                        contents = readFile(path,buffer);
                    } catch (IOException e) {
                        e.PrintStackTrace();
                        TLog.w(TAG, "Something went wrong trying to read the note");
                        return PARSING_FAILED;
                    }

                    try {
                        // Parsing
                        // XML
                        // Get a SAXParser from the SAXPArserFactory
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();

                        // Get the XMLReader of the SAXParser we created
                        XMLReader xr = sp.getXMLReader();

                        // Create a new ContentHandler, send it this note to fill and apply it to the XML-Reader
                        NoteHandler xmlHandler = new NoteHandler(rnote);
                        xr.setContentHandler(xmlHandler);

                        // Create the proper input source
                        StringReader sr = new StringReader(contents);
                        InputSource inputSource = new InputSource(sr);

                        TLog.d(TAG, "parsing note. filename: {0}", path.Name());
                        xr.parse(inputSource);

                    // TODO wrap and throw a new exception here
                    } catch (Exception e) {
                        e.PrintStackTrace();
                        if(e as TimeFormatException) TLog.e(TAG, "Problem parsing the note's date and time");
                        return PARSING_FAILED;
                    }

                    note.createDate = rnote.createDate;
                    note.cursorPos = rnote.cursorPos;
                    note.width = rnote.width;
                    note.height = rnote.height;
                    note.X = rnote.X;
                    note.Y = rnote.Y;

                    note.setTags(rnote.getTags());
                }

                string xmlOutput = note.getXmlFileString();

                path.CreateNewFile();
                FileOutputStream fOut = new FileOutputStream(path);
                OutputStreamWriter myOutWriter =
                                        new OutputStreamWriter(fOut);
                myOutWriter.Append(xmlOutput);
                myOutWriter.Close();
                fOut.Close();

            }
            catch (Exception e) {
                TLog.e(TAG, "push to sd card didn't work");
                return NOTE_PUSH_ERROR;
            }
            return NOTE_PUSHED;
        }
Пример #38
0
 /// <summary>
 /// Write all given bytes to a file with given path.
 /// </summary>
 public static void WriteAllBytes(string path, byte[] bytes)
 {
     if (path == null)
         throw new ArgumentNullException("path");
     if (bytes == null)
         throw new ArgumentNullException("bytes");
     var file = new JFile(path);
     var stream = new FileOutputStream(file);
     try
     {
         stream.Write(bytes, 0, bytes.Length);
     }
     finally
     {
         stream.Close();
     }
 }
Пример #39
0
        public static Java.IO.File bitmapToFile(Bitmap inImage)
        {
            //create a file to write bitmap data
            Java.IO.File f = new Java.IO.File(nn_context.CacheDir, "tempimgforfacebookshare");
             			f.CreateNewFile();

            //Convert bitmap to byte array
            Bitmap bitmap = inImage;

            var bos = new MemoryStream();
             			bitmap.Compress(Bitmap.CompressFormat.Png, 0, bos);
            byte[] bitmapdata = bos.ToArray ();

            //write the bytes in file
            FileOutputStream fos = new FileOutputStream(f);
            fos.Write(bitmapdata);
            fos.Flush();
            fos.Close();

            return f;
        }
Пример #40
0
 public void OnPictureTaken(byte[] data, Camera camera)
 {
     FileOutputStream outStream = null;
     File dataDir = Android.OS.Environment.ExternalStorageDirectory;
     if (data != null)
     {
         try
         {
             outStream = new FileOutputStream(dataDir + "/" + "Photo.jpg");
             outStream.Write(data);
             outStream.Close();
             this.Dismiss();
         }
         catch (FileNotFoundException e)
         {
             System.Console.Out.WriteLine(e.Message);
         }
         catch (IOException ie)
         {
             System.Console.Out.WriteLine(ie.Message);
         }
     }
 }
Пример #41
0
		private void copyDataBase()
		{

			Stream iStream = Assets.Open("database/cache.db");
			var oStream = new FileOutputStream ("/data/data/hitec.Droid/files/cache.db");
			byte[] buffer = new byte[2048];
			int length = 2048;
			//    length = Convert.ToInt16(length2);



			while (iStream.Read(buffer, 0, length) > 0)
			{
				oStream.Write(buffer, 0, length);
			}
			oStream.Flush();
			oStream.Close();
			iStream.Close();
			
		

		}
Пример #42
0
        /// <summary>
        /// Downloads the resource with the specified URI to a local file.
        /// </summary>
        public void DownloadFile(URL address, string fileName)
        {
            URLConnection connection = null;
            InputStream inputStream = null;
            OutputStream outputStream = new FileOutputStream(fileName);
            try
            {
                connection = OpenConnection(address);
                inputStream = connection.InputStream;
                var buffer = new byte[BUFFER_SIZE];
                int len;

                while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0)
                {
                    outputStream.Write(buffer, 0, len);
                }

                outputStream.Flush();
            }
            finally
            {
                if (inputStream != null)
                    inputStream.Close();
                var httpConnection = connection as HttpURLConnection;
                if (httpConnection != null)
                    httpConnection.Disconnect();
                outputStream.Close();
            }
        }
Пример #43
0
		/// <summary>
		/// 下载apk文件
		/// </summary>
		private void DownloadApk()
		{
			
			URL url = null;  
			Stream instream = null;  
			FileOutputStream outstream = null;  
			HttpURLConnection conn = null;  
			try
			{
				url = new URL(Global.AppPackagePath);
				//创建连接
				conn = (HttpURLConnection) url.OpenConnection();
				conn.Connect();

				conn.ConnectTimeout =20000;
				//获取文件大小
				var filelength = conn.ContentLength;
				instream = conn.InputStream;
				var file = new Java.IO.File(FILE_PATH);
				if(!file.Exists())
				{
					file.Mkdir();
				}
				outstream = new FileOutputStream(new Java.IO.File(saveFileName));

				int count =0;
				//缓存
				byte[] buff = new byte[1024];
				//写入文件中
				do
				{
					int numread = instream.Read(buff,0,buff.Length);
					count+=numread;
					//计算进度条位置
					progress = (int)(((float)count/filelength)*100);
				    //更新进度---- other question

					mProgressbar.Progress = progress;
					if(numread<=0)
					{
						//下载完成,安装新apk
						Task.Factory.StartNew(InStallApk);
						break;
					}
					//写入文件
					outstream.Write(buff,0,numread);

				}
				while(!cancelUpdate);//点击取消,停止下载
					
			}
			catch(Exception ex)
			{
				Android.Util.Log.Error (ex.StackTrace,ex.Message);
			}
			finally
			{
				if (instream != null)
					instream.Close ();
				if (outstream != null)
					outstream.Close ();
				if(conn!=null)
				    conn.Disconnect ();
			}
			dowloadDialog.Dismiss ();
		}
Пример #44
0
        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/
            };
        }
	    /**
	     * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback
	     * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}.
	     *
	     * @param cookie An arbitrary object that will be passed to the callback.
	     */
	    public static void FetchImage(Context context, Java.Lang.String url, BitmapFactory.Options decodeOptions, Java.Lang.Object cookie, Action<Bitmap> callback) 
		{
			
			Task.Factory.StartNew(() => {
				if(TextUtils.IsEmpty(url))
				{
					result = null;
					return;
				}
				
				File cacheFile = null;
				try
				{
					MessageDigest mDigest = MessageDigest.GetInstance("SHA-1");
					mDigest.Update(url.GetBytes());
					string cacheKey = BytesToHexString(mDigest.Digest());
					if(Environment.MediaMounted.Equals(Environment.ExternalStorageState))
					{
						cacheFile = new File(Environment.ExternalStorageDirectory +
						                     File.Separator + "Android " + 
						                     File.Separator + "data" +
						                     File.Separator + context.PackageName + 
						                     File.Separator + "cache" +
						                     File.Separator + "bitmap_" + cacheKey + ".tmp");
					}
				}
				catch (Exception e) 
				{
					// NoSuchAlgorithmException
					// Oh well, SHA-1 not available (weird), don't cache bitmaps.
				}
				
				if (cacheFile != null && cacheFile.Exists()) 
				{
	                Bitmap cachedBitmap = BitmapFactory.DecodeFile(cacheFile.ToString(), decodeOptions);
                    if (cachedBitmap != null) {
                        result = cachedBitmap;
						return;
                    }
                }
				
				try 
				{
				    // TODO: check for HTTP caching headers
					var client = new System.Net.WebClient();
					var image = client.DownloadData(new Uri(url.ToString()));
					if (image != null)
					{
						result = null;
						return;
					}
				
				    // Write response bytes to cache.
				    if (cacheFile != null) {
				        try {
				            cacheFile.ParentFile.Mkdirs();
				            cacheFile.CreateNewFile();
				            FileOutputStream fos = new FileOutputStream(cacheFile);
				            fos.Write(image);
				            fos.Close();
				        } catch (FileNotFoundException e) {
				            Log.Warn(TAG, "Error writing to bitmap cache: " + cacheFile.ToString(), e);
				        } catch (IOException e) {
				            Log.Warn(TAG, "Error writing to bitmap cache: " + cacheFile.ToString(), e);
				        }
				    }
				
				    // Decode the bytes and return the bitmap.
				    result = (BitmapFactory.DecodeByteArray(image, 0, image.Length, decodeOptions));
					return;
				} catch (Exception e) {
				    Log.Warn(TAG, "Problem while loading image: " + e.ToString(), e);
				}
                result = null;
			})
			.ContinueWith(task =>
				callback(result)
        	);
			
	    }
Пример #46
0
        public Task<string> GetSoundFromGalleryAsync()
        {
            return AsyncHelper.CreateAsyncFromCallback<string>(resultCallback =>
            {
                Intent intent = new Intent();
                intent.SetType("audio/*");
                intent.SetAction(Intent.ActionGetContent);
                var trad = DependencyService.Container.Resolve<ILocalizationService>();
                ActivityService.StartActivityForResult(Intent.CreateChooser(intent, trad.GetString("SoundChoice_PickerTitle", "Text")), (result, data) =>
                {
                    string path = null;
                    if (result == Result.Ok)
                    {
                        Uri selectedSound = data.Data;
                        ParcelFileDescriptor parcelFileDescriptor = ActivityService.CurrentActivity.ContentResolver.OpenFileDescriptor(selectedSound, "r");
                        FileDescriptor fileDescriptor = parcelFileDescriptor.FileDescriptor;
                        FileInputStream inputStream = new FileInputStream(fileDescriptor);
                        path = StorageService.GenerateFilename(StorageType.Sound, "3gpp");
                        File outputFile = new File(path);
	                    InputStream inStream = inputStream;
                        OutputStream outStream = new FileOutputStream(outputFile);

                        byte[] buffer = new byte[1024];

                        int length;
                        //copy the file content in bytes 
                        while ((length = inStream.Read(buffer)) > 0)
                        {
                            outStream.Write(buffer, 0, length);
                        }
                        inStream.Close();
                        outStream.Close();
                    }
                    resultCallback(path);
                });
            });
        }
Пример #47
0
 public void OnPictureTaken(sbyte[] data, Camera camera)
 {
     var pictureFile = GetOutputMediaFile();
     if (pictureFile == null)
     {
         return;
     }
     try
     {
         var fos = new FileOutputStream(pictureFile);
         fos.Write(data);
         fos.Close();
     }
     catch
     {
         // Ignore for now
     }
 }
Пример #48
0
        public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
        {
            FileOutputStream output = null;
            string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "Images");
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            string filename = PictureName + number.ToString() + ".jpg";
            if (data != null)
            {
                fullFilename = System.IO.Path.Combine(path, filename);
                number++;
                try
                {
                    output = new FileOutputStream(fullFilename);
                    output.Write(data);
                    output.Close();
                }
                catch (FileNotFoundException)
                {
                    RunOnUiThread(delegate
                    {
                        GeneralUtils.Alert(context, Application.Context.Resources.GetString(Resource.String.commonError),
                            Application.Context.Resources.GetString(Resource.String.errorFileTransfer));
                    });
                    return;
                }
                catch (IOException)
                {
                    RunOnUiThread(delegate
                    {
                        GeneralUtils.Alert(context, Application.Context.Resources.GetString(Resource.String.commonError),
                            Application.Context.Resources.GetString(Resource.String.errorNoImagesTaken));
                    });
                    isRunning = true;
                    camera.StartPreview();
                    return;
                }
                catch (Exception e)
                {
                    #if DEBUG
                    System.Diagnostics.Debug.WriteLine("Exception thrown - {0}", e.Message);
                    #endif
                    return;
                }

                var f = new File(fullFilename);
                try
                {
                    var exifInterface = new ExifInterface(f.CanonicalPath);
                    exifInterface.GetAttribute(ExifInterface.TagModel);
                    var latLong = new float[2];
                    exifInterface.GetLatLong(latLong);
                    exifInterface.SetAttribute(ExifInterface.TagMake, "Phone picture");
                    exifInterface.SetAttribute(ExifInterface.TagDatetime, DateTime.Now.ToString());
                }
                catch (IOException)
                {
                    RunOnUiThread(delegate
                    {
                        GeneralUtils.Alert(context, Application.Context.Resources.GetString(Resource.String.commonError),
                            Application.Context.Resources.GetString(Resource.String.errorStoreEXIF));
                    });
                    isRunning = true;
                    camera.StartPreview();
                    return;
                }
            }
            RunOnUiThread(() => Toast.MakeText(context, Application.Context.Resources.GetString(Resource.String.commonPictureTaken), ToastLength.Short).Show());
            isRunning = true;
            camera.StartPreview();
            return;
        }
        private Bitmap GetBitmap(string url)
        {
            File f= m_FileCache.GetFile(url);

            ////from SD cache
            Bitmap b = DecodeFile(f, m_Scale);
            if(b!=null)
                return b;

            ////from web
            try
            {
                Bitmap bitmap=null;
                URL imageUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection)imageUrl.OpenConnection();
                conn.ConnectTimeout = 5000;
                conn.ReadTimeout = 5000;
                conn.InstanceFollowRedirects = true;

                if (conn.ErrorStream != null)
                    return null;

                var inputStream = conn.InputStream;
                OutputStream os = new FileOutputStream(f);
                CopyStream(inputStream, os);
                os.Close();
                bitmap = DecodeFile(f, m_Scale);
                return bitmap;
            }
            catch (Exception ex)
            {
               //ex.printStackTrace();
               return null;
            }
        }
Пример #50
0
        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/
            };
        }
Пример #51
0
		//***************************************************************************************************
		//******************FUNCION  QUE SE ENCARGA DEL PROCESO DE DESCARGA DE ARCHIVO***********************
		//***************************************************************************************************
		void DescargaArchivo(ProgressCircleView  tem_pcv, string url_archivo)
		{
			//OBTENEMOS LA RUTA DONDE SE ENCUENTRA LA CARPETA PICTURES DE NUESTRO DISPOSITIVO Y LE CONCTENAMOS 
			//EL NOMBRE DE UNA CARPETA NUEVA CARPETA, ES AQUI DONDE GUADAREMOS EL ARCHIVO A DESCARGAR
			string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ;
			Java.IO.File directory = new Java.IO.File (filePath);

			//VERIFICAMOS SI LA CARPETA EXISTE, SI NO LA CREAMOS
			if(directory.Exists() ==false)
			{
				directory.Mkdir();
			}

			//ESTABLECEMOS LA UBICACION DE NUESTRO ARCHIVO A DESCARGAR
			URL url = new URL(url_archivo);

			//CABRIMOS UNA CONEXION CON EL ARCHIVO
			URLConnection conexion = url.OpenConnection();
			conexion.Connect ();

			//OBTENEMOS EL TAMAÑO DEL ARCHIVO A DESCARGAR
			int lenghtOfFile = conexion.ContentLength;

			//CREAMOS UN INPUTSTREAM PARA PODER EXTRAER EL ARCHIVO DE LA CONEXION
			InputStream input = new BufferedInputStream(url.OpenStream());

			//ASIGNAMOS LA RUTA DONDE SE GUARDARA EL ARCHIVO, Y ASIGNAMOS EL NOMBRE CON EL QUE SE DESCARGAR EL ARCHIVO
			//PARA ESTE CASO CONSERVA EL MISMO NOMBRE
			string NewFile = directory.AbsolutePath+ "/"+ url_archivo.Substring (url_archivo.LastIndexOf ("/") + 1);

			//CREAMOS UN OUTPUTSTREAM EN EL CUAL UTILIZAREMOS PARA CREAR EL ARCHIVO QUE ESTAMOS DESCARGANDO
			OutputStream output = new FileOutputStream(NewFile);
			byte[] data= new byte[lenghtOfFile];
			long total = 0;

			int count;
			//COMENSAMOS A LEER LOS DATOS DE NUESTRO INPUTSTREAM
			while ((count = input.Read(data)) != -1) 
			{
				total += count;
				//CON ESTA OPCION REPORTAMOS EL PROGRESO DE LA DESCARGA EN PORCENTAJE A NUESTRO CONTROL
				//QUE SE ENCUENTRA EN EL HILO PRINCIPAL
				RunOnUiThread(() => tem_pcv.setPorcentaje ((int)((total*100)/lenghtOfFile)));

				//ESCRIBIMOS LOS DATOS DELIDOS ES NUESTRO OUTPUTSTREAM
				output.Write(data, 0, count);

			}
			output.Flush();
			output.Close();
			input.Close();

			//INDICAMOS A NUESTRO PROGRESS QUE SE HA COMPLETADO LA DESCARGA AL 100%
			RunOnUiThread(() => tem_pcv.setPorcentaje (100));

		}
Пример #52
0
		public Bitmap GetBitmap(string url) 
		{
			Java.IO.File file=fileCache.GetFile(url);
			//先从文件缓存中查找是否有
			//from SD cache
			Bitmap b = DecodeFile(file);
			if(b!=null)
				return b;
			/**
         *  最后从指定的url中下载图片
         */
			//from web
			try {
				Bitmap bitmap=null;
				URL imageUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection)imageUrl.OpenConnection();
				conn.Connect();
				conn.ConnectTimeout=30000;
				conn.ReadTimeout=30000;
				conn.InstanceFollowRedirects=true;
				var inStream=conn.InputStream;
				var outputStream = new FileOutputStream(file);
				CopyStream(inStream, outputStream);
				outputStream.Close();
				conn.Disconnect();
				bitmap = DecodeFile(file);

				return bitmap;

			} catch (Throwable ex){
				
				ex.PrintStackTrace();
				if(ex is OutOfMemoryError)
					memoryCache.Clear();
				return null;
			}

		}
Пример #53
0
			protected override Java.Lang.Object DoInBackground (params Java.Lang.Object[] @params)
			{
				//REALIZAMOS EL PROCESO DE DESCARGA DEL ARCHIVO
				try{

					string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ;
					Java.IO.File directory = new Java.IO.File (filePath);
					if(directory.Exists() ==false)
					{
						directory.Mkdir();
					}

					//RECUPERAMOS LA DIRECCION DEL ARCHIVO QUE DESEAMOS DESCARGAR
					string url_link = @params [0].ToString ();
					URL url = new URL(url_link);
					URLConnection conexion = url.OpenConnection();
					conexion.Connect ();

					int lenghtOfFile = conexion.ContentLength;
					InputStream input = new BufferedInputStream(url.OpenStream());

					string NewImageFile = directory.AbsolutePath+ "/"+ url_link.Substring (url_link.LastIndexOf ("/") + 1);
					OutputStream output = new FileOutputStream(NewImageFile);
					byte[] data= new byte[lenghtOfFile];


					int count;
					while ((count = input.Read(data)) != -1) 
					{
						output.Write(data, 0, count);
					}
					output.Flush();
					output.Close();
					input.Close();
					return true;

				}catch {
					return  false;
				}

			}
Пример #54
0
        private void SaveMessage(string message)
        {
            try
              {
            if (Context != null)
            {
              using (File dir = Context.GetDir("RaygunIO", FileCreationMode.Private))
              {
            int number = 1;
            string[] files = dir.List();
            while (true)
            {
              bool exists = FileExists(files, "RaygunErrorMessage" + number + ".txt");
              if (!exists)
              {
                string nextFileName = "RaygunErrorMessage" + (number + 1) + ".txt";
                exists = FileExists(files, nextFileName);
                if (exists)
                {
                  DeleteFile(dir, nextFileName);
                }
                break;
              }
              number++;
            }
            if (number == 11)
            {
              string firstFileName = "RaygunErrorMessage1.txt";
              if (FileExists(files, firstFileName))
              {
                DeleteFile(dir, firstFileName);
              }
            }

            using (File file = new File(dir, "RaygunErrorMessage" + number + ".txt"))
            {
              using (FileOutputStream stream = new FileOutputStream(file))
              {
                stream.Write(Encoding.ASCII.GetBytes(message));
                stream.Flush();
                stream.Close();
              }
            }
            System.Diagnostics.Debug.WriteLine("Saved message: " + "RaygunErrorMessage" + number + ".txt");
            System.Diagnostics.Debug.WriteLine("File Count: " + dir.List().Length);
              }
            }
              }
              catch (Exception ex)
              {
            System.Diagnostics.Debug.WriteLine(string.Format("Error saving message to isolated storage {0}", ex.Message));
              }
        }
Пример #55
0
        public void OnPictureTaken(byte[] data,Camera camera)
        {
            System.Console.WriteLine("OnPictureTaken");

            lastPictureFilePath = getOutputMediaFilepath ();
            File pictureFile = new File(lastPictureFilePath);
            if (pictureFile == null) {
                Log.Error ("CustomCamera", "Error creating media file, check storage permissions: ", new Java.IO.IOException ());
                return;
            }

            try {
                FileOutputStream fos = new FileOutputStream (pictureFile);
                fos.Write (data);
                fos.Close ();
            } catch (Java.IO.FileNotFoundException e) {
                Log.Error ("CustomCamera", "File not found: ", e);
            } catch (Java.IO.IOException e) {
                Log.Error ("CustomCamera", "Error accessing file: ", e);
            }
        }
Пример #56
0
		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 ();
				}
			}
		}
 private void CopyTestImageToSdCard(Java.IO.File testImageOnSdCard)
 {
     new Thread(new Runnable(() =>
     {
         try
         {
             Stream is_ = Assets.Open(TEST_FILE_NAME);
             FileOutputStream fos = new FileOutputStream(testImageOnSdCard);
             byte[] buffer = new byte[8192];
             int read;
             try
             {
                 while ((read = is_.Read(buffer, 0, buffer.Length)) != -1)
                 {
                     fos.Write(buffer, 0, read);
                 }
             }
             finally
             {
                 fos.Flush();
                 fos.Close();
                 is_.Close();
             }
         }
         catch (Java.IO.IOException e)
         {
             L.W("Can't copy test image onto SD card");
         }
     })).Start();
 }
Пример #58
0
        public void get(String remoteAbsolutePath, String localAbsolutePath, SftpProgressMonitor monitor, int mode)
        {
            remoteAbsolutePath = this.remoteAbsolutePath(remoteAbsolutePath);
            localAbsolutePath = this.localAbsolutePath(localAbsolutePath);

            try
            {
                ArrayList files = glob_remote(remoteAbsolutePath);

                if (files.Count == 0)
                {
                    throw new SftpException(SSH_FX_NO_SUCH_FILE, "No such file");
                }

                bool copyingToDirectory = new File(localAbsolutePath).isDirectory();

                // if we're not copying to a directory but we're copying multiple files, there's a problem
                if (false == copyingToDirectory && files.Count > 1)
                {
                    throw new SftpException(SSH_FX_FAILURE, "Copying multiple files, but destination is missing or is a file.");
                }

                // if the given local path doesn't end with a '\' or other file separator, add one
                if (!localAbsolutePath.EndsWith(file_separator))
                {
                    localAbsolutePath += file_separator;
                }

                for (int j = 0; j < files.Count; j++)
                {
                    String sourceFile = (String)(files[j]);

                    SftpATTRS attr = GetPathAttributes(sourceFile);

                    // get information on the current file
                    if (attr.isDir())
                    {
                        // right now it's not able to get a directory
                        throw new SftpException(SSH_FX_FAILURE, "not supported to get directory " + sourceFile);
                    }

                    String destinationPath = null;

                    if (copyingToDirectory)
                    {
                        StringBuilder destinationSb = new StringBuilder(localAbsolutePath);

                        // find the last file separator character
                        int i = sourceFile.LastIndexOf(file_separatorc);

                        // basically we're appending just the filename
                        if (i == -1)
                            destinationSb.Append(sourceFile);
                        else
                            destinationSb.Append(sourceFile.Substring(i + 1));

                        destinationPath = destinationSb.ToString();
                    }
                    else
                    {
                        destinationPath = localAbsolutePath;
                    }

                    if (mode == RESUME)
                    {
                        long sizeOfSourceFile = attr.getSize();

                        long sizeOfDestinationFile = new File(destinationPath).Length();

                        // this means we already copied more data than is available. fail
                        if (sizeOfDestinationFile > sizeOfSourceFile)
                        {
                            throw new SftpException(SSH_FX_FAILURE, "failed to resume for " + destinationPath);
                        }

                        // if the sizes are equal, we're gravy
                        if (sizeOfDestinationFile == sizeOfSourceFile)
                        {
                            return;
                        }
                    }

                    if (monitor != null)
                    {
                        monitor.init(SftpProgressMonitor.GET, sourceFile, destinationPath, attr.getSize());

                        if (mode == RESUME)
                        {
                            monitor.count(new File(destinationPath).Length());
                        }
                    }

                    // create the output stream, and append if it's in overwrite mode
                    FileOutputStream fileOutputStream = new FileOutputStream(destinationPath, mode == OVERWRITE);

                    _get(sourceFile, fileOutputStream, monitor, mode, new File(destinationPath).Length());

                    fileOutputStream.Close();
                }
            }
            catch (SftpException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new SftpException(SSH_FX_FAILURE, "");
            }
        }
Пример #59
0
		private void copyDataBase()
		{

			Stream iStream = Assets.Open("database/cache.db");
			string dbPath = "/data/data/camping.Droid/files/cache.db";
			    	//path  "/data/data/camping.Droid/files/cache.db"   

			var oStream = new FileOutputStream (dbPath);

			bool exists = System.IO.File.Exists(dbPath);
			long size = 0;
			Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(dbPath));

			using (var fd = ContentResolver.OpenFileDescriptor(uri, "r"))
				size = fd.StatSize;

			if ( size == 0 ) {
				byte[] buffer = new byte[2048];
				int length = 2048;
				//    length = Convert.ToInt16(length2);
				 
				while (iStream.Read(buffer, 0, length) > 0)
				{
					oStream.Write(buffer, 0, length);
				}
				oStream.Flush();
				oStream.Close();
				iStream.Close();

			}

		

		}