Exemple #1
0
 public async Task SaveData <T>(T data, string filename, string targetFolder)
 {
     try
     {
         await Task.Run(async() =>
         {
             targetFolder = string.IsNullOrEmpty(targetFolder) ? Application.Context.GetExternalFilesDir(null).Path : Path.Combine(Application.Context.GetExternalFilesDir(null).Path, targetFolder);
             var file     = new File(Path.Combine(targetFolder, filename));
             if (!file.ParentFile.Exists())
             {
                 file.ParentFile.Mkdir();
             }
             file.CreateNewFile();
             var json = JsonConvert.SerializeObject(new Tuple <DateTime, T>(DateTime.UtcNow, data));
             using (FileWriter writer = new FileWriter(file))
             {
                 await writer.WriteAsync(json);
                 writer.Close();
             }
         });
     }
     catch (Exception e)
     {
         //
     }
 }
        private void createFile(string filename, Java.IO.File extStore)
        {
            Java.IO.File file = new Java.IO.File(extStore + "/" + filename + ".aes");

            if (filename.IndexOf(".") != -1)
            {
                try
                {
                    file.CreateNewFile();
                }
                catch (Java.IO.IOException e)
                {
                    // TODO Auto-generated catch block
                    Android.Util.Log.Error("lv", e.Message);
                }
                Android.Util.Log.Error("lv", "file created");
            }
            else
            {
                file.Mkdir();
                Android.Util.Log.Error("lv", "folder created");
            }

            file.Mkdirs();
        }
Exemple #3
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);
                Java.IO.File f        = new Java.IO.File(Element.SavedImagePath);

                f.CreateNewFile();

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

                fo.Close();
            }
            else
            {
                UpdateControl(true);
            }
        }
        public async Task <bool> OpenFile(string fileName, bool forWriting)
        {
            Java.IO.File dir  = ThisContext.GetDir("songs", FileCreationMode.Private);
            Java.IO.File file = new Java.IO.File(dir, fileName);
            if (file.Exists() == false)
            {
                file.CreateNewFile();
            }
            Stream stream;

            if (forWriting)
            {
                stream       = ThisContext.OpenFileOutput(fileName, FileCreationMode.Private);
                OutputStream = new DataOutputStream(stream);
            }
            else
            {
                try
                {
                    stream      = ThisContext.OpenFileInput(fileName);
                    InputStream = new DataInputStream(stream);
                }
                catch (Java.IO.FileNotFoundException e)
                {
                    return(false);
                }
            }
            return(true);
        }
Exemple #5
0
        private static void logMsg(string text)
        {
            string path = "/storage/emulated/0/logCsharp.txt";

            Java.IO.File logFile = new Java.IO.File(path);
            //File logFile = new File("sdcard/log.file");
            if (!logFile.Exists())
            {
                try
                {
                    // logFile.Mkdir();
                    logFile.CreateNewFile();
                }
                catch (Java.IO.IOException e)
                {
                    // TODO Auto-generated catch block
                    e.PrintStackTrace();
                }
            }
            try
            {
                //BufferedWriter for performance, true to set append to file flag
                BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
                buf.Append(text);
                buf.NewLine();
                buf.Close();
            }
            catch (Java.IO.IOException e)
            {
                // TODO Auto-generated catch block
                e.PrintStackTrace();
            }
        }
Exemple #6
0
        public string Capture(string filename)
        {
            var    rootView = _currentActivity.Window.DecorView.RootView;
            string fullpath = string.Empty;

            using (var screenshot = Bitmap.CreateBitmap(
                       rootView.Width,
                       rootView.Height,
                       Bitmap.Config.Argb8888))
            {
                var canvas = new Canvas(screenshot);
                rootView.Draw(canvas);

                using (var stream = new MemoryStream())
                {
                    screenshot.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);

                    File picturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);


                    using (File bitmapFile = new File(picturesDirectory, filename))
                    {
                        bitmapFile.CreateNewFile();

                        using (FileOutputStream outputStream = new FileOutputStream(bitmapFile))
                        {
                            outputStream.Write(stream.ToArray());
                        }
                        fullpath = bitmapFile.AbsolutePath;
                    }
                    return(fullpath);
                }
            }
        }
        void ShareCurrentPhoto()
        {
            File externalCacheDir = Activity.ExternalCacheDir;

            if (externalCacheDir == null)
            {
                Toast.MakeText(Activity, "Error writing to USB/external storage.",
                               ToastLength.Short).Show();
                return;
            }

            // Prevent media scanning of the cache directory.
            File noMediaFile = new File(externalCacheDir, ".nomedia");

            try {
                noMediaFile.CreateNewFile();
            } catch (IOException e) {
            }

            // Write the bitmap to temporary storage in the external storage directory (e.g. SD card).
            // We perform the actual disk write operations on a separate thread using the
            // {@link AsyncTask} class, thus avoiding the possibility of stalling the main (UI) thread.

            File tempFile = new File(externalCacheDir, "tempfile.jpg");

            new AsyncTaskImpl(delegate(Java.Lang.Object [] parms) {
                /**
                 * Compress and write the bitmap to disk on a separate thread.
                 * @return TRUE if the write was successful, FALSE otherwise.
                 */
                try {
                    var fo = System.IO.File.OpenWrite(tempFile.AbsolutePath);
                    if (!mBitmap.Compress(Bitmap.CompressFormat.Jpeg, 60, fo))
                    {
                        Toast.MakeText(Activity, "Error writing bitmap data.", ToastLength.Short).Show();
                        return(false);
                    }
                    return(true);
                } catch (FileNotFoundException e) {
                    Toast.MakeText(Activity, "Error writing to USB/external storage.", ToastLength.Short).Show();
                    return(false);
                }
            }, delegate {
                throw new System.NotImplementedException();
            }, delegate(bool result) {
                /**
                 * After doInBackground completes (either successfully or in failure), we invoke an
                 * intent to share the photo. This code is run on the main (UI) thread.
                 */
                if (result != true)
                {
                    return;
                }

                Intent shareIntent = new Intent(Intent.ActionSend);
                shareIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(tempFile));
                shareIntent.SetType("image/jpeg");
                StartActivity(Intent.CreateChooser(shareIntent, "Share photo"));
            }).Execute();
        }
        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)
            {
            }
        }
Exemple #9
0
        public async Task <bool> SavePhotoAsync(byte[] data, string folder, string filename)
        {
            try
            {
                Java.IO.File picturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
                Java.IO.File folderDirectory   = picturesDirectory;

                if (!string.IsNullOrEmpty(folder))
                {
                    folderDirectory = new Java.IO.File(picturesDirectory, folder);
                    folderDirectory.Mkdirs();
                }

                using (Java.IO.File bitmapFile = new Java.IO.File(folderDirectory, filename))
                {
                    bitmapFile.CreateNewFile();

                    using (FileOutputStream outputStream = new FileOutputStream(bitmapFile))
                    {
                        await outputStream.WriteAsync(data);
                    }

                    // Make sure it shows up in the Photos gallery promptly.
                    MediaScannerConnection.ScanFile(Android.App.Application.Context,
                                                    new string[] { bitmapFile.Path },
                                                    new string[] { "image/png", "image/jpeg" }, null);
                }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Exemple #10
0
        public static void WritFile(string fileName, string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return;
            }
            string filePath = PATH + fileName;

            Java.IO.File file2 = new Java.IO.File(PATH);
            if (!file2.Exists())
            {
                try {
                    file2.Mkdirs();//.CreateNewFile();
                } catch (System.IO.IOException e)
                {
                }
            }

            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)
                {
                    Log.Info("create fall", ex.Message);
                }
            }
            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)
                {
                }
            }
        }
Exemple #11
0
        public static void WritFile2(string fileName, byte[] data)
        {
            if (data == null && data.Length > 0)
            {
                return;
            }
            Java.IO.File file2 = new Java.IO.File(PATH);
            if (!file2.Exists())
            {
                bool rss = file2.Mkdirs();
            }
            string filePath = PATH + fileName;

            Java.IO.File file = new Java.IO.File(filePath);
            if (!file.Exists())
            {
                try
                {
                    // String aaa=    mkdirs2(PATH);

                    file.CreateNewFile();
                    Runtime runtime = Runtime.GetRuntime();
                    runtime.Exec("chmod 0666 " + file);
                }
                catch (Java.Lang.Exception ex)
                {
                    ex.PrintStackTrace();
                }
            }
            RandomAccessFile randomAccessFile = null;

            try
            {
                randomAccessFile = new RandomAccessFile(filePath, "rw");
                randomAccessFile.Write(data);
            }
            catch (Java.Lang.Exception e)
            {
                e.PrintStackTrace();
            }
            finally
            {
                try
                {
                    if (randomAccessFile != null)
                    {
                        randomAccessFile.Close();
                    }
                }
                catch (Java.Lang.Exception e)
                {
                }
            }
        }
Exemple #12
0
        private static void logMsg(string text)
        {
            //string path = "/storage/emulated/0/logsX.txt";
            //var path1 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            //System.IO.File.Create(path);

            //Java.IO.File sdCard = Android.OS.Environment.ExternalStorageDirectory;
            //Java.IO.File dir = new Java.IO.File(sdCard.AbsolutePath);
            //dir.Mkdirs();
            //Java.IO.File file = new Java.IO.File(dir, "iootext.txt");
            //if (!file.Exists())
            //{
            //    file.CreateNewFile();
            //    file.Mkdir();
            //    FileWriter writer = new FileWriter(file);
            //    // Writes the content to the file
            //    writer.Write("");
            //    writer.Flush();
            //    writer.Close();
            //}

            string path = "/storage/emulated/0/logCsharp.txt";

            Java.IO.File logFile = new Java.IO.File(path);
            //File logFile = new File("sdcard/log.file");
            if (!logFile.Exists())
            {
                try
                {
                    // logFile.Mkdir();
                    logFile.CreateNewFile();
                }
                catch (Java.IO.IOException e)
                {
                    // TODO Auto-generated catch block
                    e.PrintStackTrace();
                }
            }
            try
            {
                //BufferedWriter for performance, true to set append to file flag
                BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
                buf.Append(text);
                buf.NewLine();
                buf.Close();
            }
            catch (Java.IO.IOException e)
            {
                // TODO Auto-generated catch block
                e.PrintStackTrace();
            }
        }
        void Toolbar_MenuItemClick(object sender, Android.Support.V7.Widget.Toolbar.MenuItemClickEventArgs e)
        {
            var x = e.Item.ItemId;

            switch (_specialTab)
            {
            case SpecialTab.TaskManager:
                ConnectionManager.Current.CurrentController.Commander.GetCommand <TaskManagerCommand> ().Refresh();
                Toast.MakeText(this, "Refreshing task list...", ToastLength.Short).Show();
                break;

            case SpecialTab.Passwords:
                ConnectionManager.Current.CurrentController.Commander.GetCommand <PasswordCommand> ().GetPasswords();
                Toast.MakeText(this, "Get passwords...", ToastLength.Short).Show();
                break;

            case SpecialTab.RemoteDesktop:
                if (e.Item.Icon == null)
                {
                    ConnectionManager.Current.CurrentController.Commander.GetCommand <RemoteDesktopCommand> ().TakeScreenshot();
                    Toast.MakeText(this, "Get screenshot...", ToastLength.Short).Show();
                }
                else
                {
                    var image = ConnectionManager.Current.CurrentController.Commander.GetCommand <RemoteDesktopCommand> ().CurrentImage;
                    if (image == null)
                    {
                        break;
                    }

                    var shareIntent = new Intent(Intent.ActionSend);
                    shareIntent.SetType("image/jpeg");
                    using (var byteStream = new MemoryStream()) {
                        image.Compress(Bitmap.CompressFormat.Jpeg, 100, byteStream);

                        var file = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "RemoteDesktop.jpg");
                        try {
                            file.CreateNewFile();
                            using (var fo = new FileOutputStream(file))
                                fo.Write(byteStream.ToArray());
                        } catch (Exception ex) {
                            Toast.MakeText(this, "Error creating temporary file: " + ex.Message, ToastLength.Short).Show();
                            break;
                        }
                        shareIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(@"file:///sdcard/RemoteDesktop.jpg"));
                    }

                    StartActivity(Intent.CreateChooser(shareIntent, "Share Image"));
                }
                break;
            }
        }
        public static bool downloadFile(string fileid)
        {
            fileByte = null;
            var filename = "";

            System.Net.ServicePointManager.Expect100Continue = false;
            string con_string = GetConnectionstring();

            using (SqlConnection conn = new SqlConnection())
            {
                SqlDataReader datareader;
                conn.ConnectionString = con_string;


                SqlCommand command = new SqlCommand("SELECT Name, Data FROM Files WHERE id ='" + fileid.ToString() + "';");
                command.Connection = conn;

                conn.Open();
                command.ExecuteNonQuery();
                datareader = command.ExecuteReader(CommandBehavior.CloseConnection);
                if (datareader.HasRows)
                {
                    while (datareader.Read())
                    {
                        filename = datareader["Name"].ToString();
                        fileByte = (byte[])datareader["Data"];
                    }
                }
                conn.Close();
            }

            var downloadLoc = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads) + "'\'" + filename;

            Java.IO.File outputFile = new Java.IO.File(downloadLoc);

            try
            {
                if (outputFile.Exists())
                {
                    outputFile.CreateNewFile();
                }
                FileOutputStream outputStream = new FileOutputStream(outputFile);
                outputStream.Write(fileByte);  //write the bytes and im done.
            } catch (Exception ex)
            {
                new AlertDialog.Builder(Android.App.Application.Context).SetTitle("Indigent App Error").SetMessage("Upload failed: " + ex.Message + "\n \nPlease try again later").SetCancelable(true).Show();
            }



            return(true);
        }
Exemple #15
0
            private async void CreatePDF2(Android.Webkit.WebView webview)
            {
                try
                {
                    // 计算webview打印需要的页数
                    int numberOfPages = await GetPDFPageCount(webview);

                    File pdfFile = new File(fileNameWithPath);
                    if (pdfFile.Exists())
                    {
                        pdfFile.Delete();
                    }
                    pdfFile.CreateNewFile();
                    descriptor = ParcelFileDescriptor.Open(pdfFile, ParcelFileMode.ReadWrite);
                    // 设置打印参数
                    var             dm         = webview.Context.Resources.DisplayMetrics;
                    var             d          = dm.Density;
                    var             dpi        = dm.DensityDpi;
                    var             height     = dm.HeightPixels;
                    var             width      = dm.WidthPixels;
                    var             xdpi       = dm.Xdpi;
                    var             ydpi       = dm.Ydpi;
                    PrintAttributes attributes = new PrintAttributes.Builder()
                                                 .SetMediaSize(MediaSize)
                                                 .SetResolution(new PrintAttributes.Resolution("id", Context.PrintService, Convert.ToInt16(xdpi), Convert.ToInt16(ydpi)))
                                                 .SetColorMode(PrintColorMode.Color)
                                                 .SetMinMargins(PrintAttributes.Margins.NoMargins)
                                                 .Build();

                    ranges = new PageRange[] { new PageRange(0, numberOfPages - 1) };
                    // 创建pdf文件缓存目录
                    // 获取需要打印的webview适配器
                    printAdapter = webview.CreatePrintDocumentAdapter("CreatePDF");
                    // 开始打印
                    printAdapter.OnStart();
                    printAdapter.OnLayout(attributes, attributes, new CancellationSignal(), GetLayoutResultCallback(this), new Bundle());
                }
                catch (Java.IO.FileNotFoundException e)
                {
                    System.Console.WriteLine(e.Message);
                }
                catch (Java.IO.IOException e)
                {
                    System.Console.WriteLine(e.Message);
                }
                catch (Java.Lang.Exception e)
                {
                    System.Console.WriteLine(e.Message);
                }
            }
        public void Save(string fileName, string contentType, MemoryStream stream, Context context)
        {
            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();
                file.CreateNewFile();
            }
            try
            {
                using (FileOutputStream outs = new FileOutputStream(file, false))
                {
                    outs.Write(stream.ToArray());
                    outs.Flush();
                    outs.Close();
                }
            }
            catch (Exception e)
            {
                exception = e.ToString();
                AlertDialog.Builder alerta = HelperMethods.setAlert(exception, this);
            }
            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);
                context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
Exemple #17
0
        public void Save(string fileName, String contentType, MemoryStream stream, Context context)
        {
            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();
                file.CreateNewFile();
            }
            try
            {
                FileOutputStream outs = new FileOutputStream(file, false);
                outs.Write(stream.ToArray());

                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                exception = e.ToString();
            }
            if (file.Exists() && contentType != "application/html")
            {
                Android.Net.Uri path      = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", 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.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                intent.SetDataAndType(path, mimeType);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
Exemple #18
0
        public async Task <string> ResizeImage(string imageArray)
        {
            try
            {
                string environmentPath = CrossCurrentActivity.Current.AppContext.ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures).AbsolutePath;
                if (Directory.Exists(environmentPath))
                {
                    Bitmap originalImage = await BitmapFactory.DecodeFileAsync(environmentPath + "/" + imageArray);

                    if (originalImage != null)
                    {
                        using (System.IO.MemoryStream stream = new MemoryStream())
                        {
                            stream.Position = 0;
                            originalImage.Compress(Bitmap.CompressFormat.Jpeg, 0, stream);
                            byte[] byteArray = stream.GetBuffer();
                            string path      = environmentPath + "/../Compress/";
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                                Java.IO.File file = new Java.IO.File(path + ".nomedia");
                                file.CreateNewFile();
                            }
                            using (var newFile = new Java.IO.File(path + imageArray))
                            {
                                newFile.CreateNewFile();
                                // TODO : Update visual studio and enable async method to write new file.
                                //await System.IO.File.WriteAllBytesAsync(newFile.Path,byteArray);
                                System.IO.File.WriteAllBytes(newFile.Path, byteArray);
                            }
                        }
                        return(imageArray);
                    }
                    else
                    {
                        return(null);
                    }
                }
                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
                return(null);
            }
        }
Exemple #19
0
        public async Task <bool> SavePhotoAsnyc(byte[] data, string folder, string filename)
        {
            try
            {
                if (ContextCompat.CheckSelfPermission(MainActivity.Instance, Manifest.Permission.WriteExternalStorage) != PermissionChecker.PermissionGranted)
                {
                    ActivityCompat.RequestPermissions(MainActivity.Instance, new string[] { Manifest.Permission.WriteExternalStorage }, 1000);
                }


                File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
                File folderDirectory;

                if (!string.IsNullOrEmpty(folder))
                {
                    folderDirectory = new File(picturesDirectory.ToString(), folder);
                    folderDirectory.Mkdirs();
                }
                else
                {
                    folderDirectory = picturesDirectory;
                }

                using (File bitmapFile = new File("/storage/emulated/0/Download", filename))
                {
                    bitmapFile.CreateNewFile();

                    using (FileStream outputStream = new FileStream(bitmapFile.ToString(), FileMode.Open))
                    {
                        await outputStream.WriteAsync(data);
                    }

                    // Make sure it shows up in the Photos gallery promptly.
                    MediaScannerConnection.ScanFile(MainActivity.Instance,
                                                    new string[] { bitmapFile.Path },
                                                    new string[] { "image/png", "image/jpeg" }, null);
                }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Exemple #20
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)
                {
                }
            }
        }
Exemple #21
0
        //static {
        //init();
        //    }

        /**
         * Inits the.
         */
        public static void init()
        {
            //        DEBUG = false;
            //        INFO = false;
            //        WARN = false;
            //        ERROR = false;

            if (initialized)
            {
                return;
            }

            DEBUG = (LOGCAT_LEVEL <= LOG_LEVEL_DEBUG);
            INFO  = (LOGCAT_LEVEL <= LOG_LEVEL_INFO);
            WARN  = (LOGCAT_LEVEL <= LOG_LEVEL_WARN);
            ERROR = (LOGCAT_LEVEL <= LOG_LEVEL_ERROR);

            try
            {
                Java.IO.File sdRoot = getSDRootFile();
                if (sdRoot != null)
                {
                    Java.IO.File logFile = new Java.IO.File(sdRoot, LOG_FILE_NAME);
                    if (!logFile.Exists())
                    {
                        logFile.CreateNewFile();
                    }

                    Log.Debug(LOG_TAG_STRING, TAG + " : Log to file : " + logFile);
                    if (logStream != null)
                    {
                        logStream.Close();
                    }
                    FileStream file = new FileStream(logFile.Path, FileMode.Open);
                    logStream   = new PrintStream(file, true);
                    initialized = true;
                }
                logFileChannel = getFileLock();
            }
            catch (Java.Lang.Exception e)
            {
                Log.Error(LOG_TAG_STRING, "init log stream failed", e);
            }
        }
Exemple #22
0
        private void writeInStorage(String fileName, String TEXT)
        {
            bool    test;
            Context sContext = Android.App.Application.Context;

            try
            {
                Java.IO.File dirv = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath + "/AndroidTest/" + fileName + ".txt");
                Java.IO.File path = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath + "/AndroidTest");;
                if (!path.Exists())
                {
                    path.Mkdirs();
                }
                //Java.IO.File dirv = new Java.IO.File("/storage/emulated/AndroidTest");
                if (!dirv.Exists())//工作目录是否存在?
                {
                    test = dirv.CreateNewFile();
                }

                FileStream fileOS = new FileStream(dirv.ToString(), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                //String str = "this is a test about Write SD card file";
                Java.IO.BufferedWriter buf1 = new Java.IO.BufferedWriter(new Java.IO.OutputStreamWriter(fileOS));
                buf1.Write(TEXT, 0, TEXT.Length);
                buf1.Flush();
                buf1.Close();
                fileOS.Close();

                Toast.MakeText(sContext, "写入完成", ToastLength.Short).Show();
            }
            catch (Java.IO.FileNotFoundException e)
            {
                Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show();
            }
            catch (UnsupportedEncodingException e)
            {
                Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show();
            }
            catch (Java.IO.IOException e)
            {
                Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show();
            }
        }
Exemple #23
0
            /// <summary>
            /// 创建一个文件或文件夹并返回是否创建成功。如果文件已经存在,则直接返回false。
            /// </summary>
            /// <param name="path">路径</param>
            /// <returns></returns>
            public static bool Create(string path)
            {
                var f = new Java.IO.File(path);

                if (path.EndsWith(Java.IO.File.Separator))
                {
                    return(f.Mkdir());
                }
                else
                {
                    try
                    {
                        return(f.CreateNewFile());
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
            }
Exemple #24
0
        void the_proper_save(Android.Graphics.Bitmap bit)
        {
            Java.IO.File fil = new Java.IO.File(path_file);

            if (!fil.Exists())
            {
                fil.Mkdir();
            }

            string cur_time_milisec = System.DateTime.Now.Millisecond.ToString();
            string cur_time_sec     = System.DateTime.Now.Second.ToString();

            File ceva = new Java.IO.File(path_file, "image" + cur_time_milisec + cur_time_sec + ".jpg");

            if (!ceva.Exists())
            {
                ceva.CreateNewFile();
            }


            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            bit.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
            byte[] byte_array = stream.ToArray();

            if (ceva != null)
            {
                FileOutputStream outstream = new FileOutputStream(ceva);


                outstream.Write(byte_array);
                outstream.Flush();
                outstream.Close();
            }

            Intent intent = new Intent(this, typeof(CameraSurface));

            StartActivity(intent);

            Finish();
        }
Exemple #25
0
        private void CopyDatabaseFile(string dbPath)
        {
            var destPath = System.IO.Path.Combine(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath, "database.db");

            // Destination
            var destFile = new Java.IO.File(destPath);
            var canWrite = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).CreateNewFile();
            var canRead  = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).CanRead();

            if (!destFile.Exists())
            {
                try
                {
                    var result = destFile.CanWrite();
                    destFile.CreateNewFile();
                }
                catch (Java.IO.IOException ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Error Message: {ex.Message}");
                    System.Diagnostics.Debug.WriteLine($"Error Source: {ex.Source}");
                }
            }
        }
Exemple #26
0
    public async Task onPictureTakeAsync(byte[] data, Camera camera)
    {
            /*ContextWrapper cw = new ContextWrapper(ApplicationContext);
            imageFileFolder = cw.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures);

            Calendar c = Calendar.Instance;
            imageFileName = new Java.IO.File(imageFileFolder, c.Time.Seconds + ".bmp");
            imageFileName.CreateNewFile();

            using (var os = new FileStream(imageFileName.AbsolutePath, FileMode.Create))
            {
                os.Write(data, 0, data.Length);
            }
            */
            TesseractApi tesseractApi = new TesseractApi(ApplicationContext, AssetsDeployment.OncePerInitialization);
            if (!tesseractApi.Initialized)
                await tesseractApi.Init("eng");
            var tessResult = await tesseractApi.SetImage(data);
            if (tessResult)
            {
                var a = tesseractApi.Text;
                var b = a;
            }

            Bitmap cameraBitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length);
            int wid = cameraBitmap.Width;
            int hgt = cameraBitmap.Height;

            Bitmap resultImage = Bitmap.CreateBitmap(wid, hgt, Bitmap.Config.Argb8888);
            Canvas canvas = new Canvas(resultImage);
            canvas.DrawBitmap(cameraBitmap, 0f, 0f, null);

            image.DrawingCacheEnabled = true;
            image.Measure(MeasureSpec.MakeMeasureSpec(300, MeasureSpecMode.Exactly),
                          MeasureSpec.MakeMeasureSpec(300, MeasureSpecMode.Exactly));
            image.Layout(0, 0, image.MeasuredWidth, image.MeasuredHeight);
            image.BuildDrawingCache(true);
            Bitmap layoutBitmap = Bitmap.CreateBitmap(image.DrawingCache);
            image.DrawingCacheEnabled = false;
            canvas.DrawBitmap(layoutBitmap, 80f, 0f, null);

            ContextWrapper cw = new ContextWrapper(ApplicationContext);
            imageFileFolder = cw.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures);

            imageFileName = new Java.IO.File(imageFileFolder, DateTime.Now.Ticks.ToString() + ".jpg");
            imageFileName.CreateNewFile();

            try
            {
                using (var os = new FileStream(imageFileName.AbsolutePath, FileMode.Create))
                {
                    resultImage.Compress(Bitmap.CompressFormat.Jpeg, 95, os);
                }
            }
            catch (Exception e)
            {
                Log.Debug("In Saving File", e + "");
            }

            dialog.Dismiss();

            var activity = new Intent(this, typeof(ImageActivity));

            activity.PutExtra("AbsolutePath", imageFileName.AbsolutePath);
            StartActivity(activity);
            Finish();
            //StartActivity(typeof(ImageActivity));
        }
Exemple #27
0
        public async void RecordSelected(object sender, PositionSelectedEventArgs e)
        {
            var cvc  = sender as CarouselViewControl;
            var item = cvc.ItemsSource.GetItem(e.NewValue) as Record;

            if (item.IsDownloaded)
            {
            }
            else
            {
                var httpConnectorDesc = new HTTPConector();
                httpConnectorDesc.Address = $"record/description";
                var contentDesc = new
                {
                    Id       = item.Id,
                    IsPublic = true
                };
                httpConnectorDesc.Content = ("Record", contentDesc);
                var respDesc = string.Empty;
                try
                {
                    respDesc = await httpConnectorDesc.SendAsync <UserMiniSerializer>();
                }
                catch (Exception ex)
                {
                    return;
                }
                var respRec = JsonSerializer.Deserialize <Record>(respDesc, new JsonSerializerOptions {
                    PropertyNameCaseInsensitive = true
                });
                item.Description  = respRec.Description;
                item.IsDownloaded = true;
            }
            var httpConnector = new HTTPConector();

            httpConnector.Address = $"record/listen";
            var content = new
            {
                Id       = item.Id,
                IsPublic = true
            };

            httpConnector.Content = ("Record", content);
            var resp = string.Empty;

            try
            {
                resp = await httpConnector.SendAsync <UserMiniSerializer>(true);
            }
            catch (Exception ex)
            {
                return;
            }
            //var path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, item.Id.ToString() + ".wav");
            //if (System.IO.File.Exists(path))
            //	System.IO.File.Delete(path);
            //var file = System.IO.File.Create(path);
            //var ar = await httpConnector.Response.Content.ReadAsByteArrayAsync();
            //await file.WriteAsync(ar, 0, ar.Length);
            //file.Close();
            ////file.Seek(0, SeekOrigin.Begin);
            ///
            if (Device.RuntimePlatform == Device.Android)
            {
                var path = Path.Combine(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryMusic).AbsolutePath, "123.wav");
                var f    = new File(path);
                if (f.Exists())
                {
                    f.Delete();
                }
                f.CreateNewFile();
                var fd = new Java.IO.FileWriter(f);
                //{
                var bytes = await httpConnector.Response.Content.ReadAsByteArrayAsync();

                var chars = System.Text.Encoding.ASCII.GetChars(bytes);
                fd.Write(chars, 0, chars.Length);
                //}
                IMediaItem media = new MediaItem();
                await MediaManager.CrossMediaManager.Current.Play(new FileInfo(f.AbsolutePath));



                //MediaPlayer mp = new MediaPlayer();

                //var mp = new MediaPlayer();
                //mp.SetDataSource(f.AbsolutePath);

                //mp.
                //mp.Prepared += (sender, args) =>
                //{
                //	mp.Start();
                //};

                //mp.PrepareAsync();
                //Player.Play();
            }
            else
            {
                Player.Load(await httpConnector.Response.Content.ReadAsStreamAsync());
                Player.Play();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="mirrorNames"></param>
        /// <param name="mirrorUrls"></param>
        /// <param name="mirror"></param>
        /// <param name="title"></param>
        /// <param name="path">FULL PATH</param>
        /// <param name="poster"></param>
        /// <param name="fileName"></param>
        /// <param name="beforeTxt"></param>
        /// <param name="openWhenDone"></param>
        /// <param name="showNotificaion"></param>
        /// <param name="showDoneNotificaion"></param>
        /// <param name="showDoneAsToast"></param>
        /// <param name="resumeIntent"></param>
        public static void HandleIntent(int id, List <BasicMirrorInfo> mirrors, int mirror, string title, string path, string poster, string beforeTxt, bool openWhenDone, bool showNotificaion, bool showDoneNotificaion, bool showDoneAsToast, bool resumeIntent)
        {
            const int UPDATE_TIME = 1;

            try {
                isStartProgress[id] = true;
                print("START DLOAD::: " + id);
                if (isPaused.ContainsKey(id))
                {
                    //if (isPaused[id] == 2) {
                    //  isPaused.Remove(id);
                    //    print("YEET DELETED KEEEE");
                    return;
                    //  }
                }
                var context = Application.Context;

                //$"{nameof(id)}={id}|||{nameof(title)}={title}|||{nameof(path)}={path}|||{nameof(poster)}={poster}|||{nameof(fileName)}={fileName}|||{nameof(beforeTxt)}={beforeTxt}|||{nameof(openWhenDone)}={openWhenDone}|||{nameof(showDoneNotificaion)}={showDoneNotificaion}|||{nameof(showDoneAsToast)}={showDoneAsToast}|||");

                int progress = 0;

                int bytesPerSec = 0;

                void UpdateDloadNot(string progressTxt)
                {
                    //poster != ""
                    if (!isPaused.ContainsKey(id))
                    {
                        isPaused[id] = 0;
                    }
                    try {
                        int  isPause  = isPaused[id];
                        bool canPause = isPause == 0;
                        if (isPause != 2)
                        {
                            ShowLocalNot(new LocalNot()
                            {
                                actions = new List <LocalAction>()
                                {
                                    new LocalAction()
                                    {
                                        action = $"handleDownload|||id={id}|||dType={(canPause ? 1 : 0)}|||", name = canPause ? "Pause" : "Resume"
                                    }, new LocalAction()
                                    {
                                        action = $"handleDownload|||id={id}|||dType=2|||", name = "Stop"
                                    }
                                }, mediaStyle = false, bigIcon = poster, title = $"{title} - {ConvertBytesToAny(bytesPerSec / UPDATE_TIME, 2, 2)} MB/s", autoCancel = false, showWhen = false, onGoing = canPause, id = id, smallIcon = PublicNot, progress = progress, body = progressTxt
                            }, context);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   //canPause
                        }
                    }
                    catch (Exception _ex) {
                        print("ERRORLOADING PROGRESS:::" + _ex);
                    }
                }

                void ShowDone(bool succ, string overrideText = null)
                {
                    print("DAAAAAAAAAASHOW DONE" + succ);
                    if (succ)
                    {
                        App.RemoveKey(DOWNLOAD_KEY, id.ToString());
                        App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString());
                    }
                    if (showDoneNotificaion)
                    {
                        print("DAAAAAAAAAASHOW DONE!!!!");
                        Device.BeginInvokeOnMainThread(() => {
                            try {
                                print("DAAAAAAAAAASHOW DONE222");
                                ShowLocalNot(new LocalNot()
                                {
                                    mediaStyle = poster != "", bigIcon = poster, title = title, autoCancel = true, onGoing = false, id = id, smallIcon = PublicNot, body = overrideText ?? (succ ? "Download done!" : "Download Failed")
                                }, context);                                                                                                                                                                                                                                                                    // ((e.Cancelled || e.Error != null) ? "Download Failed!"
                            }
                            catch (Exception _ex) {
                                print("SUPERFATALEX: " + _ex);
                            }
                        });
                        //await Task.Delay(1000); // 100% sure that it is downloaded
                        OnSomeDownloadFinished?.Invoke(null, EventArgs.Empty);
                    }
                    else
                    {
                        print("DONT SHOW WHEN DONE");
                    }
                    // Toast.MakeText(context, "PG DONE!!!", ToastLength.Long).Show();
                }



                void StartT()
                {
                    isStartProgress[id] = true;
                    if (isPaused.ContainsKey(id))
                    {
                        //if (isPaused[id] == 2) {
                        //    isPaused.Remove(id);
                        return;
                        //  }
                    }

                    Thread t = new Thread(() => {
                        print("START:::");
                        string json = JsonConvert.SerializeObject(new DownloadHandleNot()
                        {
                            id = id, mirrors = mirrors, showDoneAsToast = showDoneAsToast, openWhenDone = openWhenDone, showDoneNotificaion = showDoneNotificaion, beforeTxt = beforeTxt, mirror = mirror, path = path, poster = poster, showNotificaion = showNotificaion, title = title
                        });

                        App.SetKey(DOWNLOAD_KEY_INTENT, id.ToString(), json);

                        var mirr = mirrors[mirror];

                        string url     = mirr.mirror;
                        string urlName = mirr.name;
                        string referer = mirr.referer ?? "";
                        bool isM3u8    = url.Contains(".m3u8");

                        if ((int)Android.OS.Build.VERSION.SdkInt > 9)
                        {
                            StrictMode.ThreadPolicy policy = new
                                                             StrictMode.ThreadPolicy.Builder().PermitAll().Build();
                            StrictMode.SetThreadPolicy(policy);
                        }
                        long total     = 0;
                        int fileLength = 0;

                        void UpdateProgress()
                        {
                            UpdateDloadNot($"{beforeTxt.Replace("{name}", urlName)}{progress} % ({ConvertBytesToAny(total, 1, 2)} MB/{ConvertBytesToAny(fileLength, 1, 2)} MB)");
                        }

                        void UpdateFromId(object sender, int _id)
                        {
                            if (_id == id)
                            {
                                UpdateProgress();
                            }
                        }

                        bool removeKeys = true;
                        var rFile       = new Java.IO.File(path);

                        try {
                            // CREATED DIRECTORY IF NEEDED
                            try {
                                Java.IO.File __file = new Java.IO.File(path);
                                __file.Mkdirs();
                            }
                            catch (Exception _ex) {
                                print("FAILED:::" + _ex);
                            }

                            URL _url = new URL(url);

                            URLConnection connection = _url.OpenConnection();

                            print("SET CONNECT ::");
                            if (!rFile.Exists())
                            {
                                print("FILE DOSENT EXITS");
                                rFile.CreateNewFile();
                            }
                            else
                            {
                                if (resumeIntent)
                                {
                                    total = rFile.Length();
                                    connection.SetRequestProperty("Range", "bytes=" + rFile.Length() + "-");
                                }
                                else
                                {
                                    rFile.Delete();
                                    rFile.CreateNewFile();
                                }
                            }
                            print("SET CONNECT ::2");
                            connection.SetRequestProperty("Accept-Encoding", "identity");
                            if (referer != "")
                            {
                                connection.SetRequestProperty("Referer", referer);
                            }
                            int clen = 0;

                            if (isM3u8)
                            {
                                clen = 1;
                            }
                            else
                            {
                                bool Completed = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(10000), () => {
                                    connection.Connect();
                                    clen = connection.ContentLength;
                                    if (clen < 5000000 && !path.Contains("/YouTube/"))                                       // min of 5 MB
                                    {
                                        clen = 0;
                                    }
                                });
                                if (!Completed)
                                {
                                    print("FAILED MASS");
                                    clen = 0;
                                }
                                print("SET CONNECT ::3");
                            }

                            print("TOTALLLLL::: " + clen);

                            if (clen == 0)
                            {
                                if (isStartProgress.ContainsKey(id))
                                {
                                    isStartProgress.Remove(id);
                                }
                                if (mirror < mirrors.Count - 1 && progress < 2 && rFile.Length() < 1000000)                                   // HAVE MIRRORS LEFT
                                {
                                    mirror++;
                                    removeKeys   = false;
                                    resumeIntent = false;
                                    rFile.Delete();

                                    print("DELETE;;;");
                                }
                                else
                                {
                                    ShowDone(false);
                                }
                            }
                            else
                            {
                                fileLength = clen + (int)total;
                                print("FILELEN:::: " + fileLength);
                                App.SetKey("dlength", "id" + id, fileLength);
                                string fileExtension = MimeTypeMap.GetFileExtensionFromUrl(url);
                                InputStream input    = new BufferedInputStream(connection.InputStream);

                                //long skip = App.GetKey<long>(DOWNLOAD_KEY, id.ToString(), 0);

                                OutputStream output = new FileOutputStream(rFile, true);

                                outputStreams[id] = output;
                                inputStreams[id]  = input;

                                if (isPaused.ContainsKey(id))
                                {
                                    //if (isPaused[id] == 2) {
                                    //    isPaused.Remove(id);
                                    return;
                                    //  }
                                }

                                isPaused[id] = 0;
                                activeIds.Add(id);

                                int m3u8Progress = 0;

                                int cProgress()
                                {
                                    if (isM3u8)
                                    {
                                        return(m3u8Progress);
                                    }
                                    return((int)(total * 100 / fileLength));
                                }
                                progress = cProgress();

                                byte[] data = new byte[1024];
                                // skip;
                                int count;
                                int previousProgress = 0;
                                UpdateDloadNot(total == 0 ? "Download starting" : "Download resuming");

                                System.DateTime lastUpdateTime = System.DateTime.Now;
                                long lastTotal = total;

                                changedPause += UpdateFromId;

                                if (isStartProgress.ContainsKey(id))
                                {
                                    isStartProgress.Remove(id);
                                }
                                bool showDone = true;

                                bool WriteDataUpdate()
                                {
                                    progressDownloads[id] = total;
                                    progress = cProgress();

                                    if (isPaused[id] == 1)
                                    {
                                        print("PAUSEDOWNLOAD");
                                        UpdateProgress();
                                        while (isPaused[id] == 1)
                                        {
                                            Thread.Sleep(100);
                                        }
                                        if (isPaused[id] != 2)
                                        {
                                            UpdateProgress();
                                        }
                                    }
                                    if (isPaused[id] == 2)                                       // DELETE FILE
                                    {
                                        print("DOWNLOAD STOPPED");
                                        ShowDone(false, "Download Stopped");
                                        output.Flush();
                                        output.Close();
                                        input.Close();
                                        outputStreams.Remove(id);
                                        inputStreams.Remove(id);
                                        isPaused.Remove(id);
                                        rFile.Delete();
                                        App.RemoveKey(DOWNLOAD_KEY, id.ToString());
                                        App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString());
                                        App.RemoveKey(App.hasDownloadedFolder, id.ToString());
                                        App.RemoveKey("dlength", "id" + id);
                                        App.RemoveKey("DownloadIds", id.ToString());
                                        changedPause -= UpdateFromId;
                                        activeIds.Remove(id);
                                        removeKeys = true;
                                        OnSomeDownloadFailed?.Invoke(null, EventArgs.Empty);
                                        Thread.Sleep(100);
                                        return(true);
                                    }

                                    if (DateTime.Now.Subtract(lastUpdateTime).TotalSeconds > UPDATE_TIME)
                                    {
                                        lastUpdateTime = DateTime.Now;
                                        long diff      = total - lastTotal;
                                        //  UpdateDloadNot($"{ConvertBytesToAny(diff/UPDATE_TIME, 2,2)}MB/s | {progress}%");
                                        //{ConvertBytesToAny(diff / UPDATE_TIME, 2, 2)}MB/s |
                                        if (progress >= 100)
                                        {
                                            print("DLOADPG DONE!");
                                            ShowDone(true);
                                        }
                                        else
                                        {
                                            UpdateProgress();
                                            // UpdateDloadNot(progress + "%");
                                        }
                                        bytesPerSec = 0;

                                        lastTotal = total;
                                    }

                                    if (progress >= 100 || progress > previousProgress)
                                    {
                                        // Only post progress event if we've made progress.
                                        previousProgress = progress;
                                        if (progress >= 100)
                                        {
                                            print("DLOADPG DONE!");
                                            ShowDone(true);
                                            showDone = false;
                                        }
                                        else
                                        {
                                            // UpdateProgress();
                                            // UpdateDloadNot(progress + "%");
                                        }
                                    }
                                    return(false);
                                }


                                void OnError()
                                {
                                    showDone = false;
                                    ShowDone(false, "Download Failed");
                                }

                                if (isM3u8)
                                {
                                    var links   = ParseM3u8(url, referer);
                                    int counter = 0;
                                    byte[] buffer;
                                    try {
                                        while ((buffer = CloudStreamCore.DownloadByteArrayFromUrl(links[counter], referer)) != null)
                                        {
                                            counter++;
                                            m3u8Progress = counter * 100 / links.Length;
                                            count        = buffer.Length;
                                            total       += count;
                                            bytesPerSec += count;
                                            output.Write(buffer, 0, count);
                                            if (WriteDataUpdate())
                                            {
                                                return;
                                            }
                                        }
                                    }
                                    catch (Exception) {
                                        OnError();
                                    }
                                }
                                else
                                {
                                    try {
                                        while ((count = input.Read(data)) != -1)
                                        {
                                            total       += count;
                                            bytesPerSec += count;

                                            output.Write(data, 0, count);
                                            if (WriteDataUpdate())
                                            {
                                                return;
                                            }
                                        }
                                    }
                                    catch (Exception) {
                                        OnError();
                                    }
                                }

                                if (showDone)
                                {
                                    ShowDone(true);
                                }
                                output.Flush();
                                output.Close();
                                input.Close();
                                outputStreams.Remove(id);
                                inputStreams.Remove(id);
                                activeIds.Remove(id);
                            }
                        }
                        catch (Exception _ex) {
                            print("DOWNLOADURL: " + url);
                            print("DOWNLOAD FAILED BC: " + _ex);
                            if (mirror < mirrors.Count - 1 && progress < 2)                               // HAVE MIRRORS LEFT
                            {
                                mirror++;
                                removeKeys   = false;
                                resumeIntent = false;
                                rFile.Delete();
                            }
                            else
                            {
                                ShowDone(false);
                            }
                        }
                        finally {
                            changedPause -= UpdateFromId;
                            isPaused.Remove(id);
                            if (isStartProgress.ContainsKey(id))
                            {
                                isStartProgress.Remove(id);
                            }
                            if (removeKeys)
                            {
                                //App.RemoveKey(DOWNLOAD_KEY, id.ToString());
                                //App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString());
                            }
                            else
                            {
                                StartT();
                            }
                        }
                    });

                    t.Start();
                }
                StartT();
            }
            catch (Exception) {
            }
        }
Exemple #29
0
        public override void OnCreate()
        {
            base.OnCreate ();

                AndroidEnvironment.UnhandledExceptionRaiser += MyApp_UnhandledExceptionHandler;

                TapGlobal tapglobal = new TapGlobal (this);
                taputil= new TapUtil (this);
                GlobalVariable staticvalue = new GlobalVariable ();
                networknamager = new NetworkManager ();
                imagemanager = new ImageManager ();
                debugreport = new DebugReport (this);

                string databasename="tap5050seller.db";
                string path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Tap5050/";
                Java.IO.File basefile = new Java.IO.File (global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath+"/Tap5050/");

                Java.IO.File internalbasefile = new Java.IO.File (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal));
                string appinternalpath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
                var personalpath=appinternalpath+databasename;

                bool success = true;
                if (!internalbasefile.Exists()){
                    success=internalbasefile.Mkdirs();
                    Java.IO.File file =new Java.IO.File(personalpath);
                    file.CreateNewFile ();
                }

                if (success){
                    databasemanager = new DatabaseManager (personalpath);
                }

                INSTANCE = this;
        }
Exemple #30
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;
        }
        public static async void InLogFiles(Type type, Exception exception)
        {
            string pathCurrentFolder = String.Empty;
            string pathCurrentFile   = String.Empty;

            settings = Settings.Instance;

            try
            {
                if (settings.IsLogErrorStorage == true)
                {
                    TypeInfo typeInfo = type.GetTypeInfo();

                    TypeAttributes typeAttributes = typeInfo.Attributes;
                    object[]       attributes     = typeInfo.GetCustomAttributes(true);

                    if (attributes != null)
                    {
                        foreach (var item in attributes)
                        {
                            if (item.ToString() == (typeof(LogRuntimeAttribute)).FullName)
                            {
                                LogRuntimeAttribute logRun = (LogRuntimeAttribute)item;

                                pathCurrentFolder = logRun.PathFolder;
                                pathCurrentFile   = logRun.PathFile;

                                break;
                            }
                        }
                    }


                    PermissionStatus status = await Permissions.CheckStatusAsync <Permissions.StorageWrite>();

                    if (status == PermissionStatus.Granted)
                    {
                        if (pathCurrentFile != String.Empty)
                        {
                            Java.IO.File file = new Java.IO.File(pathCurrentFolder);

                            file.Mkdir();

                            file = new Java.IO.File(pathCurrentFile);
                            file.CreateNewFile();

                            FileWriter writer = new FileWriter(file);

                            writer.Write(exception.ToString());
                            writer.Flush();


                            file.Dispose();
                            writer.Close();
                            writer.Dispose();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
            }
            finally { }
        }
        public void Save(string fileName, String contentType, MemoryStream stream , Context context)
        {
            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();
                file.CreateNewFile();
            }
            try
            {
                FileOutputStream outs = new FileOutputStream(file, false);
                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);
                context.StartActivity(Intent.CreateChooser(intent, "Choose App"));

            }
        }
Exemple #33
0
        public bool downloadFile(string fileid)
        {
            fileByte = null;
            var filename = "";

            System.Net.ServicePointManager.Expect100Continue = false;
            string con_string = SQL_Functions.GetConnectionstring();

            using (SqlConnection conn = new SqlConnection())
            {
                SqlDataReader datareader;
                conn.ConnectionString = con_string;


                SqlCommand command = new SqlCommand("SELECT Name, Data FROM Files WHERE id ='" + fileid.ToString() + "';");
                command.Connection = conn;

                conn.Open();
                command.ExecuteNonQuery();
                datareader = command.ExecuteReader(CommandBehavior.CloseConnection);
                if (datareader.HasRows)
                {
                    while (datareader.Read())
                    {
                        filename = datareader["Name"].ToString();
                        fileByte = (byte[])datareader["Data"];
                    }
                }
                conn.Close();
            }

            var downloadLoc = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads) + "'\'" + filename;

            Java.IO.File outputFile = new Java.IO.File(downloadLoc);

            try
            {
                if (outputFile.Exists())
                {
                    outputFile.CreateNewFile();
                }
                FileOutputStream outputStream = new FileOutputStream(outputFile);
                outputStream.Write(fileByte);  //write the bytes and im done.

                var localImage = new Java.IO.File(downloadLoc);
                if (localImage.Exists())
                {
                    global::Android.Net.Uri uri = global::Android.Net.Uri.FromFile(localImage);

                    var intent = new Intent(Intent.ActionView, uri);

                    intent.SetAction(Intent.ActionView);
                    //  intent.SetType ("application/pdf");
                    try
                    {
                        intent.SetData(global::Android.Net.Uri.FromFile(localImage));
                        intent.AddFlags(ActivityFlags.NewTask);
                        Android.App.Application.Context.StartActivity(intent);
                    }
                    catch (Exception e)
                    {
                        var msg = e.Message;
                        Toast.MakeText(_context, "Please open the file from the root : " + downloadLoc, ToastLength.Long).Show();
                    }
                }
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(_context).SetTitle("Indigent App Error").SetMessage("Upload failed: " + ex.Message + "\n \nPlease try again later").SetCancelable(true).Show();
            }



            return(true);
        }