Ejemplo n.º 1
0
        private void Download_Load(object sender, EventArgs e)
        {
            if (this.saveFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                this.Close();
                return;
            }

            this.FileStream = new FileStream(this.saveFileDialog1.FileName, FileMode.Create, FileAccess.Write);
            this.Writer     = new BinaryWriter(this.FileStream);

            var req = WebRequest.Create("https://content.dropboxapi.com/2/files/download");

            req.Method = "POST";

            req.Headers.Add(HttpRequestHeader.Authorization, String.Format("Bearer {0}", Properties.Settings.Default.AccessToken));
            req.Headers.Add("Dropbox-API-Arg", UniValue.Create(new { path = this.FilePath }).ToString());

            req.BeginGetResponse(result =>
            {
                var resp = req.EndGetResponse(result);

                this.SafeInvoke(() =>
                {
                    this.progressBar1.Maximum = (int)resp.ContentLength;
                    this.Text = String.Format("Loading '{0}' ({1}%)", this.LoadingFileName, 0);
                });

                // get response stream
                this.Reader = resp.GetResponseStream();

                // read async
                this.Reader.BeginRead(this.ReadBuffer, 0, this.ReadBuffer.Length, this.ReadCallback, null);
            }, null);
        }
Ejemplo n.º 2
0
        public void Clone()
        {
            UniValue v  = UniValue.Create("test");
            UniValue v2 = v.Clone() as UniValue;

            v2 = "123";

#if !NET35 && !NET40
            Assert.NotEqual(v2, v);
#endif

            Assert.False(v2.Equals(v));

            var o = new { id = 123, text = "test" };

            v  = UniValue.Create(o);
            v2 = v.Clone() as UniValue;
            v2 = "test";

#if !NET35 && !NET40
            Assert.NotEqual(v2, v);
#endif

            Assert.False(v2.Equals(v));

            v       = UniValue.Create(o);
            v2      = v;
            v["id"] = "555";

#if !NET35 && !NET40
            Assert.Equal(v, v2);
#endif

            Assert.True(v2.Equals(v));
        }
Ejemplo n.º 3
0
        public CloudFiles AddFiles(Dictionary <string, object> items)
        {
            UniValue file = UniValue.Create((Dictionary <string, object>)items);
            var      map  = new ApiDataMapping();

            map.Add("id", "FileID");
            map.Add("title", "FileName");
            map.Add("fileExtension", "Extention");
            map.Add("downloadUrl", "DownUrl");
            map.Add("thumbnailLink", "Thumnail");
            map.Add("fileSize", "FileSize", typeof(long));
            map.Add("modifiedDate", "modifiedDate");
            FileInfo fi = new FileInfo(file, map);

            //fi.Path = "root";
            fi.driveinfo = driveinfo;
            if (fi.Extention != null)
            {
                fi.DownUrl = "https://www.googleapis.com/drive/v2/files/" + fi.FileID + "?alt=media";
                fi.IsFile  = true;
            }
            else
            {
                fi.Path  += fi.FileName + "/";
                fi.IsFile = false;
            }
            GoogleFile files = new GoogleFile(fi);

            GoogleFiles.Add(files);
            return(files);
        }
Ejemplo n.º 4
0
        public CloudFiles AddFiles(Dictionary <string, object> items)
        {
            UniValue file = UniValue.Create((Dictionary <string, object>)items);
            var      map  = new ApiDataMapping();

            map.Add("id", "FileID");
            map.Add("name", "FileName");
            map.Add("@content.downloadUrl", "DownUrl");
            map.Add("size", "FileSize", typeof(long));
            map.Add("lastModifiedDateTime", "modifiedDate");
            FileInfo fi = new FileInfo(file, map);

            fi.driveinfo = driveinfo;
            if (fi.Items.CollectionItems.ContainsKey("folder"))
            {
                fi.IsFile = false;
            }
            else
            {
                fi.IsFile    = true;
                fi.Extention = GetExtension(fi.FileName);
            }
            fi.Thumnail = GetTumbNail(fi.FileID);
            OneDriveFile itemss = new OneDriveFile(fi);

            files.Add(itemss);
            return(itemss);
        }
Ejemplo n.º 5
0
        private void GetFiles_Result(RequestResult result)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action <RequestResult>(GetFiles_Result), result);
                return;
            }

            this.Cursor = Cursors.Default;

            if (Enumerable.Range(200, 100).Contains(result.StatusCode)) // result.StatusCode == 200
            {
                listBox1.Items.Clear();

                listBox1.DisplayMember = "name";

                foreach (UniValue file in result["value"])
                {
                    listBox1.Items.Add(file);
                }

                if (!String.IsNullOrEmpty(this.CurrentFolderId))
                {
                    listBox1.Items.Insert(0, UniValue.Create(new { name = "..", toup = true }));
                }
            }
            else
            {
                this.ShowError(result);
            }
        }
        public void UniValueTest()
        {
            // Serialize
            var value = UniValue.Create(123);
            var bf    = new BinaryFormatter();
            var m     = new MemoryStream();

            bf.Serialize(m, value);

            // Deserialize
            m.Position = 0;

            var value2 = (UniValue)bf.Deserialize(m);

            Assert.Equal(value2, value);

            var value3 = UniValue.ParseXml("<items><item>1</item><item>2</item><item>3</item></items>");//UniValue.Create(new { id = 123, a = new HttpUrlParameter("test", null), text = "hello", list = new object[] { 1, 2, 3, 4, 5, 6, 7 } });

            var bf2 = new BinaryFormatter();
            var m2  = new MemoryStream();

            bf.Serialize(m2, value3.First());

            // Deserialize
            m2.Position = 0;

            var value4 = (UniValue)bf.Deserialize(m2);

            Assert.Equal(value4.ToString(), value3.First().ToString());

            value3 = UniValue.ParseXml("<items><item>1</item><item>2</item><item>3</item></items>");//UniValue.Create(new { id = 123, a = new HttpUrlParameter("test", null), text = "hello", list = new object[] { 1, 2, 3, 4, 5, 6, 7 } });

            bf2 = new BinaryFormatter();
            m2  = new MemoryStream();

            bf.Serialize(m2, value3);

            // Deserialize
            m2.Position = 0;

            value4 = (UniValue)bf.Deserialize(m2);

            Assert.Equal(value4.ToString(), value3.ToString());

            value3 = UniValue.Create(new { id = 123, a = new HttpUrlParameter("test", null), text = "hello", list = new object[] { 1, 2, 3, 4, 5, 6, 7 } });

            m2 = new MemoryStream();

            bf.Serialize(m2, value3);

            m2.Position = 0;

            value4 = (UniValue)bf.Deserialize(m2);

            Assert.Equal(value4.ToString(), value3.ToString());
        }
Ejemplo n.º 7
0
        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            if (MyListBox.SelectedItem == null)
            {
                return;
            }

            var file = (UniValue)this.MyListBox.SelectedItem;

            if (file[".tag"].Equals("folder"))
            {
                // this.CurrentPath = file["path_display"].ToString();
                MessageBox.Show("Cannot download folder, please select a file");
                return;
            }

            SaveFileDialog SaveF = new SaveFileDialog();

            SaveF.FileName = System.IO.Path.GetFileName(file["path_display"].ToString());

            Nullable <bool> result = SaveF.ShowDialog();

            if (result.HasValue && result.Value == false)
            {
                return;
            }


            this.DownloadFileStream = new FileStream(SaveF.FileName, FileMode.Create, FileAccess.Write);
            this.DownloadWriter     = new BinaryWriter(this.DownloadFileStream);

            var req = WebRequest.Create("https://content.dropboxapi.com/2/files/download");

            req.Method = "GET";

            req.Headers.Add(HttpRequestHeader.Authorization, this.Authorization.ToString());
            req.Headers.Add("Dropbox-API-Arg", UniValue.Create(new { path = file["path_display"].ToString() }).ToString());

            req.BeginGetResponse(resultB =>
            {
                var resp = req.EndGetResponse(resultB);

                this.DownloadReader = resp.GetResponseStream();

                this.DownloadReader.BeginRead(this.DownloadReadBuffer, 0, this.DownloadReadBuffer.Length,
                                              this.DownloadReadCallback, null);
            }, null);

            this.Getfiles();
        }
Ejemplo n.º 8
0
        public void IsNullOrEmpty()
        {
            UniValue v = null;

            Assert.True(UniValue.IsNullOrEmpty(v));

            v = "123";

            Assert.False(UniValue.IsNullOrEmpty(v));
            Assert.False(UniValue.IsNullOrEmpty(1));
            Assert.False(UniValue.IsNullOrEmpty("test"));
            Assert.True(UniValue.IsNullOrEmpty(UniValue.Empty));
            Assert.False(UniValue.IsNullOrEmpty(UniValue.Create(DateTime.Now)));
            Assert.True(UniValue.IsNullOrEmpty(UniValue.Create()));
        }
Ejemplo n.º 9
0
        private void button2_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;

            if (openFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            object parents = null;

            if (!String.IsNullOrEmpty(this.CurrentFolderId))
            {
                parents = new object[] { new { id = this.CurrentFolderId } };
            }

            UniValue properties = UniValue.Create
                                  (
                new
            {
                title   = Path.GetFileName(openFileDialog1.FileName),
                parents = parents
            }
                                  );

            var file = openFileDialog1.OpenFile();

            this.CurrentFileLength = file.Length;

            var parameters = new HttpParameterCollection();

            parameters.Add("uploadType", "multipart");
            parameters.AddContent("application/json", properties.ToString());
            parameters.AddContent("application/octet-stream", file);

            OAuthUtility.PostAsync
            (
                "https://www.googleapis.com/upload/drive/v2/files",
                parameters,
                authorization: new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken),
                contentType: "multipart/related",
                // handler of result
                callback: Upload_Result,
                // handler of uploading
                streamWriteCallback: Upload_Processing
            );
        }
Ejemplo n.º 10
0
        private void GetFiles_Result(RequestResult result)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action <RequestResult>(GetFiles_Result), result);
                return;
            }

            this.Cursor = Cursors.Default;

            if (result.StatusCode == 200)
            {
                listBox1.Items.Clear();

                listBox1.DisplayMember = "title";

                foreach (UniValue file in result["items"])
                {
                    listBox1.Items.Add(file);
                }

                if (!String.IsNullOrEmpty(this.CurrentFolderId))
                {
                    listBox1.Items.Insert(0, UniValue.Create(new { title = "..", toup = true }));
                }
            }
            else
            {
                if (result["error"]["errors"].Count > 0)
                {
                    if (result["error"]["errors"][0]["reason"].Equals("authError", StringComparison.OrdinalIgnoreCase))
                    {
                        this.GetAccessToken();
                    }
                    else
                    {
                        MessageBox.Show(result["error"]["errors"][0]["message"].ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show(result.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Ejemplo n.º 11
0
        public async Task ChageFileName(string filename)
        {
            string   uri        = "https://www.googleapis.com/drive/v1/files/" + Item.FileID + "?updateViewedDate=true&updateModifiedDate=true";
            UniValue properties = UniValue.Create(new { title = filename });
            string   method     = "PATCH";

            try
            {
                byte[] buf = Encoding.UTF8.GetBytes(properties.ToString());
                System.Net.HttpWebResponse rp = await HttpHelper.RequstHttp(method, uri, null, Item.driveinfo.token.access_token, null, buf, buf.Length, 0, buf.Length);

                item.Path     = item.Path.Replace(item.FileName, filename);
                Item.FileName = filename;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 12
0
        public async Task ChageFileName(string filename)
        {
            string   uri        = "https://api.onedrive.com/v1.0/drive/items/" + Item.FileID;
            string   method     = "PATCH";
            UniValue properties = UniValue.Create(new { name = filename });

            try
            {
                byte[] buf = Encoding.UTF8.GetBytes(properties.ToString());
                System.Net.HttpWebResponse rp = await HttpHelper.RequstHttp(method, uri, null, Item.driveinfo.token.access_token, null, buf, buf.Length, 0, buf.Length);

                Item.Path     = Item.Path.Replace(Item.FileName, filename);
                Item.FileName = filename;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 13
0
        public void UniValue_Clone()
        {
            Console.WriteLine("Test 1: String");
            UniValue v  = UniValue.Create("test");
            UniValue v2 = v.Clone() as UniValue;

            v2 = "123";
            if (v.Equals(v2))
            {
                Assert.Fail();
            }
            else
            {
                Console.WriteLine("OK");
            }
            Console.WriteLine("Test 2: Object");
            var o = new { id = 123, text = "test" };

            v  = UniValue.Create(o);
            v2 = v.Clone() as UniValue;
            v2 = "test";
            if (v.Equals(v2))
            {
                Assert.Fail();
            }
            else
            {
                Console.WriteLine("OK");
            }
            Console.WriteLine("Test 3: Reference");
            v       = UniValue.Create(o);
            v2      = v;
            v["id"] = "555";
            if (v.Equals(v2))
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
        }
Ejemplo n.º 14
0
        public async Task <CloudFiles> CreateFolder(string foldername, string parentid)
        {
            string   method     = "POST";
            string   uri        = string.Format("https://api.onedrive.com/v1.0/drive/items/{0}/children", parentid);
            UniValue properties = UniValue.Create(new { name = foldername, folder = new { } });

            try
            {
                byte[] buf = Encoding.UTF8.GetBytes(properties.ToString());
                System.Net.HttpWebResponse rp = await HttpHelper.RequstHttp(method, uri, null, driveinfo.token.access_token, null, buf, buf.Length, 0, buf.Length);

                Dictionary <string, object> dic = HttpHelper.DerealizeJson(rp.GetResponseStream());
                CloudFiles file = AddFiles(dic);
                return(file);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 15
0
        public async Task <string> GetGoogleUploadUrl()
        {
            object parent = null;

            parent = new object[] { new { id = currentfileid } };
            UniValue properties = UniValue.Create(new { title = path, parents = parent, description = "AllCloudeByUpLoad", fileSize = maxsize });

            byte[]          date = Encoding.UTF8.GetBytes(properties.ToString());
            HttpWebResponse respone;

            try
            {
                respone = await HttpHelper.RequstHttp("POST", "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable", null, accesstoken, null, date, date.Length, 0, date.Length);
            }
            catch (Exception e)
            {
                throw e;
            }
            return(respone.Headers["Location"].ToString());
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Parses the source to the <see cref="Result"/>.
        /// </summary>
        private void ParseSource()
        {
            if (this.Source == null || this.Source.Length <= 0)
            {
                return;
            }
            switch (this.ContentType.ToLower())
            {
            case "text/json":
            case "text/javascript":
            case "application/json":
            case "application/javascript":
                this.Data = UniValue.ParseJson(Encoding.UTF8.GetString(this.Source)).Data;
                break;

            case "text/xml":
            case "application/xml":
            case "application/atom+xml":
            case "application/atomsvc+xml":
                this.Data = UniValue.ParseXml(Encoding.UTF8.GetString(this.Source)).Data;
                break;

            case "text/html":
            case "text/plain":
            case "application/x-www-form-urlencoded": // for some cases
                UniValue r = UniValue.Empty;
                if (UniValue.TryParseParameters(Encoding.UTF8.GetString(this.Source), out r))
                {
                    this.Data = r.Data;
                }
                else
                {
                    this.Data = UniValue.Create(Encoding.UTF8.GetString(this.Source)).Data;
                }
                break;

            default:
                this.Data = UniValue.Create(this.Source).Data;
                break;
            }
        }
Ejemplo n.º 17
0
        public async Task CopyFile(FileInfo parentfile)
        {
            string   method   = "POST";
            UniValue properte = UniValue.Create(new { name = Item.FileName, parentReference = new { id = parentfile.FileID } });

            System.Collections.Specialized.NameValueCollection header = new System.Collections.Specialized.NameValueCollection();
            header.Add("Prefer", "respond-async");
            byte[] buf = Encoding.UTF8.GetBytes(properte.ToString());
            string uri = string.Format("https://api.onedrive.com/v1.0/drive/items/{0}/action.copy", Item.FileID);

            try
            {
                System.Net.HttpWebResponse rp = await HttpHelper.RequstHttp(method, uri, null, Item.driveinfo.token.access_token, header, buf, buf.Length, 0, buf.Length);
            }
            catch (System.Net.WebException e)
            {
                Dictionary <string, object> ErrorBlinkStyle = HttpHelper.DerealizeJson(e.Response.GetResponseStream());
                throw e;
            }
            return;
        }
Ejemplo n.º 18
0
        public void UniValue_Compatibility()
        {
            Console.WriteLine("Test 1");
            UniValue r = UniValue.ParseJson("{ response: [{ uid: 489, first_name: 'Aleksandr', last_name: '', nickname: '', online: 1, user_id: 484, lists: [1] }, { uid: 546, first_name: 'Oksana', last_name: '', deactivated: 'deleted', online: 0, user_id: 546 }, { uid: 845, first_name: 'Sergey', last_name: '', nickname: '', online: 0, user_id: 845 }] }");

            Console.WriteLine(@"foreach (Dictionary<string, object> itm in (Array)r[""response""])
Replace Dictionary<string, object> to ResultValue");
            foreach (UniValue itm in (Array)r["response"])
            {
                Console.WriteLine("{0} = {1}", itm["uid"], itm["first_name"]);
            }
            Console.WriteLine("OK");
            Console.WriteLine("-------------------------------------");

            Console.WriteLine("Test 2: Binary");
            r = UniValue.Create(new byte[] { 1, 2, 3, 4, 5 });
            var b = (byte[])r;

            Console.WriteLine(Convert.ToBase64String(b));
            Console.WriteLine("OK");
        }
Ejemplo n.º 19
0
        public void Compatibility()
        {
            int i         = 0;
            var uid       = new int[] { 489, 546, 845 };
            var firstName = new string[] { "Aleksandr", "Oksana", "Sergey" };

            UniValue r = UniValue.ParseJson("{ response: [{ uid: 489, first_name: 'Aleksandr', last_name: '', nickname: '', online: 1, user_id: 484, lists: [1] }, { uid: 546, first_name: 'Oksana', last_name: '', deactivated: 'deleted', online: 0, user_id: 546 }, { uid: 845, first_name: 'Sergey', last_name: '', nickname: '', online: 0, user_id: 845 }] }");

            foreach (UniValue itm in (Array)r["response"])
            {
                Assert.Equal(uid[i], itm["uid"]);
                Assert.Equal(firstName[i], itm["first_name"]);

                i++;
            }

            var bytes = new byte[] { 1, 2, 3, 4, 5 };

            r = UniValue.Create(bytes);

            Assert.Equal(bytes, (byte[])r);
        }
Ejemplo n.º 20
0
        public async Task <CloudFiles> CreateFolder(string foldername, string parentid)
        {
            string method = "POST";
            string uri    = "https://www.googleapis.com/drive/v2/files";
            object parent;

            parent = new object[] { new { id = parentid } };
            UniValue properties = UniValue.Create(new { title = foldername, parents = parent, mimeType = "application/vnd.google-apps.folder" });

            try
            {
                byte[] buf = Encoding.UTF8.GetBytes(properties.ToString());
                System.Net.HttpWebResponse rp = await HttpHelper.RequstHttp(method, uri, null, driveinfo.token.access_token, null, buf, buf.Length, 0, buf.Length);

                Dictionary <string, object> dic = HttpHelper.DerealizeJson(rp.GetResponseStream());
                CloudFiles file = AddFiles(dic);
                return(file);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 21
0
        public CloudFiles AddFiles(Dictionary <string, object> items)
        {
            UniValue files = UniValue.Create(items);
            var      map   = new ApiDataMapping();

            map.Add("path", "FileID");
            map.Add("path", "FileName");
            map.Add("thumb_exists", "Thumnail");
            map.Add("bytes", "FileSize", typeof(long));
            map.Add("modified", "modifiedDate");
            FileInfo fi = new FileInfo(files, map);

            fi.driveinfo = driveinfo;
            if (fi.Thumnail == "True")
            {
                fi.Thumnail = GetTumbNail(true, fi.FileID);
            }
            else
            {
                fi.Thumnail = GetTumbNail(false, fi.FileID);
            }
            if (items["icon"].ToString() == "folder")
            {
                fi.IsFile = false;
            }
            else
            {
                fi.IsFile    = true;
                fi.FileName  = GetFileName(fi.FileName);
                fi.Extention = GetExtension(fi.FileName);
                fi.DownUrl   = "https://api-content.dropbox.com/1/files/auto/" + fi.FileID;
            }
            DropBoxFile itemss = new DropBoxFile(fi);

            file.Add(itemss);
            return(itemss);
        }
Ejemplo n.º 22
0
        private void button1_Click(object sender, EventArgs e)
        {
            // help: https://developers.google.com/drive/v2/reference/files/insert

            object parents = null;

            if (!String.IsNullOrEmpty(this.CurrentFolderId))
            {
                parents = new object[] { new { id = this.CurrentFolderId } };
            }

            UniValue content = UniValue.Create
                               (
                new
            {
                mimeType = "application/vnd.google-apps.folder",
                title    = textBox1.Text,
                parents  = parents
            }
                               );

            var parameters = new HttpParameterCollection();

            parameters.Encoding = Encoding.UTF8;
            parameters.Add("uploadType", "multipart");
            parameters.AddContent("application/json", content.ToString());

            OAuthUtility.PostAsync
            (
                "https://www.googleapis.com/upload/drive/v2/files",
                parameters: parameters,
                authorization: new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken),
                contentType: "multipart/related",
                callback: CreateFolder_Result
            );
        }
Ejemplo n.º 23
0
        public void Common()
        {
            var test = new Dictionary <string, UniValue>();
            var now  = DateTime.Now;

            test.Add("a", 123);
            test.Add("b", "test");
            test.Add("c", now);
            test.Add("d", 4.2);
            test.Add("e", new byte[] { 1, 2, 3 });
            test.Add("f", UniValue.Create(new Uri("http://localhost")));
            test.Add("g", UniValue.Create(new { id = 123, name = "tester", date = now, obj = new { a = 1, b = 2, c = 3, d = new int[] { 1, 2, 3 } } }));
            test.Add("h", new int[] { 1, 2, 3 });
            test.Add("i", new string[] { "a", "b", "c" });
            test.Add("j", new StringBuilder("xyz"));

            Assert.Equal("123", test["a"].ToString());
            Assert.Equal("test", test["b"].ToString());
            Assert.Equal(now, (DateTime)test["c"]);
            Assert.Equal(4.2, (double)test["d"]);
            Assert.Equal("http://localhost", test["f"]["OriginalString"]);
            Assert.Equal(123, test["g"]["id"]);
            Assert.Equal(now, test["g"]["date"]);
            Assert.Equal(1, test["g"]["obj"]["a"]);
            Assert.Equal(2, test["g"]["obj"]["b"]);
            Assert.Equal(3, test["g"]["obj"]["c"]);
            Assert.Equal(1, test["h"][0]);
            Assert.Equal(2, test["h"][1]);
            Assert.Equal(3, test["h"][2]);
            Assert.Equal("a", test["i"][0]);
            Assert.Equal("b", test["i"][1]);
            Assert.Equal("c", test["i"][2]);
            Assert.Equal("xyz", test["j"].ToString());
            Assert.True(test["j"].Equals("xyz"));
            // TODO: Assert.Equal("xyz", test["j"]);

            UniValue r2  = "world!";
            string   ttt = "Hello, " + r2;

            Assert.True(r2.IsString);
            Assert.Equal("Hello, world!", ttt);

            r2 = 123;
            Assert.Equal(123, (int)r2);
            Assert.Equal(123, Convert.ToInt32(r2));

            r2 = "ff";
            Assert.Equal(255, Convert.ToInt32(r2.ToString(), 16));

            r2 = "123";
            Assert.Equal(123, (int)r2);

            r2 = 123.123;
            Assert.Equal(123, (int)r2);

            r2 = "123.123";
            Assert.Equal(123, (int)r2);

            r2 = "123,123";
            Assert.Equal(123, (int)r2);

            r2 = "abc";

#if NET35
            Assert.Throws <FormatException>(() => (int)r2);
#elif NET40
            Assert.Throws <FormatException>(() => (int)r2);
#else
            Assert.ThrowsAny <FormatException>(() => (int)r2);
#endif

            r2 = 123;
            Assert.Equal(123, (double)r2);

            r2 = "123";
            Assert.Equal(123, (double)r2);

            r2 = "123.123";
            Assert.Equal(123.123, (double)r2);

            r2 = "123,123";
            Assert.Equal(123.123, (double)r2);

            r2 = "abc";

#if NET35
            Assert.Throws <FormatException>(() => (double)r2);
#elif NET40
            Assert.Throws <FormatException>(() => (double)r2);
#else
            Assert.ThrowsAny <FormatException>(() => (double)r2);
#endif

            r2 = "Thu Dec 04, 2014";
            Assert.Equal(new DateTime(2014, 12, 4), Convert.ToDateTime(r2));
        }
Ejemplo n.º 24
0
        private void MyListBox_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (MyListBox.SelectedItem == null)
            {
                return;
            }
            var file = (UniValue)this.MyListBox.SelectedItem;

            if (file["path_display"] == "..")
            {
                if (!String.IsNullOrEmpty(this.CurrentPath))
                {
                    this.CurrentPath = System.IO.Path.GetDirectoryName(this.CurrentPath).Replace("\\", "/");
                    if (this.CurrentPath == "/")
                    {
                        this.CurrentPath = "";
                    }
                }
            }
            else
            {
                if (file[".tag"].Equals("folder"))
                {
                    this.CurrentPath = file["path_display"].ToString();
                }
                else
                {
                    SaveFileDialog SaveF = new SaveFileDialog();

                    SaveF.FileName = System.IO.Path.GetFileName(file["path_display"].ToString());

                    Nullable <bool> result = SaveF.ShowDialog();
                    if (result.HasValue && result.Value == false)
                    {
                        return;
                    }


                    this.DownloadFileStream = new FileStream(SaveF.FileName, FileMode.Create, FileAccess.Write);
                    this.DownloadWriter     = new BinaryWriter(this.DownloadFileStream);

                    var req = WebRequest.Create("https://content.dropboxapi.com/2/files/download");

                    req.Method = "GET";

                    req.Headers.Add(HttpRequestHeader.Authorization, this.Authorization.ToString());
                    req.Headers.Add("Dropbox-API-Arg", UniValue.Create(new { path = file["path_display"].ToString() }).ToString());

                    req.BeginGetResponse(resultB =>
                    {
                        var resp = req.EndGetResponse(resultB);

                        this.DownloadReader = resp.GetResponseStream();

                        this.DownloadReader.BeginRead(this.DownloadReadBuffer, 0, this.DownloadReadBuffer.Length,
                                                      this.DownloadReadCallback, null);
                    }, null);
                }
            }
            this.Getfiles();
        }
Ejemplo n.º 25
0
        private void bunifuCustomDataGrid1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken);

            DataGridView dvg = (DataGridView)sender;

            if (e.ColumnIndex == 9 && e.RowIndex != -1)
            {
                // Inicializar variables
                string id = (string)dvg["Codigo del articulo", e.RowIndex].Value.ToString();
                string ext;
                string file;
                int    id_int = Convert.ToInt32(id);

                //Conexión a la base de datos
                MySqlConnection conexion = new MySqlConnection();
                conexion.ConnectionString = "server=localhost; pasword=;" + "database=MASHUP_PROYECTO; User id= root; SslMode=none";
                conexion.Open();
                string          sql      = "select Ext_archivo,Nom_Origen from registro_objetos where ID_CONTENIDO = " + id;
                MySqlCommand    query    = new MySqlCommand(sql, conexion);
                MySqlDataReader myReader = query.ExecuteReader();
                myReader.Read();

                //construcción del nombre del archivo a descargar
                ext  = myReader["Ext_Archivo"].ToString();
                file = id + ext;



                SaveFileDialog save = new SaveFileDialog();
                //this.save.FileName = Path.GetFileName(file["path_display"].ToString());
                save.FileName = myReader["Nom_Origen"].ToString();
                conexion.Close();
                if (save.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }
                string path2 = save.FileName;

                // token = Properties.Settings.Default.AccessToken

                /*var dbx = new DropboxClient(Properties.Settings.Default.AccessToken);
                 *
                 *
                 * using (var response = dbx.Files.DownloadAsync("/8.gif"))
                 * {
                 *  (await response.getGetContentAsStreamAsync()).CopyTo(fileStream);
                 * }
                 * MessageBox.Show(response.);*/
                this.DownloadFileStream = new FileStream(save.FileName, FileMode.Create, FileAccess.Write);
                this.DownloadWriter     = new BinaryWriter(this.DownloadFileStream);


                var req = WebRequest.Create("https://content.dropboxapi.com/2/files/download");
                req.Method = "POST";

                req.Headers.Add(HttpRequestHeader.Authorization, this.Authorization.ToString());
                req.Headers.Add("Dropbox-API-Arg", UniValue.Create(new { path = "/" + file }).ToString());

                req.BeginGetResponse(result =>
                {
                    var resp = req.EndGetResponse(result);

                    // get response stream
                    this.DownloadReader = resp.GetResponseStream();

                    // read async
                    this.DownloadReader.BeginRead(this.DownloadReadBuffer, 0, this.DownloadReadBuffer.Length, this.DownloadReadCallback, null);
                }, null);

                //MessageBox.Show((e.RowIndex+1).ToString() + " Row clicked");
            }
        }
Ejemplo n.º 26
0
        public void UniValue_IsNullOrEmpty()
        {
            UniValue v = null;

            Console.WriteLine("null = {0}", UniValue.IsNullOrEmpty(v));
            if (UniValue.IsNullOrEmpty(v))
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
            v = "123";
            Console.WriteLine("123 = {0}", UniValue.IsNullOrEmpty(v));
            if (!UniValue.IsNullOrEmpty(v))
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
            Console.WriteLine("1 = {0}", UniValue.IsNullOrEmpty(1));
            if (!UniValue.IsNullOrEmpty(1))
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
            Console.WriteLine("test = {0}", UniValue.IsNullOrEmpty("test"));
            if (!UniValue.IsNullOrEmpty("test"))
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
            Console.WriteLine("empty = {0}", UniValue.IsNullOrEmpty(UniValue.Empty));
            if (UniValue.IsNullOrEmpty(UniValue.Empty))
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
            Console.WriteLine("create = {0}", UniValue.IsNullOrEmpty(UniValue.Create(DateTime.Now)));
            if (!UniValue.IsNullOrEmpty(UniValue.Create(DateTime.Now)))
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
            Console.WriteLine("create empty = {0}", UniValue.IsNullOrEmpty(UniValue.Create()));
            if (UniValue.IsNullOrEmpty(UniValue.Create()))
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
        }
Ejemplo n.º 27
0
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem == null)
            {
                return;
            }

            var file = (UniValue)this.listBox1.SelectedItem;

            if (file["path_display"] == "..")
            {
                if (!String.IsNullOrEmpty(this.CurrentPath))
                {
                    this.CurrentPath = Path.GetDirectoryName(this.CurrentPath).Replace("\\", "/");
                    if (this.CurrentPath == "/")
                    {
                        this.CurrentPath = "";
                    }
                }
            }
            else
            {
                if (file[".tag"].Equals("folder"))
                {
                    this.CurrentPath = file["path_display"].ToString();
                }
                else
                {
                    this.saveFileDialog1.FileName = Path.GetFileName(file["path_display"].ToString());

                    if (this.saveFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    {
                        return;
                    }

                    this.progressBar1.Value = 0;

                    this.DownloadFileStream = new FileStream(this.saveFileDialog1.FileName, FileMode.Create, FileAccess.Write);
                    this.DownloadWriter     = new BinaryWriter(this.DownloadFileStream);

                    // download file
                    var req = WebRequest.Create("https://content.dropboxapi.com/2/files/download");

                    req.Method = "POST";

                    req.Headers.Add(HttpRequestHeader.Authorization, this.Authorization.ToString());
                    req.Headers.Add("Dropbox-API-Arg", UniValue.Create(new { path = file["path_display"].ToString() }).ToString());

                    req.BeginGetResponse(result =>
                    {
                        var resp = req.EndGetResponse(result);

                        this.SafeInvoke(() =>
                        {
                            this.progressBar1.Maximum = (int)resp.ContentLength;
                        });

                        // get response stream
                        this.DownloadReader = resp.GetResponseStream();

                        // read async
                        this.DownloadReader.BeginRead(this.DownloadReadBuffer, 0, this.DownloadReadBuffer.Length, this.DownloadReadCallback, null);
                    }, null);
                }
            }
            this.GetFiles();
        }
Ejemplo n.º 28
0
        public void UniValue_Common()
        {
            Console.WriteLine("Test 1: Types");
            var test = new Dictionary <string, UniValue>();

            test.Add("a", 123);
            test.Add("b", "test");
            test.Add("c", DateTime.Now);
            test.Add("d", 4.2);
            test.Add("e", new byte[] { 1, 2, 3 });
            test.Add("f", UniValue.Create(new Uri("http://localhost")));
            test.Add("g", UniValue.Create(new { id = 123, name = "tester", date = DateTime.Now, obj = new { a = 1, b = 2, c = 3, d = new int[] { 1, 2, 3 } } }));
            test.Add("h", new int[] { 1, 2, 3 });
            test.Add("i", new string[] { "a", "b", "c" });
            StringBuilder sb = new StringBuilder(); sb.Append("xyz");

            test.Add("j", sb);

            /*ResultValue a = 123;
             * ResultValue b = "test";
             * ResultValue c = DateTime.Now;
             * ResultValue d = 4.2;
             * ResultValue e = new byte[] { 1, 2, 3 };
             * ResultValue f = new Uri("http://localhost");*/

            foreach (var key in test.Keys)
            {
                Console.WriteLine("{0} = {1}", key, test[key]);
            }

            Console.WriteLine("-------------------------------------");

            Console.WriteLine("Test 2: Parse");

            Console.WriteLine("JSON");
            try
            {
                var r = UniValue.ParseJson("test,1,#2,$3");
                Assert.Fail("Invalid parse: ERROR");
            }
            catch
            {
                Console.WriteLine("Invalid parse: OK");
            }
            try
            {
                UniValue r = UniValue.Empty;
                if (!UniValue.TryParseJson("test,1,#2,$3", out r))
                {
                    Console.WriteLine("Try parse #1: OK");
                }
                else
                {
                    Assert.Fail("Try parse #1: ERROR");
                }
                if (UniValue.TryParseJson("[1,2,3]", out r))
                {
                    Console.WriteLine("Try parse #2: OK / {0}", r);
                }
                else
                {
                    Assert.Fail("Try parse #2: ERROR");
                }
            }
            catch
            {
                Assert.Fail("Try parse: ERROR");
            }

            Console.WriteLine("-------------------------------------");

            Console.WriteLine("XML");
            try
            {
                var r = UniValue.ParseXml("test,1,#2,$3");
                Assert.Fail("Invalid parse: ERROR");
            }
            catch
            {
                Console.WriteLine("Invalid parse: OK");
            }
            try
            {
                UniValue r = UniValue.Empty;
                if (!UniValue.TryParseXml("test,1,#2,$3", out r))
                {
                    Console.WriteLine("Try parse #1: OK");
                }
                else
                {
                    Assert.Fail("Try parse #1: ERROR");
                }
                if (UniValue.TryParseXml("<items><item>1</item><item>2</item><item>3</item></items>", out r))
                {
                    Console.WriteLine("Try parse #2: OK / {0}", r);
                }
                else
                {
                    Assert.Fail("Try parse #2: ERROR");
                }
            }
            catch
            {
                Assert.Fail("Try parse: ERROR");
            }

            Console.WriteLine("-------------------------------------");

            Console.WriteLine("PARAMETERS");
            try
            {
                var r = UniValue.ParseParameters("test,1,#2,$3\r\n");
                Assert.Fail("Invalid parse: ERROR");
            }
            catch
            {
                Console.WriteLine("Invalid parse: OK");
            }
            try
            {
                UniValue r = UniValue.Empty;
                if (!UniValue.TryParseParameters("test,1,#2,$3\r\n", out r))
                {
                    Console.WriteLine("Try parse #1: OK");
                }
                else
                {
                    Assert.Fail("Try parse #1: ERROR");
                }
                if (UniValue.TryParseParameters("a=1&b=2&c=3", out r))
                {
                    Console.WriteLine("Try parse #2: OK / {0}", r);
                }
                else
                {
                    Assert.Fail("Try parse #2: ERROR");
                }
            }
            catch
            {
                Assert.Fail("Try parse: ERROR");
            }

            Console.WriteLine("-------------------------------------");

            Console.WriteLine("Test 3");

            Console.WriteLine("ToString");

            UniValue r2  = "world!";
            string   ttt = "Hello, " + r2;

            Console.WriteLine("IsString: {0}", r2.IsString);
            if (!r2.IsString)
            {
                Assert.Fail();
            }
            Console.WriteLine(ttt);
            Console.WriteLine("OK");

            Console.WriteLine("ToInt32");

            r2 = 123;
            int num = (int)r2;

            num = Convert.ToInt32(r2);

            r2  = "ff";
            num = Convert.ToInt32(r2.ToString(), 16);

            r2  = "123";
            num = (int)r2;

            r2  = 123.123;
            num = (int)r2;

            r2  = "123.123";
            num = (int)r2;

            r2  = "123,123";
            num = (int)r2;

            try
            {
                r2  = "abc";
                num = (int)r2;
                Assert.Fail();
            }
            catch
            {
            }
            Console.WriteLine("OK");

            Console.WriteLine("ToDouble");
            r2 = 123;
            double num2 = (double)r2;

            r2   = "123";
            num2 = (double)r2;

            r2   = "123.123";
            num2 = (double)r2;

            r2   = "123,123";
            num2 = (double)r2;

            try
            {
                r2   = "abc";
                num2 = (double)r2;
                Assert.Fail();
            }
            catch
            {
            }
            Console.WriteLine("OK");

            Console.WriteLine("ToDateTime");

            r2 = "Thu Dec 04, 2014";
            Convert.ToDateTime(r2);

            Console.WriteLine("OK");
        }
Ejemplo n.º 29
0
        public void Serialization_UniValue()
        {
            Console.WriteLine("Test 1 : Single");

            // Serialize
            var value = UniValue.Create(123);

            var bf = new BinaryFormatter();
            var m  = new MemoryStream();

            bf.Serialize(m, value);

            // Deserialize
            m.Position = 0;
            var value2 = (UniValue)bf.Deserialize(m);

            Console.WriteLine(value);
            Console.WriteLine(value2);
            if (value2 == value)
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }

            Console.WriteLine();
            Console.WriteLine("-------------------------------------");
            Console.WriteLine();

            Console.WriteLine("Test 2 : Collection");

            var value3 = UniValue.ParseXml("<items><item>1</item><item>2</item><item>3</item></items>");//UniValue.Create(new { id = 123, a = new HttpUrlParameter("test", null), text = "hello", list = new object[] { 1, 2, 3, 4, 5, 6, 7 } });

            var bf2 = new BinaryFormatter();
            var m2  = new MemoryStream();

            bf.Serialize(m2, value3.First());

            // Deserialize
            m2.Position = 0;
            var value4 = (UniValue)bf.Deserialize(m2);

            Console.WriteLine(value3.First());
            Console.WriteLine(value4);
            if (value4.ToString() == value3.First().ToString())
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }

            Console.WriteLine();
            Console.WriteLine("-------------------------------------");
            Console.WriteLine();

            Console.WriteLine("Test 3 : Collection #2");

            value3 = UniValue.ParseXml("<items><item>1</item><item>2</item><item>3</item></items>");//UniValue.Create(new { id = 123, a = new HttpUrlParameter("test", null), text = "hello", list = new object[] { 1, 2, 3, 4, 5, 6, 7 } });

            bf2 = new BinaryFormatter();
            m2  = new MemoryStream();
            bf.Serialize(m2, value3);

            // Deserialize
            m2.Position = 0;
            value4      = (UniValue)bf.Deserialize(m2);
            Console.WriteLine(value3);
            Console.WriteLine(value4);
            if (value4.ToString() == value3.ToString())
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }

            Console.WriteLine();
            Console.WriteLine("-------------------------------------");
            Console.WriteLine();

            Console.WriteLine("Test 4 : Collection #3");

            value3 = UniValue.Create(new { id = 123, a = new HttpUrlParameter("test", null), text = "hello", list = new object[] { 1, 2, 3, 4, 5, 6, 7 } });

            m2 = new MemoryStream();
            bf.Serialize(m2, value3);

            // Deserialize
            m2.Position = 0;
            value4      = (UniValue)bf.Deserialize(m2);
            Console.WriteLine(value3);
            Console.WriteLine(value4);
            if (value4.ToString() == value3.ToString())
            {
                Console.WriteLine("OK");
            }
            else
            {
                Assert.Fail();
            }
        }