Пример #1
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 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"));
            //}
        }
Пример #3
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();
            }
        }
Пример #4
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 ();
				}
			}
		}
 public static void save(string fname, object obj)
 {
     try
     {
         FileOutputStream fs = new FileOutputStream(fname);
         ObjectOutputStream @out = new ObjectOutputStream(fs);
         @out.writeObject(obj);
         @out.close();
     }
     catch(Exception ex)
     {
         ex.printStackTrace();
     }
 }
Пример #6
0
 /// <summary>Try to establish the lock.</summary>
 /// <remarks>Try to establish the lock.</remarks>
 /// <returns>
 /// true if the lock is now held by the caller; false if it is held
 /// by someone else.
 /// </returns>
 /// <exception cref="System.IO.IOException">
 /// the temporary output file could not be created. The caller
 /// does not hold the lock.
 /// </exception>
 public virtual bool Lock()
 {
     FileUtils.Mkdirs(lck.GetParentFile(), true);
     if (lck.CreateNewFile())
     {
         haveLck = true;
         try
         {
             os = new FileOutputStream(lck);
         }
         catch (IOException ioe)
         {
             Unlock();
             throw;
         }
     }
     return(haveLck);
 }
Пример #7
0
        public static void WritFile(string path, string fileName, string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return;
            }
            string filePath = path + fileName;

            Java.IO.File     file             = new Java.IO.File(filePath);
            FileOutputStream fileOutputStream = null;

            if (!file.Exists())
            {
                try
                {
                    file.CreateNewFile();
                    Runtime runtime = Runtime.GetRuntime();
                    runtime.Exec("chmod 0666 " + file);
                }
                catch (Java.Lang.Exception ex)
                {
                    ex.PrintStackTrace();
                }
            }
            try
            {
                fileOutputStream = new FileOutputStream(file);
                fileOutputStream.Write(Encoding.ASCII.GetBytes(data));
            }
            catch (Java.Lang.Exception e)
            {
                e.PrintStackTrace();
            }
            finally
            {
                try
                {
                    fileOutputStream.Close();
                }
                catch (Java.Lang.Exception e)
                {
                }
            }
        }
Пример #8
0
        public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream filestream)
        {
            string exception = string.Empty;
            string root      = null;

            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = System.Environment.GetFolderPath(System.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(filestream.ToArray());

                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                exception = e.ToString();
            }
            Intent email = new Intent(Android.Content.Intent.ActionSend);

            Android.Net.Uri uri = FileProvider.GetUriForFile(Forms.Context, Android.App.Application.Context.PackageName + ".provider", file);
            email.PutExtra(Android.Content.Intent.ExtraSubject, subject);
            email.PutExtra(Intent.ExtraStream, uri);
            email.SetType("application/pdf");
            Forms.Context.StartActivity(email);
        }
Пример #9
0
        public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
        {
            InputStream  input  = null;
            OutputStream output = null;

            try
            {
                File file = new File(_filePath);
                input  = new FileInputStream(file);
                output = new FileOutputStream(destination.FileDescriptor);

                byte[] buffer = new byte[8 * 1024];
                int    length;
                while ((length = input.Read(buffer)) >= 0 && !cancellationSignal.IsCanceled)
                {
                    output.Write(buffer, 0, length);
                }

                if (cancellationSignal.IsCanceled)
                {
                    callback.OnWriteCancelled();
                }
                else
                {
                    callback.OnWriteFinished(new PageRange[] { PageRange.AllPages });
                }
            }
            catch (Exception e)
            {
                callback.OnWriteFailed(e.Message);
            }
            finally
            {
                try
                {
                    input.Close();
                    output.Close();
                }
                catch (IOException e)
                {
                    Log.Error("WalkOut", e.Message);
                }
            }
        }
Пример #10
0
        public virtual void TestFileStatusSerialziation()
        {
            string testfilename = "testFileStatusSerialziation";

            TestDir.Mkdirs();
            FilePath infile = new FilePath(TestDir, testfilename);

            byte[]           content = Runtime.GetBytesForString("dingos");
            FileOutputStream fos     = null;

            try
            {
                fos = new FileOutputStream(infile);
                fos.Write(content);
            }
            finally
            {
                if (fos != null)
                {
                    fos.Close();
                }
            }
            Assert.Equal((long)content.Length, infile.Length());
            Configuration conf = new Configuration();

            ConfigUtil.AddLink(conf, "/foo/bar/baz", TestDir.ToURI());
            FileSystem vfs = FileSystem.Get(FsConstants.ViewfsUri, conf);

            Assert.Equal(typeof(ViewFileSystem), vfs.GetType());
            FileStatus stat = vfs.GetFileStatus(new Path("/foo/bar/baz", testfilename));

            Assert.Equal(content.Length, stat.GetLen());
            // check serialization/deserialization
            DataOutputBuffer dob = new DataOutputBuffer();

            stat.Write(dob);
            DataInputBuffer dib = new DataInputBuffer();

            dib.Reset(dob.GetData(), 0, dob.GetLength());
            FileStatus deSer = new FileStatus();

            deSer.ReadFields(dib);
            Assert.Equal(content.Length, deSer.GetLen());
        }
Пример #11
0
        public async Task SaveTextAsync(string fileName, String contentType, MemoryStream s)
        {
            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(s.ToArray());

                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
            }
            if (file.Exists())
            {
                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"));
            }
        }
Пример #12
0
        public async void OnSaveButtonClicked(object sender, EventArgs args)
        {
            //change to next view
            var carInfoPanel   = FindViewById <LinearLayout>(Resource.Id.carInfo);
            var carRecordPanel = FindViewById <LinearLayout>(Resource.Id.CarRecord);

            carInfoPanel.Visibility   = ViewStates.Gone;
            carRecordPanel.Visibility = ViewStates.Visible;

            var make  = FindViewById <EditText>(Resource.Id.carMake);
            var model = FindViewById <EditText>(Resource.Id.carModel);
            var year  = FindViewById <EditText>(Resource.Id.carYear);

            var path     = this.FilesDir + "/data";
            var exists   = Directory.Exists(path);
            var filepath = path + "/cardata.txt";

            if (!exists)
            {
                //pretty sure I threw an exception here the first time I ran this
                //and then never again. Dont know why, can't reproduce because now the directory exists.
                //Worked when testing on device.  Not sure what data is sent to the device when debugging.
                Directory.CreateDirectory(path);
                if (!System.IO.File.Exists(filepath))
                {
                    var newfile = new Java.IO.File(path, "cardata.txt");
                    using (FileOutputStream cardata = new FileOutputStream(newfile))
                    {
                        cardata.Write(System.Text.Encoding.ASCII.GetBytes(make.Text + "&" + model.Text + "&" + year.Text));
                        cardata.Close();
                    }
                }
            }
            else
            {
                var oldcardata = new Java.IO.File(path, "cardata.txt");

                using (FileOutputStream cardata = new FileOutputStream(oldcardata))
                {
                    cardata.Write(System.Text.Encoding.ASCII.GetBytes(make.Text + "&" + model.Text + "&" + year.Text));
                    cardata.Close();
                }
            }
        }
        public Task View(Stream stream, string filename)
        {
            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 + "/Telerik");
            myDir.Mkdir();
            Java.IO.File file = new Java.IO.File(myDir, filename);

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

            using (FileOutputStream outs = new FileOutputStream(file))
            {
                stream.Seek(0, SeekOrigin.Begin);
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                outs.Write(buffer);
            }

            if (file.Exists())
            {
                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"));
            }

            return(Task.CompletedTask);
        }
Пример #14
0
        public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
        {
            InputStream  input  = null;
            OutputStream output = null;

            try
            {
                //Create FileInputStream object from the given file
                input = new FileInputStream(FileToPrint);
                //Create FileOutputStream object from the destination FileDescriptor instance
                output = new FileOutputStream(destination.FileDescriptor);

                byte[] buf = new byte[1024];
                int    bytesRead;

                while ((bytesRead = input.Read(buf)) > 0)
                {
                    //Write the contents of the given file to the print destination
                    output.Write(buf, 0, bytesRead);
                }

                callback.OnWriteFinished(new PageRange[] { PageRange.AllPages });
            }
            catch (FileNotFoundException ee)
            {
                //Catch exception
            }
            catch (Exception e)
            {
                //Catch exception
            }
            finally
            {
                try
                {
                    input.Close();
                    output.Close();
                }
                catch (IOException e)
                {
                    e.PrintStackTrace();
                }
            }
        }
Пример #15
0
        /// <summary>test method getLocations</summary>
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestgetLocations()
        {
            JobConf  job     = new JobConf();
            FilePath tmpFile = FilePath.CreateTempFile("test", "txt");

            tmpFile.CreateNewFile();
            OutputStream @out = new FileOutputStream(tmpFile);

            @out.Write(Sharpen.Runtime.GetBytesForString("tempfile"));
            @out.Flush();
            @out.Close();
            Path[]         path    = new Path[] { new Path(tmpFile.GetAbsolutePath()) };
            long[]         lengths = new long[] { 100 };
            MultiFileSplit split   = new MultiFileSplit(job, path, lengths);

            string[] locations = split.GetLocations();
            NUnit.Framework.Assert.IsTrue(locations.Length == 1);
            NUnit.Framework.Assert.AreEqual(locations[0], "localhost");
        }
Пример #16
0
        public async Task Open(string filePath)
        {
            var client = new HttpClient();
            var rawPdf = await client.GetByteArrayAsync(filePath);

            var f = new Java.IO.File(MainActivity.CurrentActivity.CacheDir, "sample.pdf");

            FileOutputStream output = new FileOutputStream(f);
            await output.WriteAsync(rawPdf);

            output.Close();

            var pdfFileDescriptor = ParcelFileDescriptor.Open(f, ParcelFileMode.ReadOnly);
            var renderer          = new PdfRenderer(pdfFileDescriptor);

            PdfActivity.PdfRenderer = renderer;
            PdfActivity.File        = filePath;
            MainActivity.CurrentActivity.StartActivity(new Intent(MainActivity.CurrentActivity, typeof(PdfActivity)));
        }
Пример #17
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="System.IO.FileNotFoundException"/>
        /// <exception cref="System.IO.UnsupportedEncodingException"/>
        private OutputStreamWriter GetOutputStreamWriter(Path srcFilePath, string fileName
                                                         )
        {
            FilePath dir = new FilePath(srcFilePath.ToString());

            if (!dir.Exists())
            {
                if (!dir.Mkdirs())
                {
                    throw new IOException("Unable to create directory : " + dir);
                }
            }
            FilePath outputFile = new FilePath(new FilePath(srcFilePath.ToString()), fileName
                                               );
            FileOutputStream   os  = new FileOutputStream(outputFile);
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF8");

            return(osw);
        }
Пример #18
0
        public void MergeVideos(string[] pathNames, string outputPath)
        {
            List <Movie> inMovies = new List <Movie>();
            Movie        movie    = new Movie();

            foreach (string path in pathNames)
            {
                inMovies.Add(MovieCreator.Build(path));
            }

            List <List <ITrack> > allTracks = new List <List <ITrack> >();

            for (int i = 0; i < pathNames.Length; i++)
            {
                allTracks.Add(new List <ITrack>());
            }

            for (int i = 0; i < inMovies.Count(); i++)
            {
                foreach (ITrack track in inMovies[i].Tracks)
                {
                    allTracks[i].Add(track);
                }
            }

            ITrack[] tracks = new ITrack[allTracks.Count()];
            for (int i = 0; i < allTracks[0].Count(); i++)
            {
                for (int j = 0; j < allTracks.Count(); j++)
                {
                    tracks[j] = allTracks[j][i];
                }
                movie.AddTrack(new AppendTrack(tracks));
                tracks = new ITrack[allTracks.Count()];
            }


            BasicContainer   oout = (BasicContainer) new DefaultMp4Builder().Build(movie);
            FileOutputStream fos  = new FileOutputStream(new File(outputPath));

            oout.WriteContainer(fos.Channel);
            fos.Close();
        }
        public bool SaveFile(byte[] fileData, string path)
        {
            FileOutputStream fos = null;

            try
            {
                fos = new FileOutputStream(new File(path));
                fos.Write(fileData, 0, fileData.Length);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                fos.Close();
            }
            return(true);
        }
Пример #20
0
    //Method to save document as a file in Android and view the saved document
    public void SaveAndView(string fileName, String contentType, MemoryStream stream)
    {
        Java.IO.File file = new Java.IO.File(fileName);

        //Remove if the file exists
        if (file.Exists())
        {
            file.Delete();
        }

        //Write the stream into the file
        FileOutputStream outs = new FileOutputStream(file);

        outs.Write(stream.ToArray());

        outs.Flush();
        outs.Close();

        //Invoke the created file for viewing
        if (file.Exists())
        {
            Android.Net.Uri fileUri;
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.N)
            {
                fileUri = FileProvider.GetUriForFile(Android.App.Application.Context, "com.companyname.Panda_Kakei.fileprovider", file);
            }
            else
            {
                fileUri = Android.Net.Uri.FromFile(file);
            }
            string extension    = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(fileUri.ToString());
            string mimeType     = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            Intent actionIntent = new Intent(Intent.ActionView);
            actionIntent.SetDataAndType(fileUri, mimeType);
            actionIntent.AddFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission
                                  | ActivityFlags.NewTask | ActivityFlags.MultipleTask);

            Intent chooserIntent = Intent.CreateChooser(actionIntent, "Choose App");
            chooserIntent.AddFlags(ActivityFlags.NewTask | ActivityFlags.MultipleTask);

            Android.App.Application.Context.StartActivity(chooserIntent);
        }
    }
        // You can merge any amount of movies, but some format are less stable
        public void Merge(string sourceDirectory, string movie1, string movie2, string destinationDirectory, string destinationFile)
        {
            var inMovies = new Com.Googlecode.Mp4parser.Authoring.Movie[] {
                MovieCreator.Build(Path.Combine(sourceDirectory, movie1)),
                MovieCreator.Build(Path.Combine(sourceDirectory, movie2)),
            };

            var videoTracks = new List <ITrack>();
            var audioTracks = new List <ITrack>();

            foreach (var m in inMovies)
            {
                foreach (var t in m.Tracks)
                {
                    if (t.Handler.Equals("soun"))
                    {
                        audioTracks.Add(t);
                    }
                    if (t.Handler.Equals("vide"))
                    {
                        videoTracks.Add(t);
                    }
                }
            }

            var result = new Com.Googlecode.Mp4parser.Authoring.Movie();

            if (audioTracks.Count > 0)
            {
                result.AddTrack(new AppendTrack(audioTracks.ToArray()));
            }
            if (videoTracks.Count > 0)
            {
                result.AddTrack(new AppendTrack(videoTracks.ToArray()));
            }

            var outContainer = new DefaultMp4Builder().Build(result);

            var fc = new FileOutputStream(Path.Combine(destinationDirectory, destinationFile)).Channel;

            outContainer.WriteContainer(fc);
            fc.Close();
        }
        /// <exception cref="System.IO.IOException"/>
        public BZip2PipedOutputStream(string filename, OutputStream err)
        {
            string bzip2 = Runtime.GetProperty("bzip2", "bzip2");
            string cmd   = bzip2;
            // + " > " + filename;
            //log.info("getBZip2PipedOutputStream: Running command: "+cmd);
            ProcessBuilder pb = new ProcessBuilder();

            pb.Command(cmd);
            this.process  = pb.Start();
            this.filename = filename;
            OutputStream outStream = new FileOutputStream(filename);

            errWriter  = new PrintWriter(new BufferedWriter(new OutputStreamWriter(err)));
            outGobbler = new ByteStreamGobbler("Output stream gobbler: " + cmd + " " + filename, process.GetInputStream(), outStream);
            errGobbler = new StreamGobbler(process.GetErrorStream(), errWriter);
            outGobbler.Start();
            errGobbler.Start();
        }
Пример #23
0
        void WriteAudioDataToFile()
        {
            byte[]           data         = new byte[this.bufferSize];
            var              filename     = GetTempFilename();
            FileOutputStream outputStream = null;

            try
            {
                outputStream = new FileOutputStream(filename);
            }
            catch (Exception ex)
            {
                //TODO
            }

            if (outputStream != null)
            {
                List <byte[]> list = new List <byte[]>();
                while (this.isRecording)
                {
                    this.recorder.Read(data, 0, this.bufferSize);
                    try
                    {
                        outputStream.Write(data);

                        list.Add(data);
                    }
                    catch (Exception ex)
                    {
                        //TODO
                    }
                }

                try
                {
                    outputStream.Close();
                }
                catch (Exception ex)
                {
                    //TODO
                }
            }
        }
Пример #24
0
        public bool StoreBlobStream(InputStream inputStream, BlobKey outKey)
        {
            FilePath tmp = null;

            try
            {
                tmp = FilePath.CreateTempFile(TmpFilePrefix, TmpFileExtension, new FilePath(this.path)
                                              );
                FileOutputStream fos    = new FileOutputStream(tmp);
                byte[]           buffer = new byte[65536];
                int lenRead             = inputStream.Read(buffer);
                while (lenRead > 0)
                {
                    fos.Write(buffer, 0, lenRead);
                    lenRead = inputStream.Read(buffer);
                }
                inputStream.Close();
                fos.Close();
            }
            catch (IOException e)
            {
                Log.E(Database.Tag, "Error writing blog to tmp file", e);
                return(false);
            }
            BlobKey newKey = KeyForBlobFromFile(tmp);

            outKey.SetBytes(newKey.GetBytes());
            string   path = PathForKey(outKey);
            FilePath file = new FilePath(path);

            if (file.CanRead())
            {
                // object with this hash already exists, we should delete tmp file and return true
                tmp.Delete();
                return(true);
            }
            else
            {
                // does not exist, we should rename tmp file to this name
                tmp.RenameTo(file);
            }
            return(true);
        }
Пример #25
0
        /// <exception cref="System.Exception"/>
        public virtual void TestLoadCorruptTrustStore()
        {
            string       truststoreLocation = Basedir + "/testcorrupt.jks";
            OutputStream os = new FileOutputStream(truststoreLocation);

            os.Write(1);
            os.Close();
            ReloadingX509TrustManager tm = new ReloadingX509TrustManager("jks", truststoreLocation
                                                                         , "password", 10);

            try
            {
                tm.Init();
            }
            finally
            {
                tm.Destroy();
            }
        }
        public void Mux(string videoTrackFile, string audioTrackFile, string destinationFolder, string destinationFile)
        {
            Task.Run(() => {
                var res       = System.IO.File.Exists(destinationFolder + "/" + videoTrackFile);
                var h264Track = new H264TrackImpl(new FileDataSourceImpl(Path.Combine(destinationFolder, videoTrackFile)));
                var aacTrack  = new AACTrackImpl(new FileDataSourceImpl(Path.Combine(destinationFolder, audioTrackFile)));

                var movie = new Movie();
                movie.AddTrack(h264Track);
                movie.AddTrack(aacTrack);

                var mp4builder = new DefaultMp4Builder();

                var mp4file = mp4builder.Build(movie);
                var fc      = new FileOutputStream(new Java.IO.File(Path.Combine(destinationFolder, destinationFile))).Channel;
                mp4file.WriteContainer(fc);
                fc.Close();
            });
        }
        private string CopyAudioToTemp(Audio audio)
        {
            var filepath = "";

            try
            {
                var tempMp3 = File.CreateTempFile("temp", ".mp3", CacheDir);
                tempMp3.DeleteOnExit();
                var fos = new FileOutputStream(tempMp3);
                fos.Write(audio.Data);
                fos.Close();
                filepath = tempMp3.AbsolutePath;
            }
            catch (IOException ioe)
            {
                Log.Warn(logtag, "Could not write audio to temp file, exception message:" + ioe.Message);
            }
            return(filepath);
        }
Пример #28
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            System.Diagnostics.Debug.WriteLine("DHB:MainActivity:OnActivityResult");

            if (requestCode == CAMERA_REQUEST_CODE)
            {
                //< OnActivityResult
                // Activity no longer saves the file so I have to do it.
                try {
                    /* nope.
                     * FileWriter fw = new FileWriter(file);
                     * BufferedWriter bw = new BufferedWriter(fw);
                     * char[] asChar = System.Text.Encoding.Unicode.GetString(GlobalStatusSingleton.mostRecentImgBytes).ToCharArray();
                     * //.UTF8.GetString(GlobalStatusSingleton.mostRecentImgBytes).ToCharArray();
                     * bw.Write(asChar);
                     * bw.Close(); */
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.Write(GlobalStatusSingleton.mostRecentImgBytes);
                    fos.Close();
                    System.Diagnostics.Debug.WriteLine("DHB:MainActivity:OnActivityResult should have written to: " + file.Path);
                } catch (Exception e) {
                    System.Diagnostics.Debug.WriteLine("DHB:MainActivity:OnActivityResult exception:" + e.ToString());
                }
                ((ICamera)(((IExposeCamera)(Xamarin.Forms.Application.Current as App).MainPage).getCamera())).ShowImage(file.Path, null);

                GlobalStatusSingleton.imgsTakenTracker++;
                //> OnActivityResult
            }
            else
            {
                // should be facebook...
                fbLogin.OnActivityResult(requestCode, resultCode, data);
                if (fbLogin.loginCheck())
                {
                    System.Diagnostics.Debug.WriteLine("need to figure out how to kick to app");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("epic fail");
                }
            }
        }
Пример #29
0
        void WriteAudioDataToFile()
        {
            byte[]           data         = new byte[bufferSize];
            var              filename     = GetTempFilename();
            FileOutputStream outputStream = null;


            Debug.WriteLine(filename);

            try
            {
                outputStream = new FileOutputStream(filename);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            if (outputStream != null)
            {
                while (isRecording)
                {
                    recorder.Read(data, 0, bufferSize);
                    try
                    {
                        outputStream.Write(data);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("could not record" + ex.Message);
                    }
                }

                try
                {
                    outputStream.Close();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }
Пример #30
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
                }
            }
            private void Save(byte[] bytes)
            {
                OutputStream output = null;

                try
                {
                    if (File != null)
                    {
                        output = new FileOutputStream(File);
                        output.Write(bytes);
                    }
                }
                finally {
                    if (output != null)
                    {
                        output.Close();
                    }
                }
            }
 private static void WriteTrees(string filename, IList <Tree> trees, IList <int> treeIds)
 {
     try
     {
         FileOutputStream fos  = new FileOutputStream(filename);
         BufferedWriter   bout = new BufferedWriter(new OutputStreamWriter(fos));
         foreach (int id in treeIds)
         {
             bout.Write(trees[id].ToString());
             bout.Write("\n");
         }
         bout.Flush();
         fos.Close();
     }
     catch (IOException e)
     {
         throw new RuntimeIOException(e);
     }
 }
Пример #33
0
        public static void write(FileOutputStream @this, int value, bool append)
        {
            if (_nativeData[@this].FileStream != null)
            {
                _nativeData[@this].FileStream.WriteByte((byte)value);
                return;
            }

            var cb = new[] { (char)value };

            if (@this.getFD() == FileDescriptor.@out)
            {
                System.Console.Out.Write(cb);
            }
            else if (@this.getFD() == FileDescriptor.err)
            {
                System.Console.Error.Write(cb);
            }
        }
 protected internal override RandomAccessReader CreateReader(sbyte[] bytes)
 {
     try
     {
         // Unit tests can create multiple readers in the same test, as long as they're used one after the other
         DeleteTempFile();
         _tempFile = FilePath.CreateTempFile("metadata-extractor-test-", ".tmp");
         FileOutputStream stream = new FileOutputStream(_tempFile);
         stream.Write(bytes);
         stream.Close();
         _randomAccessFile = new RandomAccessFile(_tempFile, "r");
         return(new RandomAccessFileReader(_randomAccessFile));
     }
     catch (IOException)
     {
         NUnit.Framework.Assert.Fail("Unable to create temp file");
         return(null);
     }
 }
        void WriteAudioDataToFile()
        {
            byte[]           data         = new byte[_bufferSize];
            var              filename     = GetTempFilename();
            FileOutputStream outputStream = null;

            System.Diagnostics.Debug.WriteLine(filename);

            try
            {
                outputStream = new FileOutputStream(filename);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            if (outputStream != null)
            {
                while (_isRecording)
                {
                    _recorder.Read(data, 0, _bufferSize);
                    try
                    {
                        outputStream.Write(data);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                }

                try
                {
                    outputStream.Close();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }
Пример #36
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();
        }
Пример #37
0
 public virtual void ProcessAtServer()
 {
     try
     {
         var blobImpl = ServerGetBlobImpl();
         if (blobImpl != null)
         {
             blobImpl.SetTrans(Transaction());
             var file = blobImpl.ServerFile(null, true);
             var sock = ServerMessageDispatcher().Socket();
             Ok.Write(sock);
             var fout = new FileOutputStream(file);
             Copy(sock, fout, blobImpl.GetLength(), false);
             Ok.Write(sock);
         }
     }
     catch (Exception)
     {
     }
 }
Пример #38
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"));

            }
        }
 public void Run()
 {
     ByteBuffer buffer = mImage.GetPlanes()[0].Buffer;
     byte[] bytes = new byte[buffer.Remaining()];
     buffer.Get(bytes);
     using (var output = new FileOutputStream(mFile))
     {
         try
         {
             output.Write(bytes);
         }
         catch (IOException e)
         {
             e.PrintStackTrace();
         }
         finally
         {
             mImage.Close();
         }
     }
 }
Пример #40
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();
         }
     }
     }
 }
Пример #41
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);
                });
            });
        }
Пример #42
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;
        }
			private void Save(byte[] bytes)
			{
				OutputStream output = null;
				try 
				{
					if (File != null)
					{
						output = new FileOutputStream(File);
						output.Write(bytes);
					}
				}
				finally {
					if (output != null)
						output.Close ();
				}
			}
Пример #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/
            };
        }
Пример #45
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;
        }
        private static void ProcessFile(File effDocFile, File outFile)
        {
            if (!effDocFile.exists())
            {
                throw new RuntimeException("file '" + effDocFile.GetAbsolutePath() + "' does not exist");
            }
            OutputStream os;
            try
            {
                os = new FileOutputStream(outFile);
            }
            catch (FileNotFoundException e)
            {
                throw new RuntimeException(e);
            }
            os = new SimpleAsciiOutputStream(os);
            PrintStream ps;
            try
            {
                ps = new PrintStream(os, true, "UTF-8");
            }
            catch (UnsupportedEncodingException e)
            {
                throw new RuntimeException(e);
            }

            outputLicenseHeader(ps);
            Type genClass = typeof(ExcelFileFormatDocFunctionExtractor);
            ps.println("# Created by (" + genClass.Name + ")");
            // identify the source file
            ps.print("# from source file '" + SOURCE_DOC_FILE_NAME + "'");
            ps.println(" (size=" + effDocFile.Length + ", md5=" + GetFileMD5(effDocFile) + ")");
            ps.println("#");
            ps.println("#Columns: (index, name, minParams, maxParams, returnClass, paramClasses, isVolatile, hasFootnote )");
            ps.println("");
            try
            {
                ZipFile zf = new ZipFile(effDocFile);
                InputStream is1 = zf.GetInputStream(zf.GetEntry("content.xml"));
                extractFunctionData(new FunctionDataCollector(ps), is1);
                zf.Close();
            }
            catch (ZipException e)
            {
                throw new RuntimeException(e);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            ps.Close();

            String canonicalOutputFileName;
            try
            {
                canonicalOutputFileName = outFile.GetCanonicalPath();
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            Console.WriteLine("Successfully output to '" + canonicalOutputFileName + "'");
        }
Пример #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;
        }
	    /**
	     * 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)
        	);
			
	    }
Пример #50
0
		public void get(String src, String dst,
			SftpProgressMonitor monitor, int mode)
		{
			//throws SftpException{
			src=remoteAbsolutePath(src);
			dst=localAbsolutePath(dst);
			try
			{
				Vector v=glob_remote(src);
				int vsize=v.size();
				if(vsize==0)
				{
					throw new SftpException(SSH_FX_NO_SUCH_FILE, "No such file");
				}

				File dstFile=new File(dst);
				bool isDstDir=dstFile.isDirectory();
				StringBuffer dstsb=null;
				if(isDstDir)
				{
					if(!dst.endsWith(file_separator))
					{
						dst+=file_separator;
					}
					dstsb=new StringBuffer(dst);
				}
				else if(vsize>1)
				{
					throw new SftpException(SSH_FX_FAILURE, "Copying multiple files, but destination is missing or a file.");
				}

				for(int j=0; j<vsize; j++)
				{
					String _src=(String)(v.elementAt(j));

					SftpATTRS attr=_stat(_src);
					if(attr.isDir())
					{
						throw new SftpException(SSH_FX_FAILURE, "not supported to get directory "+_src);
					} 

					String _dst=null;
					if(isDstDir)
					{
						int i=_src.lastIndexOf('/');
						if(i==-1) dstsb.append(_src);
						else dstsb.append(_src.substring(i + 1));
						_dst=dstsb.toString();
						dstsb.delete(dst.length(), _dst.length());
					}
					else
					{
						_dst=dst;
					}

					if(mode==RESUME)
					{
						long size_of_src=attr.getSize();
						long size_of_dst=new File(_dst).length();
						if(size_of_dst>size_of_src)
						{
							throw new SftpException(SSH_FX_FAILURE, "failed to resume for "+_dst);
						}
						if(size_of_dst==size_of_src)
						{
							return;
						}
					}

					if(monitor!=null)
					{
						monitor.init(SftpProgressMonitor.GET, _src, _dst, attr.getSize());
						if(mode==RESUME)
						{
							monitor.count(new File(_dst).length());
						}
					}
					FileOutputStream fos=null;
					if(mode==OVERWRITE)
					{
						fos=new FileOutputStream(_dst);
					}
					else
					{
						fos=new FileOutputStream(_dst, true); // append
					}

					//System.err.println("_get: "+_src+", "+_dst);
					_get(_src, fos, monitor, mode, new File(_dst).length());
					fos.close();
				}
			}
			catch(Exception e)
			{
				if(e is SftpException) throw (SftpException)e;
				throw new SftpException(SSH_FX_FAILURE, "");
			}
		}
Пример #51
0
        public static void saveSudokuToFile(String puzzle, String filename)
        {
            FileOutputStream FO = null;
              byte[] buffer = new byte[puzzle.length()+1];
              int i = 0;

              while (i < puzzle.length()){
            buffer[i] = (byte) puzzle.charAt(i);
            i++;
              }

              try {
            FO = new FileOutputStream(filename);
            FO.write(buffer);
            FO.close();
              } catch (IOException IOE) {
            // Well, well, well....
            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;
            }
        }
Пример #53
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();
            }
        }
 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();
 }
Пример #55
0
		private CompressionStats Compress( IGrid grid,
		                                   ICompressor compressor,
										   double[] errors,
										   string outName,
		                                   ProgressViewModel progressBar )
		{
			double[] leftBorders = new double[grid.ColumnCount];
			double[] rightBorders = new double[grid.ColumnCount];

			var qs = new IQuantization[grid.ColumnCount];
			var distrs = new IDistribution[grid.ColumnCount];

			progressBar.Status = "Quantizing columns...";

			Parallel.For( 0, grid.ColumnCount, column =>
			{
				var distr = new EmpiricalDistribution( grid, column );

				leftBorders[column] = double.MaxValue;
				rightBorders[column] = double.MinValue;

				for ( int row = 0; row < grid.RowCount; ++row )
				{
					double value = grid.GetValue( row, column );
					leftBorders[column] = leftBorders[column] < value ? leftBorders[column] : value;
					rightBorders[column] = rightBorders[column] > value ? rightBorders[column] : value;
				}

				var quantizer = new Quantizer( leftBorders[column], rightBorders[column] );
				var quantization = quantizer.Quantize( errors[column], distr );

				lock ( _lockGuard )
				{
					progressBar.Progress += 1.0 / ( grid.ColumnCount + 1 );
					distrs[column] = distr;
					qs[column] = quantization;
				}
			} );

			var quantizations = new List<IQuantization>( qs );
			var distributions = new List<IDistribution>( distrs );

			progressBar.Status = "Writing archive...";
			progressBar.Progress = ( double )grid.ColumnCount / ( grid.ColumnCount + 1 );

			ICompressionResult result;

			using ( var stream = new FileOutputStream( outName ) )
			{
				result = compressor.Compress( grid, quantizations, stream );
			}

			progressBar.Progress = 1.0;
			progressBar.TryClose( );

			return new CompressionStats
			{
				CompressionResult = result,
				Distributions = distributions,
				LeftBorders = leftBorders,
				RightBorders = rightBorders,
				Quantizations = quantizations
			};
		}
Пример #56
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();
			
		

		}
Пример #57
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));

		}
Пример #58
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 ();
		}
Пример #59
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));
              }
        }
Пример #60
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;
				}

			}