Example #1
0
        public static async Task <bool> TriggerMirrorSyncAsync()
        {
            using (PatientWebClient client = new PatientWebClient()
            {
                Credentials = PrivateStuff.BigmodsNetworkCredentialScripts, Timeout = 100000
            })
            {
                try
                {
                    string result = await client.DownloadStringTaskAsync(PrivateStuff.BigmodsTriggerManualMirrorSyncPHP);

                    Logging.Info(result.Replace("<br />", "\n"));
                    if (result.ToLower().Contains("trigger=1"))
                    {
                        return(true);
                    }
                }
                catch (WebException wex)
                {
                    Logging.Error("Failed to run trigger manual sync script");
                    Logging.Exception(wex.ToString());
                    return(false);
                }
            }
            return(false);
        }
        private async void RelhaxWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //write that we're currently loading
            string loadingString = Translations.GetTranslatedString("loading");

            DatabaseUpdateText.Text = ApplicationUpdateText.Text = loadingString;
            ViewNewsOnGoogleTranslate.TheHyperlink.Click += TheHyperlink_Click;

            //get the strings
            using (PatientWebClient client = new PatientWebClient())
            {
                try
                {
                    DatabaseUpdateText.Text = await client.DownloadStringTaskAsync(ApplicationConstants.DatabaseNotesUrl);

                    ApplicationUpdateText.Text = await client.DownloadStringTaskAsync(ApplicationConstants.ApplicationNotesBetaUrl);
                }
                catch (Exception ex)
                {
                    Logging.Error("Failed to get news information");
                    Logging.Exception(ex.ToString());

                    if (DatabaseUpdateText.Text.Equals(loadingString))
                    {
                        DatabaseUpdateText.Text = Translations.GetTranslatedString("failedToGetNews");
                    }

                    ApplicationUpdateText.Text = Translations.GetTranslatedString("failedToGetNews");
                }
            }
        }
Example #3
0
        private async void RelhaxWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //write that we're currently loading
            DatabaseUpdateText.Text = ApplicationUpdateText.Text = Translations.GetTranslatedString("loading");
            ViewNewsOnGoogleTranslate.TheHyperlink.Click += TheHyperlink_Click;

            //get the strings
            using (PatientWebClient client = new PatientWebClient())
            {
                DatabaseUpdateText.Text = await client.DownloadStringTaskAsync(Settings.DatabaseNotesUrl);

                ApplicationUpdateText.Text = await client.DownloadStringTaskAsync(Settings.ApplicationNotesBetaUrl);
            }
        }
 public Task <string> ExecuteRequest(Uri url)
 {
     try
     {
         var client = new PatientWebClient {
             Credentials = CredentialCache.DefaultNetworkCredentials
         };
         using (client)
         {
             return(Task.Run(() => client.DownloadString(url)));
         }
     }
     catch (Exception e)
     {
         Dev2Logger.Error(e, "Warewolf Error");
         return(new Task <string>((() => e.Message)));
     }
 }
Example #5
0
        private static DatasetsResponse DownloadDataset(int page, QuandlDatabase database)
        {
            using (PatientWebClient client = new PatientWebClient())
            {
                try
                {
                    var json = client.DownloadString("https://www.quandl.com/api/v3/datasets.json?database_code=" + database.DatabaseCode + "&sort_by=id&page=" + page + "&api_key=" + Utils.Constants.API_KEY);
                    DatasetsResponse response =
                        JsonConvert.DeserializeObject <DatasetsResponse>(json, new JsonSerializerSettings {
                        ContractResolver = Utils.Converters.MakeUnderscoreContract()
                    });

                    pagesSum++;
                    Utils.ConsoleInformer.PrintProgress("1B", "Fetching datasets [" + database.DatabaseCode + "]: ", Utils.Helpers.GetPercent(pagesSum, response.Meta.TotalPages).ToString() + "%");

                    // Add it to its own group
                    datasetsGroups.Find(d => d.DatabaseCode == database.DatabaseCode).Datasets.AddRange(response.Datasets);

                    // Insert datasets page directly
                    QuandlDatasetGroup datasetGroup = new QuandlDatasetGroup()
                    {
                        DatabaseCode = database.DatabaseCode, Datasets = response.Datasets
                    };
                    PostgresHelpers.QuandlDatasetActions.InsertQuandlDatasetGroup(datasetGroup);

                    return(response);
                }
                catch (Exception e)
                {
                    if (e.Message.Contains("(429)") && !blocked)
                    {
                        Utils.ConsoleInformer.Inform("Looks like quandl just blocked you");
                        blocked = true;
                    }

                    // Log
                    Utils.Helpers.Log("Failed to fetch page: " + page + " from Database: [" + database.DatabaseCode + "]", "Ex: " + e.Message);

                    // Add error to inform and log later
                    errors.Add(new Tuple <string, string> ("Failed to fetch page: " + page + " from Database: [" + database.DatabaseCode + "]", "Ex: " + e.Message));
                    return(new DatasetsResponse());
                }
            }
        }
Example #6
0
 public static Result UploadBlock(FileProperty prop, string path, InitUploadResult session, FileStream stream, int blockid, string host, Credential credential)
 {
     try
     {
         using (var wc = new PatientWebClient())
         {
             var boundary = GetBoundary();
             wc.Headers.Add(HttpRequestHeader.Cookie, credential);
             wc.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + boundary);
             var str  = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"filename\"; filename=\"name\"\r\nContent-Type: application/octet-stream\r\n\r\n";
             var str2 = "\r\n--" + boundary + "--\r\n";
             stream.Seek((long)blockid * 4 * 1024 * 1024, SeekOrigin.Begin);
             var fdata = new byte[4 * 1024 * 1024];
             var len   = stream.Read(fdata, 0, fdata.Length);
             if (len < fdata.Length)
             {
                 var arr = new byte[len];
                 Array.Copy(fdata, arr, len);
                 fdata = arr;
             }
             var data = Encoding.UTF8.GetBytes(str).Concat(fdata).Concat(Encoding.UTF8.GetBytes(str2)).ToArray();
             var res  = wc.UploadData("http://" + host + "/rest/2.0/pcs/superfile2?app_id=250528&method=upload&path=" + Uri.EscapeDataString(path) + "&uploadid=" + Uri.EscapeDataString(session.uploadid) + "&partseq=" + blockid + "&partoffset=" + (long)blockid * 4 * 1024 * 1024, data);
             var obj  = JsonConvert.DeserializeObject <SuperFileResponse>(Encoding.UTF8.GetString(res));
             if (obj.md5 != prop.blocks[blockid])
             {
                 throw new Exception("MD5 mismatch.");
             }
             return(new Result()
             {
                 success = true
             });
         }
     }
     catch (Exception ex)
     {
         return(new Result()
         {
             exception = ex
         });
     }
 }
Example #7
0
 public static CommitUploadResult SimpleUpload(string localpath, string remotepath, Credential credential, string host = "c.pcs.baidu.com")
 {
     try
     {
         var size  = new FileInfo(localpath).Length;
         var mtime = (long)(new FileInfo(localpath).LastAccessTime.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
         var md5   = UploadHelper.GetMD5HashFromFile(localpath);
         var str   = "path=" + remotepath + "&size=" + size + "&isdir=0&block_list=[\"" + md5 + "\"]&autoinit=1&local_mtime=" + mtime + "&method=post";
         using (var wc = new PatientWebClient())
         {
             wc.Headers.Add(HttpRequestHeader.Cookie, credential);
             wc.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
             var res = wc.UploadData("http://pan.baidu.com/api/precreate?clienttype=8", Encoding.UTF8.GetBytes(str));
             var obj = JsonConvert.DeserializeObject <InitUploadResult>(Encoding.UTF8.GetString(res));
             if (obj.errno != 0)
             {
                 throw new Exception("precreate had errno = " + obj.errno);
             }
             var boundary = GetBoundary();
             wc.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + boundary);
             str = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"filename\"; filename=\"name\"\r\nContent-Type: application/octet-stream\r\n\r\n";
             var str2 = "\r\n--" + boundary + "--\r\n";
             var data = Encoding.UTF8.GetBytes(str).Concat(File.ReadAllBytes(localpath)).Concat(Encoding.UTF8.GetBytes(str2)).ToArray();
             res = wc.UploadData("http://" + host + "/rest/2.0/pcs/superfile2?app_id=250528&method=upload&path=" + Uri.EscapeDataString(remotepath) + "&uploadid=" + Uri.EscapeDataString(obj.uploadid) + "&partseq=0&partoffset=0", data);
             str = "path=" + remotepath + "&size=" + size + "&isdir=0&uploadid=" + Uri.EscapeDataString(obj.uploadid) + "&block_list=[\"" + md5 + "\"]&method=post&rtype=2&sequence=1&mode=1&local_mtime=" + mtime;
             res = wc.UploadData("http://pan.baidu.com/api/create?a=commit&clienttype=8", Encoding.UTF8.GetBytes(str));
             var obj2 = JsonConvert.DeserializeObject <CommitUploadResult>(Encoding.UTF8.GetString(res));
             obj2.success = true;
             return(obj2);
         }
     }
     catch (Exception ex)
     {
         return(new CommitUploadResult()
         {
             exception = ex
         });
     }
 }
Example #8
0
        string ExecuteRequest(Uri url)
        {
            Task <string> failRequest;
            var           client = new PatientWebClient {
                Credentials = CredentialCache.DefaultNetworkCredentials
            };

            using (client)
            {
                failRequest = Task.Run(() => client.DownloadString(url));
            }
            string failRequestResult;

            try
            {
                failRequestResult = failRequest.Result;
            }
            catch (AggregateException e)
            {
                return(new StreamReader((e.InnerExceptions[0] as WebException)?.Response?.GetResponseStream())?.ReadToEnd());
            }

            return(failRequestResult);
        }
        private static DatatableResponse DownloadDatatable(QuandlDatatable datatable)
        {
            using (PatientWebClient client = new PatientWebClient())
            {
                try
                {
                    var json = client.DownloadString(" https://www.quandl.com/api/v3/datatables/" + datatable.Name + ".json?api_key=" + Utils.Constants.API_KEY);
                    DatatableResponse response =
                        JsonConvert.DeserializeObject <DatatableResponse>(json, new JsonSerializerSettings {
                        ContractResolver = Utils.Converters.MakeUnderscoreContract()
                    });

                    Utils.ConsoleInformer.PrintProgress("1B", "Fetching datatable [" + datatable.Name + "]: ", Utils.Helpers.GetPercent(count, datatables.Count).ToString() + "%");

                    return(response);
                }
                catch (Exception e)
                {
                    // Add error to inform and log later
                    errors.Add(new Tuple <string, string>("Failed to fetch datatable: [" + datatable.Name + "]", "Ex: " + e.Message));
                    return(new DatatableResponse());
                }
            }
        }
Example #10
0
        private void Publish(UIMouseEvent evt, UIElement listeningElement)
        {
            if (ModLoader.modBrowserPassphrase == "")
            {
                Main.menuMode = Interface.enterPassphraseMenuID;
                Interface.enterPassphraseMenu.SetGotoMenu(Interface.modSourcesID);
                return;
            }
            Main.PlaySound(10);
            try {
                var modFile = builtMod.modFile;
                var bp      = builtMod.properties;

                var files = new List <UploadFile>();
                files.Add(new UploadFile {
                    Name     = "file",
                    Filename = Path.GetFileName(modFile.path),
                    //    ContentType = "text/plain",
                    Content = File.ReadAllBytes(modFile.path)
                });
                if (modFile.HasFile("icon.png"))
                {
                    files.Add(new UploadFile {
                        Name     = "iconfile",
                        Filename = "icon.png",
                        Content  = modFile.GetBytes("icon.png")
                    });
                }
                if (bp.beta)
                {
                    throw new WebException(Language.GetTextValue("tModLoader.BetaModCantPublishError"));
                }
                if (bp.buildVersion != modFile.tModLoaderVersion)
                {
                    throw new WebException(Language.GetTextValue("OutdatedModCantPublishError.BetaModCantPublishError"));
                }

                var values = new NameValueCollection
                {
                    { "displayname", bp.displayName },
                    { "name", modFile.name },
                    { "version", "v" + bp.version },
                    { "author", bp.author },
                    { "homepage", bp.homepage },
                    { "description", bp.description },
                    { "steamid64", ModLoader.SteamID64 },
                    { "modloaderversion", "tModLoader v" + modFile.tModLoaderVersion },
                    { "passphrase", ModLoader.modBrowserPassphrase },
                    { "modreferences", String.Join(", ", bp.modReferences.Select(x => x.mod)) },
                    { "modside", bp.side.ToFriendlyString() },
                };
                if (values["steamid64"].Length != 17)
                {
                    throw new WebException($"The steamid64 '{values["steamid64"]}' is invalid, verify that you are logged into Steam and don't have a pirated copy of Terraria.");
                }
                if (string.IsNullOrEmpty(values["author"]))
                {
                    throw new WebException($"You need to specify an author in build.txt");
                }
                ServicePointManager.Expect100Continue = false;
                string url = "http://javid.ddns.net/tModLoader/publishmod.php";
                using (PatientWebClient client = new PatientWebClient()) {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, policyErrors) => true;
                    Interface.uploadMod.SetDownloading(modFile.name);
                    Interface.uploadMod.SetCancel(() => {
                        Main.menuMode = Interface.modSourcesID;
                        client.CancelAsync();
                    });
                    client.UploadProgressChanged += (s, e) => Interface.uploadMod.SetProgress(e);
                    client.UploadDataCompleted   += (s, e) => PublishUploadDataComplete(s, e, modFile);

                    var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", System.Globalization.NumberFormatInfo.InvariantInfo);
                    client.Headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                    //boundary = "--" + boundary;
                    byte[] data = UploadFile.GetUploadFilesRequestData(files, values);
                    client.UploadDataAsync(new Uri(url), data);
                }
                Main.menuMode = Interface.uploadModID;
            }
            catch (WebException e) {
                UIModBrowser.LogModBrowserException(e);
            }
        }
Example #11
0
        private static void PublishModInner(TmodFile modFile, BuildProperties bp, bool commandLine = false)
        {
            var files = new List <UploadFile>();

            files.Add(new UploadFile {
                Name     = "file",
                Filename = Path.GetFileName(modFile.path),
                //    ContentType = "text/plain",
                Content = File.ReadAllBytes(modFile.path)
            });
            if (modFile.HasFile("icon.png"))               // Test this on server
            {
                using (modFile.Open())
                    files.Add(new UploadFile {
                        Name     = "iconfile",
                        Filename = "icon.png",
                        Content  = modFile.GetBytes("icon.png")
                    });
            }
            //if (bp.beta)
            //	throw new WebException(Language.GetTextValue("tModLoader.BetaModCantPublishError"));
            if (bp.buildVersion != modFile.TModLoaderVersion)
            {
                throw new WebException(Language.GetTextValue("OutdatedModCantPublishError.BetaModCantPublishError"));
            }

            var values = new NameValueCollection
            {
                { "displayname", bp.displayName },
                { "displaynameclean", string.Join("", ChatManager.ParseMessage(bp.displayName, Color.White).Where(x => x.GetType() == typeof(TextSnippet)).Select(x => x.Text)) },
                { "name", modFile.Name },
                { "version", "v" + bp.version },
                { "author", bp.author },
                { "homepage", bp.homepage },
                { "description", bp.description },
                { "steamid64", ModLoader.SteamID64 },
                { "modloaderversion", "tModLoader v" + modFile.TModLoaderVersion },
                { "passphrase", ModLoader.modBrowserPassphrase },
                { "modreferences", String.Join(", ", bp.modReferences.Select(x => x.mod)) },
                { "modside", bp.side.ToFriendlyString() },
            };

            if (values["steamid64"].Length != 17)
            {
                throw new WebException($"The steamid64 '{values["steamid64"]}' is invalid, verify that you are logged into Steam and don't have a pirated copy of Terraria.");
            }
            if (string.IsNullOrEmpty(values["author"]))
            {
                throw new WebException($"You need to specify an author in build.txt");
            }
            ServicePointManager.Expect100Continue = false;
            string url = "http://javid.ddns.net/tModLoader/publishmod.php";

            using (PatientWebClient client = new PatientWebClient()) {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, policyErrors) => true;
                Interface.progress.Show(displayText: $"Uploading: {modFile.Name}", gotoMenu: Interface.modSourcesID, cancel: client.CancelAsync);

                var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", System.Globalization.NumberFormatInfo.InvariantInfo);
                client.Headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                //boundary = "--" + boundary;
                byte[] data = UploadFile.GetUploadFilesRequestData(files, values, boundary);
                if (commandLine)
                {
                    var    result   = client.UploadData(new Uri(url), data);                // could use async version for progress output maybe
                    string response = HandlePublishResponse(modFile, result);
                    Console.WriteLine(Language.GetTextValue("tModLoader.MBServerResponse", response));
                    if (result.Length <= 256 || result[result.Length - 256 - 1] != '~')
                    {
                        throw new Exception("Publish failed due to invalid response from server");
                    }
                }
                else
                {
                    client.UploadDataCompleted   += (s, e) => PublishUploadDataComplete(s, e, modFile);
                    client.UploadProgressChanged += (s, e) => Interface.progress.Progress = (float)e.BytesSent / e.TotalBytesToSend;
                    client.UploadDataAsync(new Uri(url), data);
                }
            }
        }
        private void PublishMod(UIMouseEvent evt, UIElement listeningElement)
        {
            if (ModLoader.modBrowserPassphrase == "")
            {
                Main.menuMode = Interface.enterPassphraseMenuID;
                Interface.enterPassphraseMenu.SetGotoMenu(Interface.modSourcesID);
                return;
            }
            SoundEngine.PlaySound(10);
            try {
                if (ModLoader.GetMod(_builtMod.Name) == null)
                {
                    if (!_builtMod.Enabled)
                    {
                        _builtMod.Enabled = true;
                    }
                    Main.menuMode = Interface.reloadModsID;
                    ModLoader.OnSuccessfulLoad += () => {
                        PublishMod(null, null);
                    };
                    return;
                }

                var modFile = _builtMod.modFile;
                var bp      = _builtMod.properties;

                var files = new List <UploadFile>();
                files.Add(new UploadFile {
                    Name     = "file",
                    Filename = Path.GetFileName(modFile.path),
                    //    ContentType = "text/plain",
                    Content = File.ReadAllBytes(modFile.path)
                });
                if (modFile.HasFile("icon.png"))
                {
                    using (modFile.Open())
                        files.Add(new UploadFile {
                            Name     = "iconfile",
                            Filename = "icon.png",
                            Content  = modFile.GetBytes("icon.png")
                        });
                }
                if (bp.beta)
                {
                    throw new WebException(Language.GetTextValue("tModLoader.BetaModCantPublishError"));
                }
                if (bp.buildVersion != modFile.tModLoaderVersion)
                {
                    throw new WebException(Language.GetTextValue("OutdatedModCantPublishError.BetaModCantPublishError"));
                }

                var values = new NameValueCollection
                {
                    { "displayname", bp.displayName },
                    { "displaynameclean", string.Join("", ChatManager.ParseMessage(bp.displayName, Color.White).Where(x => x.GetType() == typeof(TextSnippet)).Select(x => x.Text)) },
                    { "name", modFile.name },
                    { "version", "v" + bp.version },
                    { "author", bp.author },
                    { "homepage", bp.homepage },
                    { "description", bp.description },
                    { "steamid64", ModLoader.SteamID64 },
                    { "modloaderversion", "tModLoader v" + modFile.tModLoaderVersion },
                    { "passphrase", ModLoader.modBrowserPassphrase },
                    { "modreferences", String.Join(", ", bp.modReferences.Select(x => x.mod)) },
                    { "modside", bp.side.ToFriendlyString() },
                };
                if (values["steamid64"].Length != 17)
                {
                    throw new WebException($"The steamid64 '{values["steamid64"]}' is invalid, verify that you are logged into Steam and don't have a pirated copy of Terraria.");
                }
                if (string.IsNullOrEmpty(values["author"]))
                {
                    throw new WebException($"You need to specify an author in build.txt");
                }
                ServicePointManager.Expect100Continue = false;
                string url = "http://javid.ddns.net/tModLoader/publishmod.php";
                uploadTimer = new Stopwatch();
                uploadTimer.Start();
                using (PatientWebClient client = new PatientWebClient()) {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, policyErrors) => true;
                    Interface.progress.Show(displayText: $"Uploading: {modFile.name}", gotoMenu: Interface.modSourcesID, cancel: client.CancelAsync);
                    client.UploadProgressChanged += (s, e) => {
                        double elapsedSeconds = uploadTimer.Elapsed.TotalSeconds;
                        double speed          = elapsedSeconds > 0.0 ? e.BytesSent / elapsedSeconds : 0.0;

                        Interface.progress.SubProgressText = $"{UIMemoryBar.SizeSuffix(e.BytesSent, 2)} / {UIMemoryBar.SizeSuffix(e.TotalBytesToSend, 2)} " +
                                                             $"({UIMemoryBar.SizeSuffix((long)speed, 2)}/s)";

                        Interface.progress.Progress = (float)e.BytesSent / e.TotalBytesToSend;
                    };
                    client.UploadDataCompleted += (s, e) => PublishUploadDataComplete(s, e, modFile);

                    var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", System.Globalization.NumberFormatInfo.InvariantInfo);
                    client.Headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                    //boundary = "--" + boundary;
                    byte[] data = UploadFile.GetUploadFilesRequestData(files, values, boundary);
                    client.UploadDataAsync(new Uri(url), data);
                }
            }
            catch (WebException e) {
                UIModBrowser.LogModBrowserException(e);
            }
        }
Example #13
0
        private static async Task DownloadDatasetDataAsync(QuandlDataset dataset, int to)
        {
            using (PatientWebClient client = new PatientWebClient())
            {
                try
                {
                    string data = await client.DownloadStringTaskAsync(new Uri("https://www.quandl.com/api/v3/datasets/" + dataset.DatabaseCode +
                                                                               "/" + dataset.DatasetCode + "/data.json?api_key=" + Utils.Constants.API_KEY +
                                                                               "&start_date=" + dataset.LastFetch.GetValueOrDefault(DateTime.MinValue).AddDays(1).ToString("yyyy-MM-dd"))); // Add one day because I dont want to include the current newest in the json

                    DataResponse response =
                        JsonConvert.DeserializeObject <DataResponse>(data, new JsonSerializerSettings {
                        ContractResolver = Utils.Converters.MakeUnderscoreContract()
                    });

                    QuandlDatasetData datasetData = response.DatasetData;
                    datasetData.SetBaseDataset(dataset);

                    datasetsFetched++;

                    Utils.ConsoleInformer.PrintProgress("1C", "Fetching dataset [" + dataset.DatasetCode + "]: ", Utils.Helpers.GetPercent(datasetsFetched, to).ToString() + "%");

                    // Replace old uncomplete dataset with new one
                    //ReplaceCompleteDataset(datasetData);
                    //AddCompleteDataset(datasetData);

                    // Insert
                    QuandlDatasetDataGroup datasetGroup = new QuandlDatasetDataGroup()
                    {
                        DatabaseCode = datasetData.DatabaseCode, Datasets = new List <QuandlDatasetData>()
                    };
                    datasetGroup.Datasets.Add(datasetData);
                    PostgresHelpers.QuandlDatasetActions.InsertQuandlDatasetsDataGroup(datasetGroup);
                }
                catch (Exception e)
                {
                    // Add to fetch later (Create datasetgroup if doesnt exists in failed list)
                    if (!failedToFetch.Exists(d => d.DatabaseCode == dataset.DatabaseCode))
                    {
                        failedToFetch.Add(new QuandlDatasetGroup()
                        {
                            DatabaseCode = dataset.DatabaseCode, Datasets = new List <QuandlDataset>()
                        });
                    }

                    failedToFetch.Find(d => d.DatabaseCode == dataset.DatabaseCode).Datasets.Add(dataset);

                    if (e.Message.Contains("(429)"))
                    {
                        // Print only once
                        if (!blocked)
                        {
                            Utils.ConsoleInformer.Inform("Looks like quandl just blocked you");
                        }

                        blocked = true;
                    }

                    // Log
                    Utils.Helpers.Log("Failed to fetch data: from dataset: [" + dataset.DatabaseCode + "/" + dataset.DatasetCode + "] Will try to recover", "Ex: " + e.Message);
                    //errors.Add(new Tuple<string, string>("Failed to fetch data: from dataset: [" + dataset.DatabaseCode + "/" + dataset.DatasetCode + "]", "Ex: " + e.Message));
                }
            }
        }
        private void Publish(UIMouseEvent evt, UIElement listeningElement)
        {
            if (ModLoader.modBrowserPassphrase == "")
            {
                Main.menuMode = Interface.enterPassphraseMenuID;
                Interface.enterPassphraseMenu.SetGotoMenu(Interface.modSourcesID);
                return;
            }
            Main.PlaySound(10, -1, -1, 1);
            try
            {
                TmodFile[] modFiles    = ModLoader.FindMods();
                bool       ok          = false;
                TmodFile   theTModFile = null;
                foreach (TmodFile tModFile in modFiles)
                {
                    if (Path.GetFileName(tModFile.path).Equals(@Path.GetFileName(mod) + @".tmod"))
                    {
                        ok          = true;
                        theTModFile = tModFile;
                    }
                }
                if (!ok)
                {
                    throw new Exception();
                }
                System.Net.ServicePointManager.Expect100Continue = false;
                string filename = @ModLoader.ModPath + @Path.DirectorySeparatorChar + @Path.GetFileName(mod) + @".tmod";
                string url      = "http://javid.ddns.net/tModLoader/publishmod.php";
                using (var iconStream = theTModFile.HasFile("icon.png") ? new MemoryStream(theTModFile.GetFile("icon.png")) : null)
                    using (var stream = File.Open(filename, FileMode.Open))
                    {
                        var files = new List <UploadFile>();
                        files.Add(new IO.UploadFile
                        {
                            Name     = "file",
                            Filename = Path.GetFileName(filename),
                            //    ContentType = "text/plain",
                            Stream = stream
                        }
                                  );
                        if (iconStream != null)
                        {
                            files.Add(new IO.UploadFile
                            {
                                Name     = "iconfile",
                                Filename = "icon.png",
                                Stream   = iconStream
                            }
                                      );
                        }
                        BuildProperties bp     = BuildProperties.ReadModFile(theTModFile);
                        var             values = new NameValueCollection
                        {
                            { "displayname", bp.displayName },
                            { "name", Path.GetFileNameWithoutExtension(filename) },
                            { "version", "v" + bp.version },
                            { "author", bp.author },
                            { "homepage", bp.homepage },
                            { "description", bp.description },
                            { "steamid64", ModLoader.SteamID64 },
                            { "modloaderversion", "tModLoader v" + theTModFile.tModLoaderVersion },
                            { "passphrase", ModLoader.modBrowserPassphrase },
                            { "modreferences", String.Join(", ", bp.modReferences.Select(x => x.mod)) },
                            { "modside", bp.side.ToFriendlyString() },
                        };
                        using (PatientWebClient client = new PatientWebClient())
                        {
                            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return(true); });
                            Interface.uploadMod.SetDownloading(Path.GetFileNameWithoutExtension(filename));
                            Interface.uploadMod.SetCancel(() =>
                            {
                                Main.menuMode = Interface.modSourcesID;
                                client.CancelAsync();
                            });
                            client.UploadProgressChanged += (s, e) => Interface.uploadMod.SetProgress(e);
                            client.UploadDataCompleted   += (s, e) => PublishUploadDataComplete(s, e, theTModFile);

                            var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", System.Globalization.NumberFormatInfo.InvariantInfo);
                            client.Headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                            boundary = "--" + boundary;
                            byte[] data = IO.UploadFile.GetUploadFilesRequestData(files, values);
                            client.UploadDataAsync(new Uri(url), data);
                        }
                        Main.menuMode = Interface.uploadModID;
                    }
            }
            catch (WebException e)
            {
                ErrorLogger.LogModBrowserException(e);
            }
        }