Пример #1
0
        public static void ProcessBytes(string encodedPath, string fileName)
        {
            var strByte = 0;

            using (var encodedFile = new File(encodedPath))
            {
                try
                {
                    using (var finStream = new FileInputStream(encodedFile))
                    {
                        var buffer = new byte[finStream.Available()];
                        finStream.Read(buffer, 0, finStream.Available());
                        for (var i = 0; i < buffer.Length; i++)
                        {
                            buffer[i]     ^= (byte)Mask[strByte];
                            Mask[strByte] += 0x10;
                            if (strByte < 15)
                            {
                                strByte++;
                            }
                            else
                            {
                                strByte = 0;
                            }
                        }
                        using (var writer = new FileOutputStream(DataHolder.CachePath + $"/{fileName}.mp3"))
                            writer.Write(buffer);
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine(e);
                }
            }
        }
Пример #2
0
        public static string ReadCurrentLocationFromFile()
        {
            string toreturn = "";

            try
            {
                FileInputStream input = new FileInputStream(locationFile + filename);
                try
                {
                    while (input.Available() > 0)
                    {
                        toreturn += ((char)input.Read()).ToString();
                    }
                }
                catch
                {
                    toreturn = "Found File, but can't read it.";
                }
                input.Close();
                return(toreturn);
            }
            catch (FileNotFoundException e)
            {
                toreturn = "No location saved yet";
            }
            catch (IOException e)
            {
                toreturn = "Error";
            }
            return(toreturn);
        }
Пример #3
0
        private async Task CreateCopy(Uri sourceUri, Uri destinationUri)
        {
            using (var source = new FileInputStream(ContentResolver.OpenFileDescriptor(sourceUri, "r").FileDescriptor))
            {
                using (var destination = new FileOutputStream(ContentResolver.OpenFileDescriptor(destinationUri, "w").FileDescriptor))
                {
                    byte[] content = new byte[source.Available()];
                    await source.ReadAsync(content);

                    await destination.WriteAsync(content);

                    destination.Close();
                }
            }
        }
Пример #4
0
        /**
         * 将图片转换成Base64编码
         * @param imgFile 待处理图片
         * @return
         */
        public static String GetImgStr(String imgFile)
        {
            //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
            InputStream inFile = null;

            byte[] data = null;
            //读取图片字节数组
            try
            {
                inFile = new FileInputStream(imgFile);
                data   = new byte[inFile.Available()];
                inFile.Read(data);
                inFile.Close();
            }
            catch
            { }
            return("data:image/jpeg;base64," + Convert.ToBase64String(data));
        }
Пример #5
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/
            };
        }
Пример #6
0
 /// <exception cref="System.IO.IOException"/>
 public override int Available()
 {
     return((int)Math.Min(bytesRemaining, file.Available()));
 }
            protected override string RunInBackground(params string[] @params)
            {
                for (int i = 0; i <= 2; i++)
                {
                    try
                    {
                        String sourceFileUri = MainActivity.rec_video_uri[i];

                        Java.Net.HttpURLConnection conn = null;
                        DataOutputStream           dos  = null;
                        String lineEnd = "\r\n";
                        String twoHyphens = "--";
                        String boundary = "*****";
                        int    bytesRead, bytesAvailable, bufferSize;
                        byte[] buffer;
                        int    maxBufferSize = 1 * 1024 * 1024;
                        File   sourceFile    = new File(sourceFileUri);

                        if (sourceFile.IsFile)
                        {
                            try
                            {
                                String upLoadServerUri = "http://140.114.28.134/VideoUpload/uploads/upload.php";

                                // Ppen a URL connection to the Server
                                FileInputStream fileInputStream = new FileInputStream(
                                    sourceFile);
                                Java.Net.URL url = new Java.Net.URL(upLoadServerUri);

                                // Open a HTTP connection to the URL
                                conn               = (Java.Net.HttpURLConnection)url.OpenConnection();
                                conn.DoInput       = true;  // Allow Inputs
                                conn.DoOutput      = true;  // Allow Outputs
                                conn.UseCaches     = false; // Don't use a Cached Copy
                                conn.RequestMethod = "POST";
                                conn.SetRequestProperty("Connection", "Keep-Alive");
                                conn.SetRequestProperty("ENCTYPE", "multipart/form-data");
                                conn.SetRequestProperty("Content-Type",
                                                        "multipart/form-data;boundary=" + boundary);
                                conn.SetRequestProperty("upload_name", sourceFileUri);

                                dos = new DataOutputStream(conn.OutputStream);

                                dos.WriteBytes(twoHyphens + boundary + lineEnd);
                                dos.WriteBytes("Content-Disposition: form-data; name=\"upload_name\";filename=\""
                                               + sourceFileUri + "\"" + lineEnd);

                                dos.WriteBytes(lineEnd);

                                // Create a buffer of maximum size
                                bytesAvailable = fileInputStream.Available();

                                bufferSize = Math.Min(bytesAvailable, maxBufferSize);
                                buffer     = new byte[bufferSize];

                                // Read file and write
                                bytesRead = fileInputStream.Read(buffer, 0, bufferSize);

                                while (bytesRead > 0)
                                {
                                    dos.Write(buffer, 0, bufferSize);
                                    bytesAvailable = fileInputStream.Available();
                                    bufferSize     = Math
                                                     .Min(bytesAvailable, maxBufferSize);
                                    bytesRead = fileInputStream.Read(buffer, 0,
                                                                     bufferSize);
                                }

                                // Send multipart form data necesssary after file
                                dos.WriteBytes(lineEnd);
                                dos.WriteBytes(twoHyphens + boundary + twoHyphens
                                               + lineEnd);

                                // Responses from the server (code and message)
                                serverResponseCode = conn.ResponseCode;
                                String serverResponseMessage = conn
                                                               .ResponseMessage;

                                // Close the streams
                                fileInputStream.Close();
                                dos.Flush();
                                dos.Close();
                            }
                            catch (Exception e)
                            {
                                System.Console.WriteLine(e.ToString());
                            }
                        } // End if-else block
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex.ToString());
                    }
                }
                progressDialog.Dismiss();

                return("Finished");
            }
Пример #8
0
        private bool SendFile(File file, out string response)
        {
            var result = false;

            response = "";

            try
            {
                // https://stackoverflow.com/questions/25398200/uploading-file-in-php-server-from-android-device/37953351

                HttpURLConnection conn = null;
                DataOutputStream  dos = null;
                string            lineEnd = "\r\n";
                string            twoHyphens = "--";
                string            boundary = "*****";
                int    bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int    maxBufferSize = 1 * 1024 * 1024;

                try
                {
                    // open a URL connection to the Servlet
                    FileInputStream fileInputStream = new FileInputStream(file);
                    URL             url             = new URL(UpLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection)url.OpenConnection();

                    conn.DoInput       = true;  // Allow Inputs
                    conn.DoOutput      = true;  // Allow Outputs
                    conn.UseCaches     = false; // Don't use a Cached Copy
                    conn.RequestMethod = "POST";

                    conn.AddRequestProperty("Connection", "Keep-Alive");
                    conn.AddRequestProperty("ENCTYPE", "multipart/form-data");
                    conn.AddRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                    conn.AddRequestProperty("file", file.AbsolutePath);

                    dos = new DataOutputStream(conn.OutputStream); //getOutputStream());

                    dos.WriteBytes(twoHyphens + boundary + lineEnd);
                    dos.WriteBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + file.AbsolutePath + "\"" + lineEnd);

                    dos.WriteBytes(lineEnd);

                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.Available();

                    bufferSize = Math.Min(bytesAvailable, maxBufferSize);
                    buffer     = new byte[bufferSize];

                    // read file and write it into form...
                    bytesRead = fileInputStream.Read(buffer, 0, bufferSize);

                    while (bytesRead > 0)
                    {
                        dos.Write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.Available();
                        bufferSize     = Math.Min(bytesAvailable, maxBufferSize);
                        bytesRead      = fileInputStream.Read(buffer, 0, bufferSize);
                    }

                    // send multipart form data necesssary after file
                    // data...
                    dos.WriteBytes(lineEnd);
                    dos.WriteBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                    // Responses from the server (code and message)
                    var serverResponseCode = conn.ResponseCode;


                    if (serverResponseCode == HttpStatus.Ok)
                    {
                        Log += "serverResponseCode = OK\r\n";

                        result = true;

                        var    rd = new BufferedReader(new InputStreamReader(conn.InputStream));
                        var    sb = new StringBuilder();
                        string line;

                        while ((line = rd.ReadLine()) != null)
                        {
                            sb.Append(line + '\r');
                        }

                        rd.Close();

                        response = sb.ToString();
                    }

                    // close the streams
                    fileInputStream.Close();
                    dos.Flush();
                    dos.Close();
                }
                catch (Exception e)
                {
                    Log += "1 error " + e.StackTrace + "\r\n";

                    e.PrintStackTrace();
                }
            }
            catch (Exception ex)
            {
                Log += "2 error " + ex.StackTrace + "\r\n";

                ex.PrintStackTrace();
            }

            return(result);
        }
        public virtual void TestMoreBzip2()
        {
            JobConf          jobConf = new JobConf(defaultConf);
            CompressionCodec bzip2   = new BZip2Codec();

            ReflectionUtils.SetConf(bzip2, jobConf);
            localFs.Delete(workDir, true);
            System.Console.Out.WriteLine(ColorBrMagenta + "testMoreBzip2() using non-native CBZip2InputStream (presumably)"
                                         + ColorNormal);
            // copy single-member test file to HDFS
            string fn1      = "testConcatThenCompress.txt" + bzip2.GetDefaultExtension();
            Path   fnLocal1 = new Path(Runtime.GetProperty("test.concat.data", "/tmp"), fn1);
            Path   fnHDFS1  = new Path(workDir, fn1);

            localFs.CopyFromLocalFile(fnLocal1, fnHDFS1);
            // copy multiple-member test file to HDFS
            string fn2      = "testCompressThenConcat.txt" + bzip2.GetDefaultExtension();
            Path   fnLocal2 = new Path(Runtime.GetProperty("test.concat.data", "/tmp"), fn2);
            Path   fnHDFS2  = new Path(workDir, fn2);

            localFs.CopyFromLocalFile(fnLocal2, fnHDFS2);
            FileInputFormat.SetInputPaths(jobConf, workDir);
            // here's first pair of BlockDecompressorStreams:
            FileInputStream in1 = new FileInputStream(fnLocal1.ToString());
            FileInputStream in2 = new FileInputStream(fnLocal2.ToString());

            NUnit.Framework.Assert.AreEqual("concat bytes available", 2567, in1.Available());
            NUnit.Framework.Assert.AreEqual("concat bytes available", 3056, in2.Available());

            /*
             * // FIXME
             * // The while-loop below dies at the beginning of the 2nd concatenated
             * // member (after 17 lines successfully read) with:
             * //
             * //   java.io.IOException: bad block header
             * //   at org.apache.hadoop.io.compress.bzip2.CBZip2InputStream.initBlock(
             * //   CBZip2InputStream.java:527)
             * //
             * // It is not critical to concatenated-gzip support, HADOOP-6835, so it's
             * // simply commented out for now (and HADOOP-6852 filed).  If and when the
             * // latter issue is resolved--perhaps by fixing an error here--this code
             * // should be reenabled.  Note that the doMultipleBzip2BufferSizes() test
             * // below uses the same testCompressThenConcat.txt.bz2 file but works fine.
             *
             * CompressionInputStream cin2 = bzip2.createInputStream(in2);
             * LineReader in = new LineReader(cin2);
             * Text out = new Text();
             *
             * int numBytes, totalBytes=0, lineNum=0;
             * while ((numBytes = in.readLine(out)) > 0) {
             ++lineNum;
             * totalBytes += numBytes;
             * }
             * in.close();
             * assertEquals("total uncompressed bytes in concatenated test file",
             * 5346, totalBytes);
             * assertEquals("total uncompressed lines in concatenated test file",
             * 84, lineNum);
             */
            // test CBZip2InputStream with lots of different input-buffer sizes
            DoMultipleBzip2BufferSizes(jobConf, false);
        }
        public virtual void TestBuiltInGzipDecompressor()
        {
            // NOTE:  This fails on RHEL4 with "java.io.IOException: header crc mismatch"
            //        due to buggy version of zlib (1.2.1.2) included.
            JobConf jobConf = new JobConf(defaultConf);

            jobConf.SetBoolean("io.native.lib.available", false);
            CompressionCodec gzip = new GzipCodec();

            ReflectionUtils.SetConf(gzip, jobConf);
            localFs.Delete(workDir, true);
            NUnit.Framework.Assert.AreEqual("[non-native (Java) codec]", typeof(BuiltInGzipDecompressor
                                                                                ), gzip.GetDecompressorType());
            System.Console.Out.WriteLine(ColorBrYellow + "testBuiltInGzipDecompressor() using"
                                         + " non-native (Java Inflater) Decompressor (" + gzip.GetDecompressorType() + ")"
                                         + ColorNormal);
            // copy single-member test file to HDFS
            string fn1      = "testConcatThenCompress.txt" + gzip.GetDefaultExtension();
            Path   fnLocal1 = new Path(Runtime.GetProperty("test.concat.data", "/tmp"), fn1);
            Path   fnHDFS1  = new Path(workDir, fn1);

            localFs.CopyFromLocalFile(fnLocal1, fnHDFS1);
            // copy multiple-member test file to HDFS
            // (actually in "seekable gzip" format, a la JIRA PIG-42)
            string fn2      = "testCompressThenConcat.txt" + gzip.GetDefaultExtension();
            Path   fnLocal2 = new Path(Runtime.GetProperty("test.concat.data", "/tmp"), fn2);
            Path   fnHDFS2  = new Path(workDir, fn2);

            localFs.CopyFromLocalFile(fnLocal2, fnHDFS2);
            FileInputFormat.SetInputPaths(jobConf, workDir);
            // here's first pair of DecompressorStreams:
            FileInputStream in1 = new FileInputStream(fnLocal1.ToString());
            FileInputStream in2 = new FileInputStream(fnLocal2.ToString());

            NUnit.Framework.Assert.AreEqual("concat bytes available", 2734, in1.Available());
            NUnit.Framework.Assert.AreEqual("concat bytes available", 3413, in2.Available());
            // w/hdr CRC
            CompressionInputStream cin2 = gzip.CreateInputStream(in2);
            LineReader             @in  = new LineReader(cin2);
            Text @out = new Text();
            int  numBytes;
            int  totalBytes = 0;
            int  lineNum    = 0;

            while ((numBytes = @in.ReadLine(@out)) > 0)
            {
                ++lineNum;
                totalBytes += numBytes;
            }
            @in.Close();
            NUnit.Framework.Assert.AreEqual("total uncompressed bytes in concatenated test file"
                                            , 5346, totalBytes);
            NUnit.Framework.Assert.AreEqual("total uncompressed lines in concatenated test file"
                                            , 84, lineNum);
            // test BuiltInGzipDecompressor with lots of different input-buffer sizes
            DoMultipleGzipBufferSizes(jobConf, false);
            // test GzipZlibDecompressor (native), just to be sure
            // (FIXME?  could move this call to testGzip(), but would need filename
            // setup above) (alternatively, maybe just nuke testGzip() and extend this?)
            DoMultipleGzipBufferSizes(jobConf, true);
        }
        public virtual void TestPrototypeInflaterGzip()
        {
            CompressionCodec gzip = new GzipCodec();

            // used only for file extension
            localFs.Delete(workDir, true);
            // localFs = FileSystem instance
            System.Console.Out.WriteLine(ColorBrBlue + "testPrototypeInflaterGzip() using " +
                                         "non-native/Java Inflater and manual gzip header/trailer parsing" + ColorNormal
                                         );
            // copy prebuilt (correct!) version of concat.gz to HDFS
            string fn      = "concat" + gzip.GetDefaultExtension();
            Path   fnLocal = new Path(Runtime.GetProperty("test.concat.data", "/tmp"), fn);
            Path   fnHDFS  = new Path(workDir, fn);

            localFs.CopyFromLocalFile(fnLocal, fnHDFS);
            FileInputStream @in = new FileInputStream(fnLocal.ToString());

            NUnit.Framework.Assert.AreEqual("concat bytes available", 148, @in.Available());
            // should wrap all of this header-reading stuff in a running-CRC wrapper
            // (did so in BuiltInGzipDecompressor; see below)
            byte[] compressedBuf = new byte[256];
            int    numBytesRead  = @in.Read(compressedBuf, 0, 10);

            NUnit.Framework.Assert.AreEqual("header bytes read", 10, numBytesRead);
            NUnit.Framework.Assert.AreEqual("1st byte", unchecked ((int)(0x1f)), compressedBuf
                                            [0] & unchecked ((int)(0xff)));
            NUnit.Framework.Assert.AreEqual("2nd byte", unchecked ((int)(0x8b)), compressedBuf
                                            [1] & unchecked ((int)(0xff)));
            NUnit.Framework.Assert.AreEqual("3rd byte (compression method)", 8, compressedBuf
                                            [2] & unchecked ((int)(0xff)));
            byte flags = unchecked ((byte)(compressedBuf[3] & unchecked ((int)(0xff))));

            if ((flags & unchecked ((int)(0x04))) != 0)
            {
                // FEXTRA
                numBytesRead = @in.Read(compressedBuf, 0, 2);
                NUnit.Framework.Assert.AreEqual("XLEN bytes read", 2, numBytesRead);
                int xlen = ((compressedBuf[1] << 8) | compressedBuf[0]) & unchecked ((int)(0xffff)
                                                                                     );
                @in.Skip(xlen);
            }
            if ((flags & unchecked ((int)(0x08))) != 0)
            {
                // FNAME
                while ((numBytesRead = @in.Read()) != 0)
                {
                    NUnit.Framework.Assert.IsFalse("unexpected end-of-file while reading filename", numBytesRead
                                                   == -1);
                }
            }
            if ((flags & unchecked ((int)(0x10))) != 0)
            {
                // FCOMMENT
                while ((numBytesRead = @in.Read()) != 0)
                {
                    NUnit.Framework.Assert.IsFalse("unexpected end-of-file while reading comment", numBytesRead
                                                   == -1);
                }
            }
            if ((flags & unchecked ((int)(0xe0))) != 0)
            {
                // reserved
                NUnit.Framework.Assert.IsTrue("reserved bits are set??", (flags & unchecked ((int)
                                                                                             (0xe0))) == 0);
            }
            if ((flags & unchecked ((int)(0x02))) != 0)
            {
                // FHCRC
                numBytesRead = @in.Read(compressedBuf, 0, 2);
                NUnit.Framework.Assert.AreEqual("CRC16 bytes read", 2, numBytesRead);
                int crc16 = ((compressedBuf[1] << 8) | compressedBuf[0]) & unchecked ((int)(0xffff
                                                                                            ));
            }
            // ready to go!  next bytes should be start of deflated stream, suitable
            // for Inflater
            numBytesRead = @in.Read(compressedBuf);
            // Inflater docs refer to a "dummy byte":  no clue what that's about;
            // appears to work fine without one
            byte[]   uncompressedBuf = new byte[256];
            Inflater inflater        = new Inflater(true);

            inflater.SetInput(compressedBuf, 0, numBytesRead);
            try
            {
                int    numBytesUncompressed = inflater.Inflate(uncompressedBuf);
                string outString            = Sharpen.Runtime.GetStringForBytes(uncompressedBuf, 0, numBytesUncompressed
                                                                                , "UTF-8");
                System.Console.Out.WriteLine("uncompressed data of first gzip member = [" + outString
                                             + "]");
            }
            catch (SharpZipBaseException ex)
            {
                throw new IOException(ex.Message);
            }
            @in.Close();
        }
Пример #12
0
        /// <summary>
        /// 读取配置文件
        /// </summary>
        public JSONObject ReadConfig()
        {
            lock (ConfigLocker)
            {
                JSONObject jsonObject = null;

                using (File config = new File(Settings.AppPath + "/" + GetString(Resource.String.configFile)))
                {
                    if (config.Exists())
                    {
                        try
                        {
                            using (FileInputStream fis = new FileInputStream(config))
                            {
                                int    length     = fis.Available();
                                byte[] jsonBuffer = new byte[length];
                                fis.Read(jsonBuffer);
                                using (var jsonStr = new Java.Lang.String(jsonBuffer))
                                {
                                    jsonObject = new JSONObject((string)jsonStr);
                                }
                                jsonBuffer = null;
                            }
                        }
                        catch (IOException e)
                        {
                            jsonObject = null;
                            e.PrintStackTrace();
                            System.Console.WriteLine("Parse Config IOException: " + e.Message);
                        }
                    }
                    else
                    {
                        // 配置文件不存在
                        RunOnUiThread(() =>
                        {
                            Toast.MakeText(this, "配置文件不存在!", ToastLength.Short).Show();
                        });

                        //try
                        //{
                        //    // 写入配置文件
                        //    JSONObject jsonObject = new JSONObject();
                        //    jsonObject.Put("config1", "1");
                        //    jsonObject.Put("timeStamp", "0");
                        //    string defult = jsonObject.ToString();
                        //    var stream = new System.IO.FileStream(config.Path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
                        //    var writer = new OutputStreamWriter(stream);
                        //    writer.Write(defult, 0, defult.Length);
                        //    writer.Flush();
                        //    writer.Close();
                        //}
                        //catch (IOException e)
                        //{
                        //    e.PrintStackTrace();
                        //}
                    }
                }

                return(jsonObject);
            }
        }
Пример #13
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Create your application here
            SetContentView(Resource.Layout.History);
            db = new MoodDatabase(this);

            Button MoodTime = FindViewById<Button> (Resource.Id.buttonMoodTime);
            MoodTime.Click += delegate {
                //create an intent to go to the next screen
                Intent intent = new Intent(this, typeof(MoodTime));
                StartActivity(intent);
            };

            Button MoodPeople = FindViewById<Button> (Resource.Id.buttonMoodPeople);
            MoodPeople.Click += delegate {
                //create an intent to go to the next screen
                Intent intent = new Intent(this, typeof(MoodPeople));
                StartActivity(intent);
            };

            Button ExDB = FindViewById<Button> (Resource.Id.buttonExDB);
            ExDB.Click += delegate {
                //delete current DB and fill it with an example dataset
                db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData");
                db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql);
                //we want histograms that show bad mood when you are alone and good mood when you are with people
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '07:30', 3, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '09:30', 3, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '11:30', 7, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '16:30', 1, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '20:30', 6, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '07:30', 3, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '09:30', 2, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '11:30', 7, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '16:30', 1, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '20:30', 6, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '09:30', 2, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '11:30', 7, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '13:30', 1, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '16:30', 8, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '18:30', 3, 0, 1, 1, 1023)");
                //Feedback message
                Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short);
                toast.SetGravity (GravityFlags.Center, 0, 0);
                toast.Show ();
            };

            Button BackHome = FindViewById<Button> (Resource.Id.button1);
            BackHome.Click += delegate {
                //create an intent to go to the next screen
                Intent intent = new Intent(this, typeof(Home));
                intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
                StartActivity(intent);
            };

            Button DeleteButton = FindViewById<Button> (Resource.Id.button2);
            DeleteButton.Click += delegate {
                //create an intent to go to the next screen
                db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData");
                db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql);

                //Feedback message
                Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short);
                toast.SetGravity (GravityFlags.Center, 0, 0);
                toast.Show ();

                //restart this activity in order to update the view
                Intent intent = new Intent(this, typeof(History));
                intent.SetFlags(ActivityFlags.ClearTop); //remove the history
                StartActivity(intent);
            };

            //EXPORT BUTTON TO WRITE SQLITE DB FILE TO SD CARD
            Button ExportButton = FindViewById<Button> (Resource.Id.button3);
            ExportButton.Click += delegate {

                //This is for exporting the db file
                File sd = GetExternalFilesDir(null);
                File backupDB = new File(sd, "MoodData.db"); //this is where we're going to export to
                //this is the database file
                File data = GetDatabasePath("MoodData.db");
                //Android.Widget.Toast.MakeText(this, data.AbsolutePath, Android.Widget.ToastLength.Short).Show();
                OutputStream OS = new FileOutputStream(backupDB);
                InputStream IS = new FileInputStream(data);
                //the actual copying action
                byte[] dataByte = new byte[IS.Available()];
                IS.Read(dataByte);
                OS.Write(dataByte);
                IS.Close();
                OS.Close();

                //Now try to export everything as a csv file
                Android.Database.ICursor cursor;
                cursor = db.ReadableDatabase.RawQuery("SELECT * FROM MoodData ORDER BY _id DESC", null); // cursor query
                //only write a file if there are entries in the DB
                if (cursor.Count > 0) {
                    backupDB = new File(sd, "MoodData.csv"); //this is where we're going to export to
                    OS = new FileOutputStream(backupDB);
                    //write a header in the beginning
                    string header = "date; time; mood; people; what; location; pos1; pos2; pos3; pos4; pos5; neg1; neg2; neg3; neg4; neg5\n";
                    byte[] bytes = new byte[header.Length * sizeof(char)];
                    System.Buffer.BlockCopy(header.ToCharArray(), 0, bytes, 0, bytes.Length);
                    OS.Write(bytes);

                    for (int ii = 0; ii < cursor.Count; ii++) { //go through all rows
                        cursor.MoveToPosition (ii);
                        //now go through all columns
                        for (int kk = 1; kk < cursor.ColumnCount-1; kk++) { //skip the first column since it is just the ID and the last since it's the question flags
                            //[date] TEXT NOT NULL, [time] TEXT NOT NULL, [mood] INT NOT NULL, [people] INT NOT NULL, [what] INT NOT NULL, [location] INT NOT NULL, [pos1] INT, [pos2] INT , [pos3] INT, [pos4] INT, [pos5] INT, [neg1] INT, [neg2] INT , [neg3] INT, [neg4] INT, [neg5] INT, [QuestionFlags] INT NOT NULL)";
                            //the first two columns are strings, the rest is int
                            string tempStr;
                            if (kk < 3) {
                                tempStr = cursor.GetString(kk);
                            }
                            else {
                                int tempInt = cursor.GetInt(kk);
                                tempStr = tempInt.ToString();
                            }
                            if (kk == cursor.ColumnCount-2) //if last column, advance to next line
                                tempStr += "\n";
                            else
                                tempStr += "; ";
                            //convert to byte and write
                            bytes = new byte[tempStr.Length * sizeof(char)];
                            System.Buffer.BlockCopy(tempStr.ToCharArray(), 0, bytes, 0, bytes.Length);
                            OS.Write(bytes);
                        }
                    }

                    OS.Close();

                    //Encrypt File
                    var zipTemp = new ZIPHelper();
                    zipTemp.Save(sd.AbsolutePath);
                    System.Console.WriteLine("Path: " + sd.AbsolutePath );

                    //send via email
                    var email = new Intent(Intent.ActionSend);
                    email.SetType("text/plain");
                    //email.PutExtra(Android.Content.Intent.ExtraEmail, new string[]{"*****@*****.**"});
                    email.PutExtra(Android.Content.Intent.ExtraSubject, "R-U-OK Export");
                    email.PutExtra(Android.Content.Intent.ExtraText, "Beschreibung der Datenbank Einträge :\n[mood] Stimmung 0-8, -1 wenn die Erinnerung verpasst wurde\n[people] keiner-viele, 0-2 \n[what] Freizeit-Arbeit, 0-2 \n[location] Unterwegs/Daheim, 0-1 \n[pos1-5] und [neg1-5] sind die Affekt Fragen, bewertet zwischen 1-9. Einträge mit 0 sind nicht gefragt worden. Die Frage sind folgende:\nPos1: Wie fröhlich fühlen Sie sich?\nPos2: Wie optimistisch sind Sie?\nPos3: Wie zufrieden sind Sie?\nPos4: Wie entspannt sind Sie?\nPos5: 5te Frage fehlt noch\nNeg1: Wie traurig sind Sie?\nNeg2: Wie ängstlich sind Sie?\nNeg3: Wie einsam sind Sie?\nNeg4: Wie unruhig sind Sie?\nNeg5: Wie ärgerlich sind Sie?\n" );
                    //email.PutExtra(Android.Content.Intent.ExtraStream, Android.Net.Uri.Parse("file://" + backupDB.AbsolutePath));
                    email.PutExtra(Android.Content.Intent.ExtraStream, Android.Net.Uri.Parse("file://" + sd.AbsolutePath + "//MoodData.zip"));
                    //System.Console.WriteLine(backupDB.AbsolutePath);
                    StartActivity(Intent.CreateChooser(email, "Send email..."));
                }

                //Feedback message
                Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short);
                toast.SetGravity (GravityFlags.Center, 0, 0);
                toast.Show ();

                //http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29
                //http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/
            };
        }