public static Price PrimaryPackagePrice(Download download)
		{
			var package = download.PrimaryPackage();
			if (package == null)
			{
				return null;
			}

			var packagePrice = package.Price;

			var isOnSale = (packagePrice.RecommendedRetailPrice != packagePrice.SevendigitalPrice);

			var currencySymbol = currencySymbolMap[packagePrice.CurrencyCode];

			var rrp = FormatPrice(packagePrice.RecommendedRetailPrice);
			var priceValue = FormatPrice(packagePrice.SevendigitalPrice);
			var formattedRrp = FormatPriceWithSymbol(packagePrice.RecommendedRetailPrice, currencySymbol);
			var formattedPriceValue = FormatPriceWithSymbol(packagePrice.SevendigitalPrice, currencySymbol);

			return new Price
			{
				Currency = new Currency
					{
						Code = packagePrice.CurrencyCode,
						Symbol = currencySymbol
					},
				Rrp = rrp,
				FormattedRrp = formattedRrp,
				Value = priceValue,
				FormattedPrice = formattedPriceValue,
				IsOnSale = isOnSale
			};
		}
Exemplo n.º 2
0
 /// <summary>
 /// Handles the Click event of the btnSave control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 protected void btnSave_Click(object sender, EventArgs e)
 {
     try {
     HttpPostedFile file = fuFile.PostedFile;
     if (file.ContentLength > 0) {
       FileWriter fileWriter = new FileWriter();
       string finalPath = HttpContext.Current.Server.MapPath(DOWNLOAD_PATH) + fuFile.FileName;
       fileWriter.Write(finalPath, file.InputStream);
     }
     Download artifact = null;
     if (!string.IsNullOrEmpty(lblDownloadId.Text)) {
       artifact = new Download(lblDownloadId.Text.Trim());
     }
     else {
       artifact = new Download();
     }
     artifact.DownloadFile = (file.ContentLength > 0) ? DOWNLOAD_PATH + fuFile.FileName : artifact.DownloadFile;
     artifact.Title = txtTitle.Text;
     artifact.Description = HttpUtility.HtmlEncode(txtDescriptor.Value);
     artifact.ForPurchaseOnly = chkForPurchaseOnly.Checked;
     artifact.ContentType = (file.ContentLength > 0) ? file.ContentType : artifact.ContentType;
     artifact.Save(WebUtility.GetUserName());
     chkForPurchaseOnly.Checked = false;
     txtTitle.Text = string.Empty;
     txtDescriptor.Value = string.Empty;
     LoadDownloads();
     Master.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblDownloadSaved"));
       }
       catch (Exception ex) {
     Logger.Error(typeof(downloadedit).Name + ".btnSave_Click", ex);
     Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
       }
 }
		public void ShouldHaveNoPrimaryPackageWhenThereAreNoPackages()
		{
			var download = new Download();

			var primaryPackage = download.PrimaryPackage();

			Assert.That(primaryPackage, Is.Null);
		}
Exemplo n.º 4
0
 public IDisposable Fetch(string aUrl, FileStream aFileStream, IDownloadListener aListener)
 {
     var download = new Download(
         aUrl,
         4096,
         aFileStream,
         aListener);
     download.Start();
     return download;
 }
        /* Methode zum synchronen Download einer Datei */
        public void DownloadSync(string url, Stream destStream, int blockSize,
            DownloadProgress downloadProgress, DownloadEnd downloadEnd,
            DownloadError downloadError)
        {
            // Download-Objekt erzeugen und initialisieren
            Download download = new Download(url, destStream, blockSize,
                downloadProgress, downloadEnd, downloadError);

            // Download synchron starten
            download.PerformDownload();
        }
        /* Methode zum asynchronen Download einer Datei */
        public void DownloadAsync(string url, Stream destStream, int blockSize, 
            DownloadProgress downloadProgress, DownloadEnd downloadEnd,
            DownloadError downloadError)
        {
            // Download-Objekt erzeugen und initialisieren
            Download download = new Download(url, destStream, blockSize,
                downloadProgress, downloadEnd, downloadError);

            // Thread für den Download starten
            Thread downloadThread = new Thread(new ThreadStart(download.PerformDownload));
            downloadThread.Start();
        }
Exemplo n.º 7
0
        private static bool DownloadFile(string pFilename)
        {
            WebClient client = new WebClient();
            client.DownloadFileCompleted += DownloadFileCompleted;
            client.DownloadProgressChanged += DownloadProgressChanged;

            Download download = new Download(pFilename);
            Console.WriteLine("Downloading {0}...", download.DownloadFile);
            download.DownloadEvent.Reset();
            client.DownloadFileAsync(new Uri(sURL + download.DownloadFile), download.DownloadFile, download);
            download.DownloadEvent.WaitOne();

            return download.DownloadResult;
        }
		public static FormatList PrimaryPackageFormats(Download download)
		{
			var package = download.PrimaryPackage();
			if (package == null)
			{
				return null;
			}

			return new FormatList
			{
				AvailableDrmFree = true,
				Formats = package.Formats.Select(ConvertFormat).ToList()
			};
		}
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            var requestAnalyzer = new RequestAnalyzer();
            var download = new Download();
            var redirect = new Redirect();

            var board = new SilkveilBoard(requestAnalyzer, download, redirect);

            using (var stream = new MemoryStream())
            {
                board.Start(stream);
            }

            Console.Read();
        }
Exemplo n.º 10
0
        /// <summary>
        /// Starts downloading the request.
        /// </summary>
        /// <param name="request">The request data.</param>
        /// <param name="originator">The request's originator.</param>
        /// <returns>The active download.</returns>
        protected virtual IDownload DownloadAsync(Request request, INode originator)
        {
            var cancel = new CancellationTokenSource();

            if (_filter(request))
            {
                var task = LoadAsync(request, cancel.Token);
                var download = new Download(task, cancel, request.Address, originator);
                Add(download);
                task.ContinueWith(m => Remove(download));
                return download;
            }

            return new Download(TaskEx.FromResult(default(IResponse)), cancel, request.Address, originator);
        }
		public void ShouldHavePrimaryPackageWhenThereIsOnePackage()
		{
			var download = new Download
			{
				Packages = new List<Package>
				{
					new Package {Id = 123}
				}
			};

			var primaryPackage = download.PrimaryPackage();

			Assert.That(primaryPackage, Is.Not.Null);
			Assert.That(primaryPackage.Id, Is.EqualTo(123));
		}
Exemplo n.º 12
0
 public JsonResult DeleteFile(string models)
 {
     JsonResult result = new JsonResult();
     Download bll = new Download();
     List<sd_download> fileList = new List<sd_download>();
     sd_download info = new sd_download();
     if (models != null)
     {
         var t = JsonConvert.DeserializeObject<List<sd_download>>(models);
         if (t.Count > 0)
         {
             bll.Delete(t);
             result.Data = fileList;
         }
     }
     return result;
 }
		public void ShouldFallBackToFirstPackage()
		{
			var download = new Download
			{
				Packages = new List<Package>
				{
					new Package {Id = 123},
					new Package {Id = 456},
					new Package {Id = 789}
				}
			};

			var primaryPackage = download.PrimaryPackage();

			Assert.That(primaryPackage, Is.Not.Null);
			Assert.That(primaryPackage.Id, Is.EqualTo(123));
		}
		public void ShouldPickStandardPackageIfPresent()
		{
			var download = new Download
			{
				Packages = new List<Package>
				{
					new Package {Id = 123},
					new Package {Id = 456},
					new Package {Id = 2},
					new Package {Id = 789}
				}
			};

			var primaryPackage = download.PrimaryPackage();

			Assert.That(primaryPackage, Is.Not.Null);
			Assert.That(primaryPackage.Id, Is.EqualTo(2));
		}
Exemplo n.º 15
0
 /// <summary>
 /// Handles the Download event of the Delete control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.Web.UI.WebControls.DataGridCommandEventArgs"/> instance containing the event data.</param>
 protected void Delete_Download(object sender, DataGridCommandEventArgs e)
 {
     try {
     int artifactId = 0;
     bool isParsed = int.TryParse(dgDownloads.DataKeys[e.Item.ItemIndex].ToString(), out artifactId);
     if (isParsed) {
       Download artifact = new Download(artifactId);
       File.Delete(Server.MapPath(artifact.DownloadFile));
       Download.Delete(artifactId);
     }
     LoadDownloads();
     txtTitle.Text = string.Empty;
     txtDescriptor.Value = string.Empty;
       }
       catch (Exception ex) {
     Logger.Error(typeof(downloadedit).Name + ".Delete_Download", ex);
     Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
       }
 }
Exemplo n.º 16
0
        public void MultipleHtmlDownload()
        {
            IDocument document = Substitute.For<IDocument>();

            var output = new List<Tuple<Stream, IEnumerable<KeyValuePair<string, object>>>>();

            document
                .When(x => x.Clone(Arg.Any<Stream>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>(), Arg.Any<bool>()))
                .Do(x =>
                {
                    output.Add(Tuple.Create(x.Arg<Stream>(), x.Arg<IEnumerable<KeyValuePair<string, object>>>()));
                });

            IModule download = new Download().Uris("http://www.siwawi.com/", "http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream");
            IExecutionContext context = Substitute.For<IExecutionContext>();

            // When
            download.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

            Console.WriteLine("Length " + output.Count);
            // Then
            foreach(var o in output)
            {
                var headers = o.Item2.FirstOrDefault(x => x.Key == MetadataKeys.SourceHeaders).Value as Dictionary<string, string>;

                Assert.IsNotNull(headers, "Header cannot be null");
                Assert.IsTrue(headers.Count > 0, "Headers must contain contents");

                foreach (var h in headers)
                {
                    Assert.IsNotEmpty(h.Key, "Header key cannot be empty");
                    Assert.IsNotEmpty(h.Value, "Header value cannot be empty");
                    Console.WriteLine($"{h.Key} - {h.Value}");
                }

                o.Item1.Seek(0, SeekOrigin.Begin);
                var content = new StreamReader(o.Item1).ReadToEnd();
                o.Item1.Dispose();

                Assert.IsNotEmpty(content, "Download cannot be empty");
            }
        }
Exemplo n.º 17
0
        public object OnDownload(ISession session, Download e)
        {

            try
            {
                CurrentFolder folder = GetFolder(session);
                string filename = folder.Path + e.File;
                if (!System.IO.File.Exists(filename))
                {
                    return new Error { Message = e.File + " not found!" };
                }
                session["DOWNLOAD_TAG"] = new FileHelper(filename);
                System.IO.FileInfo fi = new System.IO.FileInfo(filename);
                return new FileInfo { Name=fi.Name, Size= fi.Length };
            }
            catch (Exception e_)
            {
                return new Error { Message = e_.Message };
            }
        }
        public DownloadProgress(string currentDownloadID)
        {
            InitializeComponent();
            SourceInitialized += OnSourceInitialized;

            downloadData = Downloads.DownloadEntries.Where(download => download.DownloadID == currentDownloadID).FirstOrDefault();

            currentDownload = Mackerel.currentDownloads[downloadData.DownloadID];

            currentDownload.ResumablityChanged += CurrentDownload_ResumablityChanged;
            currentDownload.ProgressChanged += CurrentDownload_ProgressChanged;
            currentDownload.Completed += CurrentDownload_Completed;
            currentDownload.Error += CurrentDownload_Error;

            //set temporary values before download starts
            this.Title = downloadData.FileName;
            FileSize.Text = Helper.SizeSuffix(downloadData.Size, 3);
            Downloaded.Text = "Checking...";
            TransferRate.Text = "(Unknown)";
            TimeLeft.Text = "(Unknown)";

            DownloadLink.Text = downloadData.DownloadLink.ToString();
            Status.Text = "Connecting...";

            FileSize.Text = Helper.SizeSuffix(downloadData.Size, 3) != null ? Helper.SizeSuffix(downloadData.Size, 3) : "Unknown";

            // enables Mackerel class to stop downloads just by setting downloadData.Running value to false
            Downloads.DownloadEntries.ListChanged += delegate
            {
                if (!downloadData.Running && !currentDownload.Stop)
                {
                    currentDownload.StopDownload();
                    downloadData.TransferRate = null;
                    Close();
                }
            };
        }
Exemplo n.º 19
0
        void ShowDownloadDialog()
        {
            var window = Widget.OpenWindow("INIT_DOWNLOAD");
            var status = window.GetWidget<LabelWidget>("STATUS");
            status.GetText = () => "Initializing...";
            var progress = window.GetWidget<ProgressBarWidget>("PROGRESS");

            // Save the package to a temp file
            var file = Path.GetTempPath() + Path.DirectorySeparatorChar + Path.GetRandomFileName();
            Action<DownloadProgressChangedEventArgs> onDownloadChange = i =>
            {
                status.GetText = () => "Downloading {1}/{2} kB ({0}%)".F(i.ProgressPercentage, i.BytesReceived/1024, i.TotalBytesToReceive/1024);
                progress.Percentage = i.ProgressPercentage;
            };

            Action<AsyncCompletedEventArgs, bool> onDownloadComplete = (i, cancelled) =>
            {
                if (i.Error != null)
                    ShowDownloadError(window, i.Error.Message);
                else if (!cancelled)
                {
                    // Automatically extract
                    status.GetText = () => "Extracting...";
                    progress.Indeterminate = true;
                    var error = false;
                    Action<string> parseOutput = s =>
                    {
                        if (s.Substring(0,5) == "Error")
                        {
                            error = true;
                            ShowDownloadError(window, s);
                        }
                        if (s.Substring(0,6) == "Status")
                            window.GetWidget<LabelWidget>("STATUS").GetText = () => s.Substring(7).Trim();
                    };

                    Action onComplete = () =>
                    {
                        if (!error)
                            Game.RunAfterTick(() => ContinueLoading(Info));
                    };

                    Game.RunAfterTick(() => Game.Utilities.ExtractZipAsync(file, FileSystem.SpecialPackageRoot+Info.PackagePath, parseOutput, onComplete));
                }
            };

            var dl = new Download(Info.PackageURL, file, onDownloadChange, onDownloadComplete);
            window.GetWidget("CANCEL").OnMouseUp = mi => { dl.Cancel(); ShowInstallMethodDialog(); return true; };
            window.GetWidget("RETRY").OnMouseUp = mi => { dl.Cancel(); ShowDownloadDialog(); return true; };
        }
Exemplo n.º 20
0
        internal void DownloadFileBlocking(string download_url, string download_dest)
        {
            Download dl = new Download(this.downloadsIndex, download_url, download_dest, null, null);

            Downloaders.AbstractDownloader downloader = this.GetDownloader(BLOCKING_DOWNLOAD_ID, dl);
            downloader.Status += new Downloaders.StatusHandler( this.OnDownloadStatus );
            downloader.Finished += new Downloaders.FinishedHandler( this.DownloadFinishedCallback );

            downloader.Download ();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Server Update Call
        /// </summary>
        public string Update()
        {
            if (!clientSocket.Connected)
            {
                Connect();
            }

            CleanStream();

            //Sockets Connection
            //Debug - Log Times
            Stopwatch timer = new Stopwatch();

            timer.Start();

            serverStream = clientSocket.GetStream();
            byte[] outStream = Encoding.ASCII.GetBytes("Request=Update");
            byte[] outSize   = BitConverter.GetBytes(outStream.Length);

            Log.Write("Raw Data: " + BitConverter.ToInt32(outSize, 0) + " -> " + Encoding.ASCII.GetString(outStream));

            //Write Bytes
            serverStream.Write(outSize, 0, outSize.Length);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            //Wait for Response - TODO: Add Recieve Byte outSize

            byte[] size = new byte[4];

            serverStream.Read(size, 0, size.Length);

            byte[] bytesFrom = new byte[BitConverter.ToInt32(size, 0)];

            Log.Write("ExpectedSize: " + BitConverter.ToInt32(size, 0) + " bytesFrom Length: " + bytesFrom.Length);

            serverStream.Read(bytesFrom, 0, bytesFrom.Length);

            string returndata = Encoding.ASCII.GetString(bytesFrom); //Out of memory????

            Log.Write("Data from Server: " + returndata);

            if (Request.Contains("Size", returndata))
            {
                long ExpectedSize = Convert.ToInt64(Request.Get("Size", returndata));

                Download download = new Download(serverStream, Environment.CurrentDirectory + "\\Update.zip", ExpectedSize);
                download.ShowDialog();

                if (download.Done)
                {
                    Log.Write("Download Completed: Update.zip -> Size: " + ExpectedSize);

                    return("Download Completed");
                }
                else
                {
                    Log.Write("Download Failed: Update.zip -> Size: " + ExpectedSize);

                    return("Download Failed");
                }
            }
            else
            {
                Console.WriteLine("Size Parameter was not provided");
            }

            Log.Write(timer.Elapsed.TotalMilliseconds + "ms");

            timer.Reset();

            return(returndata);
        }
Exemplo n.º 22
0
 /// <summary>
 /// Inserts a download
 /// </summary>
 /// <param name="download">Download</param>
 public virtual void InsertDownload(Download download)
 {
     _downloadRepository.Insert(download);
 }
Exemplo n.º 23
0
        void ShowDownloadDialog()
        {
            getStatusText             = () => "Fetching list of mirrors...";
            progressBar.Indeterminate = true;

            var retryButton = panel.Get <ButtonWidget>("RETRY_BUTTON");

            retryButton.IsVisible = () => false;

            var cancelButton = panel.Get <ButtonWidget>("CANCEL_BUTTON");

            var file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Action deleteTempFile = () =>
            {
                Log.Write("install", "Deleting temporary file " + file);
                File.Delete(file);
            };

            Action <DownloadProgressChangedEventArgs> onDownloadProgress = i =>
            {
                var dataReceived = 0.0f;
                var dataTotal    = 0.0f;
                var mag          = 0;
                var dataSuffix   = "";

                if (i.TotalBytesToReceive < 0)
                {
                    dataTotal    = float.NaN;
                    dataReceived = i.BytesReceived;
                    dataSuffix   = SizeSuffixes[0];
                }
                else
                {
                    mag          = (int)Math.Log(i.TotalBytesToReceive, 1024);
                    dataTotal    = i.TotalBytesToReceive / (float)(1L << (mag * 10));
                    dataReceived = i.BytesReceived / (float)(1L << (mag * 10));
                    dataSuffix   = SizeSuffixes[mag];
                }

                progressBar.Indeterminate = false;
                progressBar.Percentage    = i.ProgressPercentage;

                getStatusText = () => "Downloading from {4} {1:0.00}/{2:0.00} {3} ({0}%)".F(i.ProgressPercentage,
                                                                                            dataReceived, dataTotal, dataSuffix,
                                                                                            downloadHost ?? "unknown host");
            };

            Action <string> onExtractProgress = s => Game.RunAfterTick(() => getStatusText = () => s);

            Action <string> onError = s => Game.RunAfterTick(() =>
            {
                Log.Write("install", "Download failed: " + s);

                progressBar.Indeterminate = false;
                progressBar.Percentage    = 100;
                getStatusText             = () => "Error: " + s;
                retryButton.IsVisible     = () => true;
                cancelButton.OnClick      = Ui.CloseWindow;
            });

            Action <AsyncCompletedEventArgs> onDownloadComplete = i =>
            {
                if (i.Cancelled)
                {
                    deleteTempFile();
                    Game.RunAfterTick(Ui.CloseWindow);
                    return;
                }

                if (i.Error != null)
                {
                    deleteTempFile();
                    onError(Download.FormatErrorMessage(i.Error));
                    return;
                }

                // Automatically extract
                getStatusText             = () => "Extracting...";
                progressBar.Indeterminate = true;

                var extracted = new List <string>();
                try
                {
                    using (var stream = File.OpenRead(file))
                        using (var z = ZipFileHelper.Create(stream))
                        {
                            foreach (var kv in download.Extract)
                            {
                                var entry = z.GetEntry(kv.Value);
                                if (entry == null || !entry.IsFile)
                                {
                                    continue;
                                }

                                onExtractProgress("Extracting " + entry.Name);
                                Log.Write("install", "Extracting " + entry.Name);
                                var targetPath = Platform.ResolvePath(kv.Key);
                                Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
                                extracted.Add(targetPath);

                                using (var zz = z.GetInputStream(entry))
                                    using (var f = File.Create(targetPath))
                                        zz.CopyTo(f);
                            }

                            z.Close();
                        }

                    Game.RunAfterTick(() => { Ui.CloseWindow(); onSuccess(); });
                }
                catch (Exception e)
                {
                    Log.Write("install", "Archive extraction failed: " + e.ToString());

                    foreach (var f in extracted)
                    {
                        Log.Write("install", "Deleting " + f);
                        File.Delete(f);
                    }

                    onError("Archive extraction failed");
                }
                finally
                {
                    deleteTempFile();
                }
            };

            Action <string> downloadUrl = url =>
            {
                Log.Write("install", "Downloading " + url);

                downloadHost = new Uri(url).Host;
                var dl = new Download(url, file, onDownloadProgress, onDownloadComplete);
                cancelButton.OnClick = dl.CancelAsync;
                retryButton.OnClick  = ShowDownloadDialog;
            };

            if (download.MirrorList != null)
            {
                Log.Write("install", "Fetching mirrors from " + download.MirrorList);

                Action <DownloadDataCompletedEventArgs> onFetchMirrorsComplete = i =>
                {
                    progressBar.Indeterminate = true;

                    if (i.Cancelled)
                    {
                        Game.RunAfterTick(Ui.CloseWindow);
                        return;
                    }

                    if (i.Error != null)
                    {
                        onError(Download.FormatErrorMessage(i.Error));
                        return;
                    }

                    try
                    {
                        var data       = Encoding.UTF8.GetString(i.Result);
                        var mirrorList = data.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        downloadUrl(mirrorList.Random(new MersenneTwister()));
                    }
                    catch (Exception e)
                    {
                        Log.Write("install", "Mirror selection failed with error:");
                        Log.Write("install", e.ToString());
                        onError("Online mirror is not available. Please install from an original disc.");
                    }
                };

                var updateMirrors = new Download(download.MirrorList, onDownloadProgress, onFetchMirrorsComplete);
                cancelButton.OnClick = updateMirrors.CancelAsync;
                retryButton.OnClick  = ShowDownloadDialog;
            }
            else
            {
                downloadUrl(download.URL);
            }
        }
Exemplo n.º 24
0
        private async Task <string> GetDefaultConfig(string model)
        {
            if (await Download.getFilefromNetAsync(
                    "https://raw.githubusercontent.com/ArduPilot/ardupilot/master/Tools/autotest/sim_vehicle.py",
                    sitldirectory + "sim_vehicle.py").ConfigureAwait(false) || File.Exists(sitldirectory + "sim_vehicle.py"))
            {
                var matches = default_params_regex.Matches(File.ReadAllText(sitldirectory + "sim_vehicle.py"));

                foreach (Match match in matches)
                {
                    if (match.Groups[1].Value.ToLower().Equals(model))
                    {
                        if (await Download.getFilefromNetAsync(
                                "https://raw.githubusercontent.com/ArduPilot/ardupilot/master/Tools/autotest/" +
                                match.Groups[2].Value.ToString(),
                                sitldirectory + match.Groups[2].Value.ToString()).ConfigureAwait(false) || File.Exists(sitldirectory + match.Groups[2].Value.ToString()))
                        {
                            return(sitldirectory + match.Groups[2].Value.ToString());
                        }
                    }
                }
            }

            if (await Download.getFilefromNetAsync(
                    "https://firmware.ardupilot.org/Tools/MissionPlanner/vehicleinfo.py",
                    sitldirectory + "vehicleinfo.py").ConfigureAwait(false) || File.Exists(sitldirectory + "vehicleinfo.py"))
            {
                try
                {
                    cleanupJson(sitldirectory + "vehicleinfo.py");

                    using (Newtonsoft.Json.JsonTextReader reader =
                               new JsonTextReader(File.OpenText(sitldirectory + "vehicleinfo.py")))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        var            obj        = (JObject)serializer.Deserialize(reader);

                        if (obj == null)
                        {
                            return("");
                        }

                        foreach (var fwtype in obj)
                        {
                            var frames = fwtype.Value["frames"];

                            if (frames == null)
                            {
                                continue;
                            }

                            var config = frames[model];

                            if (config == null)
                            {
                                continue;
                            }

                            var configs = config["default_params_filename"];

                            if (configs is JValue)
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(sitldirectory + configs.ToString()));

                                if (await Download.getFilefromNetAsync(
                                        "https://raw.githubusercontent.com/ArduPilot/ardupilot/master/Tools/autotest/" +
                                        configs.ToString(),
                                        sitldirectory + configs.ToString()).ConfigureAwait(false) ||
                                    File.Exists(sitldirectory + configs.ToString()))
                                {
                                    return(sitldirectory + configs.ToString());
                                }
                            }

                            string data = "";

                            foreach (var config1 in configs)
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(sitldirectory + config1.ToString()));

                                if (await Download.getFilefromNetAsync(
                                        "https://raw.githubusercontent.com/ArduPilot/ardupilot/master/Tools/autotest/" +
                                        config1.ToString(),
                                        sitldirectory + config1.ToString()).ConfigureAwait(false) ||
                                    File.Exists(sitldirectory + config1.ToString()))
                                {
                                    data += "\r\n" + File.ReadAllText(sitldirectory + config1.ToString());
                                }
                            }

                            var temp = Path.GetTempFileName();
                            File.WriteAllText(temp, data);
                            return(temp);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    Console.WriteLine(ex.ToString());
                }
            }
            return("");
        }
Exemplo n.º 25
0
 /// <summary>
 /// Deletes a download
 /// </summary>
 /// <param name="download">Download</param>
 public virtual void DeleteDownload(Download download)
 {
     _downloadRepository.Delete(download);
 }
Exemplo n.º 26
0
        internal override void OnMessage(string method, JsonElement?serverParams)
        {
            switch (method)
            {
            case "close":
                Closed?.Invoke(this, EventArgs.Empty);
                break;

            case "crash":
                Crashed?.Invoke(this, EventArgs.Empty);
                break;

            case "domcontentloaded":
                DOMContentLoaded?.Invoke(this, EventArgs.Empty);
                break;

            case "load":
                Load?.Invoke(this, EventArgs.Empty);
                break;

            case "bindingCall":
                BindingCall?.Invoke(
                    this,
                    new BindingCallEventArgs
                {
                    BidingCall = serverParams?.GetProperty("binding").ToObject <BindingCallChannel>(Connection.GetDefaultJsonSerializerOptions()).Object,
                });
                break;

            case "route":
                Route?.Invoke(
                    this,
                    new RouteEventArgs
                {
                    Route   = serverParams?.GetProperty("route").ToObject <RouteChannel>(Connection.GetDefaultJsonSerializerOptions()).Object,
                    Request = serverParams?.GetProperty("request").ToObject <RequestChannel>(Connection.GetDefaultJsonSerializerOptions()).Object,
                });
                break;

            case "popup":
                Popup?.Invoke(this, new PageChannelPopupEventArgs
                {
                    Page = serverParams?.GetProperty("page").ToObject <PageChannel>(Connection.GetDefaultJsonSerializerOptions()).Object,
                });
                break;

            case "pageError":
                PageError?.Invoke(this, serverParams?.GetProperty("error").GetProperty("error").ToObject <PageErrorEventArgs>(Connection.GetDefaultJsonSerializerOptions()));
                break;

            case "fileChooser":
                FileChooser?.Invoke(this, serverParams?.ToObject <FileChooserChannelEventArgs>(Connection.GetDefaultJsonSerializerOptions()));
                break;

            case "frameAttached":
                FrameAttached?.Invoke(this, new FrameEventArgs(serverParams?.GetProperty("frame").ToObject <FrameChannel>(Connection.GetDefaultJsonSerializerOptions()).Object));
                break;

            case "frameDetached":
                FrameDetached?.Invoke(this, new FrameEventArgs(serverParams?.GetProperty("frame").ToObject <FrameChannel>(Connection.GetDefaultJsonSerializerOptions()).Object));
                break;

            case "dialog":
                Dialog?.Invoke(this, new DialogEventArgs(serverParams?.GetProperty("dialog").ToObject <DialogChannel>(Connection.GetDefaultJsonSerializerOptions()).Object));
                break;

            case "console":
                Console?.Invoke(this, new ConsoleEventArgs(serverParams?.GetProperty("message").ToObject <ConsoleMessage>(Connection.GetDefaultJsonSerializerOptions())));
                break;

            case "request":
                Request?.Invoke(this, new RequestEventArgs {
                    Request = serverParams?.GetProperty("request").ToObject <RequestChannel>(Connection.GetDefaultJsonSerializerOptions()).Object
                });
                break;

            case "requestFinished":
                RequestFinished?.Invoke(this, serverParams?.ToObject <PageChannelRequestEventArgs>(Connection.GetDefaultJsonSerializerOptions()));
                break;

            case "requestFailed":
                RequestFailed?.Invoke(this, serverParams?.ToObject <PageChannelRequestEventArgs>(Connection.GetDefaultJsonSerializerOptions()));
                break;

            case "response":
                Response?.Invoke(this, new ResponseEventArgs {
                    Response = serverParams?.GetProperty("response").ToObject <ResponseChannel>(Connection.GetDefaultJsonSerializerOptions()).Object
                });
                break;

            case "webSocket":
                WebSocket?.Invoke(this, new WebSocketEventArgs {
                    WebSocket = serverParams?.GetProperty("webSocket").ToObject <WebSocketChannel>(Connection.GetDefaultJsonSerializerOptions()).Object
                });
                break;

            case "download":
                Download?.Invoke(this, new DownloadEventArgs()
                {
                    Download = serverParams?.GetProperty("download").ToObject <DownloadChannel>(Connection.GetDefaultJsonSerializerOptions()).Object
                });
                break;

            case "video":
                Video?.Invoke(this, new VideoEventArgs()
                {
                    RelativePath = serverParams?.GetProperty("relativePath").ToString()
                });
                break;

            case "worker":
                Worker?.Invoke(
                    this,
                    new WorkerChannelEventArgs
                {
                    WorkerChannel = serverParams?.GetProperty("worker").ToObject <WorkerChannel>(Connection.GetDefaultJsonSerializerOptions()),
                });
                break;
            }
        }
Exemplo n.º 27
0
        public Client(ISettings settings)
        {
            if (settings.UsePogoDevHashServer)
            {
                if (string.IsNullOrEmpty(settings.AuthAPIKey))
                {
                    throw new AuthConfigException("You have selected Pogodev API but not provide proper API Key");
                }

                Cryptor = new Crypto(); // 0.61.0

                // This value will determine which version of the hashing service you will receive.
                // Currently supported versions:
                // v119   -> Pogo iOS 1.19
                // v121   -> Pogo iOS 1.21
                // v121_2 -> Pogo iOS 1.22
                // v125   -> Pogo iOS 1.25
                // v127_2 -> Pogo iOS 1.27.2
                // v127_3 -> Pogo iOS 1.27.3
                // v127_4 -> Pogo iOS 1.27.4
                // v129_1 -> Pogo iOS 1.29.1
                // v131_0 -> Pogo iOS 1.31.0

                ApiEndPoint = "api/v131_0/hash"; // 0.61.0

                Hasher = new PokefamerHasher(settings.AuthAPIKey, settings.DisplayVerboseLog, ApiEndPoint);

                // These 4 constants below need to change if we update the hashing server API version that is used.

                //Unknown25 = -816976800928766045; // 0.59.1
                Unknown25 = 1296456256998993698; // 0.61.0


                // WARNING! IF YOU CHANGE THE APPVERSION BELOW ALSO UPDATE THE API_VERSION AT THE TOP OF THE FILE!
                //AppVersion = 5704;
                AppVersion = 6100; // 0.61.0

                CurrentApiEmulationVersion = new Version(API_VERSION);
                UnknownPlat8Field          = "90f6a704505bccac73cec99b07794993e6fd5a12";
            }

            /*
             * else
             * if (settings.UseLegacyAPI)
             * {
             *  Hasher = new LegacyHashser();
             *  Cryptor = new LegacyCrypt();
             *
             *  Unknown25 = -816976800928766045;// - 816976800928766045;// - 1553869577012279119;
             *  AppVersion = 4500;
             *  CurrentApiEmulationVersion = new Version("0.45.0");
             * }
             */
            else
            {
                throw new AuthConfigException("No API method being select in your auth.json");
            }

            Settings          = settings;
            Proxy             = InitProxy();
            PokemonHttpClient = new PokemonHttpClient();
            Login             = new Login(this);
            Player            = new Player(this);
            Download          = new Download(this);
            Inventory         = new Inventory(this);
            Map            = new Map(this);
            Fort           = new Fort(this);
            Encounter      = new Encounter(this);
            Misc           = new Misc(this);
            KillswitchTask = new KillSwitchTask(this);

            Player.SetCoordinates(Settings.DefaultLatitude, Settings.DefaultLongitude, Settings.DefaultAltitude);
            Platform = settings.DevicePlatform.Equals("ios", StringComparison.Ordinal) ? Platform.Ios : Platform.Android;

            // We can no longer emulate Android so for now just overwrite settings with randomly generated iOS device info.
            if (Platform == Platform.Android)
            {
                Signature.Types.DeviceInfo iosInfo = DeviceInfoHelper.GetRandomIosDevice();
                settings.DeviceId             = iosInfo.DeviceId;
                settings.DeviceBrand          = iosInfo.DeviceBrand;
                settings.DeviceModel          = iosInfo.DeviceModel;
                settings.DeviceModelBoot      = iosInfo.DeviceModelBoot;
                settings.HardwareManufacturer = iosInfo.HardwareManufacturer;
                settings.HardwareModel        = iosInfo.HardwareModel;
                settings.FirmwareBrand        = iosInfo.FirmwareBrand;
                settings.FirmwareType         = iosInfo.FirmwareType;

                // Clear out the android fields.
                settings.AndroidBoardName      = "";
                settings.AndroidBootloader     = "";
                settings.DeviceModelIdentifier = "";
                settings.FirmwareTags          = "";
                settings.FirmwareFingerprint   = "";

                // Now set the client platform to ios
                Platform = Platform.Ios;
            }
        }
Exemplo n.º 28
0
        public void SalvarDownloadBD(Download objDown)
        {
            iObjDownData.ConexaoBanco();

            //Salva no BD
        }
Exemplo n.º 29
0
 public ActionResult NovoDownload(Download objDown)
 {
     iObjDownBusiness.SalvarDownloadBD(objDown);
     return(View());
 }
Exemplo n.º 30
0
        private async void myDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // Ignore clicks that are not on button cells.
            if (e.RowIndex < 0 || e.ColumnIndex !=
                myDataGridView1.Columns["updateDataGridViewTextBoxColumn"].Index &&
                e.ColumnIndex != myDataGridView1.Columns["Parameter"].Index)
            {
                return;
            }

            byte nodeID = (byte)myDataGridView1[iDDataGridViewTextBoxColumn.Index, e.RowIndex].Value;

            if (e.ColumnIndex == myDataGridView1.Columns["Parameter"].Index)
            {
                IProgressReporterDialogue prd = new ProgressReporterDialogue();
                List <uavcan.uavcan_protocol_param_GetSet_res> paramlist =
                    new List <uavcan.uavcan_protocol_param_GetSet_res>();
                prd.DoWork += dialogue =>
                {
                    paramlist = can.GetParameters(nodeID);
                };
                prd.UpdateProgressAndStatus(-1, Strings.GettingParams);
                prd.RunBackgroundOperationAsync();

                new UAVCANParams(can, nodeID, paramlist).ShowUserControl();
            }
            else if (e.ColumnIndex == myDataGridView1.Columns["updateDataGridViewTextBoxColumn"].Index)
            {
                ProgressReporterDialogue    prd      = new ProgressReporterDialogue();
                uavcan.FileSendProgressArgs filesend = (id, file, percent) =>
                {
                    prd.UpdateProgressAndStatus((int)percent, id + " " + file);
                };
                can.FileSendProgress += filesend;
                if (CustomMessageBox.Show("Do you want to search the internet for an update?", "Update", CustomMessageBox.MessageBoxButtons.YesNo) == CustomMessageBox.DialogResult.Yes)
                {
                    var devicename = myDataGridView1[nameDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
                    var hwversion  = double.Parse(myDataGridView1[hardwareVersionDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString(), CultureInfo.InvariantCulture);

                    var url = can.LookForUpdate(devicename, hwversion);

                    if (url != string.Empty)
                    {
                        try
                        {
                            prd.DoWork += dialogue =>
                            {
                                var tempfile = Path.GetTempFileName();
                                Download.getFilefromNet(url, tempfile);

                                try
                                {
                                    can.Update(nodeID, devicename, hwversion, tempfile);
                                }
                                catch (Exception ex)
                                {
                                    throw;
                                }

                                return;
                            };

                            prd.RunBackgroundOperationAsync();
                        }
                        catch (Exception ex)
                        {
                            CustomMessageBox.Show(ex.Message, Strings.ERROR);
                        }
                    }
                    else
                    {
                        CustomMessageBox.Show(Strings.UpdateNotFound, Strings.UpdateNotFound);
                    }
                }
                else
                {
                    FileDialog fd = new OpenFileDialog();
                    fd.RestoreDirectory = true;
                    fd.Filter           = "*.bin|*.bin";
                    var dia = fd.ShowDialog();

                    if (fd.CheckFileExists && dia == DialogResult.OK)
                    {
                        try
                        {
                            prd.DoWork += dialogue =>
                            {
                                can.Update(nodeID, myDataGridView1[nameDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString(), 0,
                                           fd.FileName);

                                return;
                            };

                            prd.RunBackgroundOperationAsync();
                        }
                        catch (Exception ex)
                        {
                            CustomMessageBox.Show(ex.Message, Strings.ERROR);
                        }
                    }
                }
                can.FileSendProgress -= filesend;
                prd.Dispose();
            }
        }
Exemplo n.º 31
0
        public void ShouldRejectBasicAuth_without_username()
        {
            var d = new Download(From, To, auth: Download.AuthType.basic, username: null, password: "******");

            assertInitializationFails(d, "Basic Auth is enabled, but username is not specified");
        }
Exemplo n.º 32
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            #region DEBUG初始化
            //debug
            logHandler = new LogHandler(true);
            AggregateExceptionCatched += (a, b) => logHandler.AppendFatal(b.AggregateException);
            if (e.Args.Contains("-debug"))
            {
                Windows.DebugWindow debugWindow = new Windows.DebugWindow();
                debugWindow.Show();
                logHandler.OnLog += (s, log) => debugWindow?.AppendLog(s, log);
            }
            #endregion

            config = new ConfigHandler();

            #region DEBUG初始化(基于配置文件)
            if (config.MainConfig.Launcher.Debug && !e.Args.Contains("-debug"))
            {
                Windows.DebugWindow debugWindow = new Windows.DebugWindow();
                debugWindow.Show();
                logHandler.OnLog += (s, log) => debugWindow?.AppendLog(s, log);
            }
            #endregion

            #region MineRealms反馈API初始化

#if DEBUG
            MineRealmsAPIHandler = new MineRealmsLauncherCore.Net.PhalAPI.APIHandler(true);
#else
            MineRealmsAPIHandler = new MineRealmsLauncherCore.Net.PhalAPI.APIHandler(config.MainConfig.Launcher.NoTracking);
#endif

            #endregion

            #region 数据初始化
            Config.Environment env = config.MainConfig.Environment;

            javaList = Java.GetJavaList();

            //设置版本路径
            string gameroot = null;
            switch (env.GamePathType)
            {
            case GameDirEnum.ROOT:
                gameroot = Path.GetFullPath(".minecraft");
                break;

            case GameDirEnum.APPDATA:
                gameroot = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\.minecraft";
                break;

            case GameDirEnum.PROGRAMFILES:
                gameroot = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\.minecraft";
                break;

            case GameDirEnum.CUSTOM:
                gameroot = env.GamePath + "\\.minecraft";
                break;

            default:
                throw new ArgumentException("判断游戏目录类型时出现异常,请检查配置文件中GamePathType节点");
            }
            logHandler.AppendInfo("核心初始化->游戏根目录(默认则为空):" + gameroot);

            //设置JAVA
            Java java = null;
            if (env.AutoJava)
            {
                java = Java.GetSuitableJava(javaList);
            }
            else
            {
                java = javaList.Find(x => x.Path == env.JavaPath);
                if (java == null)
                {
                    java = Java.GetJavaInfo(env.JavaPath);
                }
            }
            if (java != null)
            {
                env.JavaPath = java.Path;
                logHandler.AppendInfo("核心初始化->Java路径:" + java.Path);
                logHandler.AppendInfo("核心初始化->Java版本:" + java.Version);
                logHandler.AppendInfo("核心初始化->Java位数:" + java.Arch);
            }
            else
            {
                logHandler.AppendWarn("核心初始化失败,当前电脑未匹配到JAVA");
            }

            //设置版本独立
            bool verIso = config.MainConfig.Environment.VersionIsolation;
            #endregion

            #region 启动核心初始化
            handler          = new LaunchHandler(gameroot, java, verIso);
            handler.GameLog += (s, log) => logHandler.AppendLog(s, new Log()
            {
                LogLevel = LogLevel.GAME, Message = log
            });
            handler.LaunchLog += (s, log) => logHandler.AppendLog(s, log);
            #endregion

            #region  载核心初始化
            ServicePointManager.DefaultConnectionLimit = 10;

            Download downloadCfg = config.MainConfig.Download;
            downloader = new MultiThreadDownloader();
            if (!string.IsNullOrWhiteSpace(downloadCfg.DownloadProxyAddress))
            {
                WebProxy proxy = new WebProxy(downloadCfg.DownloadProxyAddress, downloadCfg.DownloadProxyPort);
                if (!string.IsNullOrWhiteSpace(downloadCfg.ProxyUserName))
                {
                    NetworkCredential credential = new NetworkCredential(downloadCfg.ProxyUserName, downloadCfg.ProxyUserPassword);
                    proxy.Credentials = credential;
                }
                downloader.Proxy = proxy;
            }
            downloader.ProcessorSize = App.config.MainConfig.Download.DownloadThreadsSize;
            downloader.CheckFileHash = App.config.MainConfig.Download.CheckDownloadFileHash;
            downloader.DownloadLog  += (s, log) => logHandler?.AppendLog(s, log);
            #endregion

            #region 自定义主题初始化
            var custom = config.MainConfig.Customize;
            if (!string.IsNullOrWhiteSpace(custom.AccentColor) && !string.IsNullOrWhiteSpace(custom.AppThme))
            {
                logHandler.AppendInfo("自定义->更改主题颜色:" + custom.AccentColor);
                logHandler.AppendInfo("自定义->更改主题:" + custom.AppThme);
                ThemeManager.ChangeAppStyle(Current, ThemeManager.GetAccent(custom.AccentColor), ThemeManager.GetAppTheme(custom.AppThme));
            }
            #endregion
        }
Exemplo n.º 33
0
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product to copy</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
        /// <returns>Product copy</returns>
        public virtual Product CopyProduct(Product product, string newName,
                                           bool isPublished = true, bool copyImages = true, bool copyAssociatedProducts = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            if (String.IsNullOrEmpty(newName))
            {
                throw new ArgumentException("Product name is required");
            }

            //product download & sample download
            int downloadId       = product.DownloadId;
            int sampleDownloadId = product.SampleDownloadId;

            if (product.IsDownload)
            {
                var download = _downloadService.GetDownloadById(product.DownloadId);
                if (download != null)
                {
                    var downloadCopy = new Download
                    {
                        DownloadGuid   = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl    = download.DownloadUrl,
                        DownloadBinary = download.DownloadBinary,
                        ContentType    = download.ContentType,
                        Filename       = download.Filename,
                        Extension      = download.Extension,
                        IsNew          = download.IsNew,
                    };
                    _downloadService.InsertDownload(downloadCopy);
                    downloadId = downloadCopy.Id;
                }

                if (product.HasSampleDownload)
                {
                    var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId);
                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download
                        {
                            DownloadGuid   = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl    = sampleDownload.DownloadUrl,
                            DownloadBinary = sampleDownload.DownloadBinary,
                            ContentType    = sampleDownload.ContentType,
                            Filename       = sampleDownload.Filename,
                            Extension      = sampleDownload.Extension,
                            IsNew          = sampleDownload.IsNew
                        };
                        _downloadService.InsertDownload(sampleDownloadCopy);
                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            // product
            var productCopy = new Product
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                VendorId             = product.VendorId,
                ProductTemplateId    = product.ProductTemplateId,
                AdminComment         = product.AdminComment,
                ShowOnHomePage       = product.ShowOnHomePage,
                MetaKeywords         = product.MetaKeywords,
                MetaDescription      = product.MetaDescription,
                MetaTitle            = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores      = product.LimitedToStores,
                Sku = product.Sku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin                             = product.Gtin,
                IsGiftCard                       = product.IsGiftCard,
                GiftCardType                     = product.GiftCardType,
                OverriddenGiftCardAmount         = product.OverriddenGiftCardAmount,
                RequireOtherProducts             = product.RequireOtherProducts,
                RequiredProductIds               = product.RequiredProductIds,
                AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
                IsDownload                       = product.IsDownload,
                DownloadId                       = downloadId,
                UnlimitedDownloads               = product.UnlimitedDownloads,
                MaxNumberOfDownloads             = product.MaxNumberOfDownloads,
                DownloadExpirationDays           = product.DownloadExpirationDays,
                DownloadActivationType           = product.DownloadActivationType,
                HasSampleDownload                = product.HasSampleDownload,
                SampleDownloadId                 = sampleDownloadId,
                HasUserAgreement                 = product.HasUserAgreement,
                UserAgreementText                = product.UserAgreementText,
                IsRecurring                      = product.IsRecurring,
                RecurringCycleLength             = product.RecurringCycleLength,
                RecurringCyclePeriod             = product.RecurringCyclePeriod,
                RecurringTotalCycles             = product.RecurringTotalCycles,
                IsRental                         = product.IsRental,
                RentalPriceLength                = product.RentalPriceLength,
                RentalPricePeriod                = product.RentalPricePeriod,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                ShipSeparately                   = product.ShipSeparately,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                DeliveryDateId                   = product.DeliveryDateId,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                IsTelecommunicationsOrBroadcastingOrElectronicServices = product.IsTelecommunicationsOrBroadcastingOrElectronicServices,
                ManageInventoryMethod         = product.ManageInventoryMethod,
                UseMultipleWarehouses         = product.UseMultipleWarehouses,
                WarehouseId                   = product.WarehouseId,
                StockQuantity                 = product.StockQuantity,
                DisplayStockAvailability      = product.DisplayStockAvailability,
                DisplayStockQuantity          = product.DisplayStockQuantity,
                MinStockQuantity              = product.MinStockQuantity,
                LowStockActivityId            = product.LowStockActivityId,
                NotifyAdminForQuantityBelow   = product.NotifyAdminForQuantityBelow,
                BackorderMode                 = product.BackorderMode,
                AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions,
                OrderMinimumQuantity          = product.OrderMinimumQuantity,
                OrderMaximumQuantity          = product.OrderMaximumQuantity,
                AllowedQuantities             = product.AllowedQuantities,
                AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations,
                DisableBuyButton      = product.DisableBuyButton,
                DisableWishlistButton = product.DisableWishlistButton,
                AvailableForPreOrder  = product.AvailableForPreOrder,
                PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc,
                CallForPrice = product.CallForPrice,
                Price        = product.Price,
                OldPrice     = product.OldPrice,
                ProductCost  = product.ProductCost,
                SpecialPrice = product.SpecialPrice,
                SpecialPriceStartDateTimeUtc = product.SpecialPriceStartDateTimeUtc,
                SpecialPriceEndDateTimeUtc   = product.SpecialPriceEndDateTimeUtc,
                CustomerEntersPrice          = product.CustomerEntersPrice,
                MinimumCustomerEnteredPrice  = product.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice  = product.MaximumCustomerEnteredPrice,
                BasepriceEnabled             = product.BasepriceEnabled,
                BasepriceAmount           = product.BasepriceAmount,
                BasepriceUnitId           = product.BasepriceUnitId,
                BasepriceBaseAmount       = product.BasepriceBaseAmount,
                BasepriceBaseUnitId       = product.BasepriceBaseUnitId,
                MarkAsNew                 = product.MarkAsNew,
                MarkAsNewStartDateTimeUtc = product.MarkAsNewStartDateTimeUtc,
                MarkAsNewEndDateTimeUtc   = product.MarkAsNewEndDateTimeUtc,
                Weight = product.Weight,
                Length = product.Length,
                Width  = product.Width,
                Height = product.Height,
                AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc   = product.AvailableEndDateTimeUtc,
                DisplayOrder = product.DisplayOrder,
                Published    = isPublished,
                Deleted      = product.Deleted,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow
            };

            //validate search engine name
            _productService.InsertProduct(productCopy);

            //search engine name
            _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

            var languages = _languageService.GetAllLanguages(true);

            //localization
            foreach (var lang in languages)
            {
                var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                if (!String.IsNullOrEmpty(name))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
                }

                var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(shortDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
                }

                var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(fullDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
                }

                var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaKeywords))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
                }

                var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
                }

                var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaTitle))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
                }

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
            }

            //product tags
            foreach (var productTag in product.ProductTags)
            {
                productCopy.ProductTags.Add(productTag);
            }
            _productService.UpdateProduct(productCopy);

            //product pictures
            //variable to store original and new picture identifiers
            var originalNewPictureIdentifiers = new Dictionary <int, int>();

            if (copyImages)
            {
                foreach (var productPicture in product.ProductPictures)
                {
                    var picture     = productPicture.Picture;
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(newName),
                        picture.AltAttribute,
                        picture.TitleAttribute);
                    _productService.InsertProductPicture(new ProductPicture
                    {
                        ProductId    = productCopy.Id,
                        PictureId    = pictureCopy.Id,
                        DisplayOrder = productPicture.DisplayOrder
                    });
                    originalNewPictureIdentifiers.Add(picture.Id, pictureCopy.Id);
                }
            }

            // product <-> warehouses mappings
            foreach (var pwi in product.ProductWarehouseInventory)
            {
                var pwiCopy = new ProductWarehouseInventory
                {
                    ProductId        = productCopy.Id,
                    WarehouseId      = pwi.WarehouseId,
                    StockQuantity    = pwi.StockQuantity,
                    ReservedQuantity = 0,
                };

                productCopy.ProductWarehouseInventory.Add(pwiCopy);
            }
            _productService.UpdateProduct(productCopy);

            // product <-> categories mappings
            foreach (var productCategory in product.ProductCategories)
            {
                var productCategoryCopy = new ProductCategory
                {
                    ProductId         = productCopy.Id,
                    CategoryId        = productCategory.CategoryId,
                    IsFeaturedProduct = productCategory.IsFeaturedProduct,
                    DisplayOrder      = productCategory.DisplayOrder
                };

                _categoryService.InsertProductCategory(productCategoryCopy);
            }

            // product <-> manufacturers mappings
            foreach (var productManufacturers in product.ProductManufacturers)
            {
                var productManufacturerCopy = new ProductManufacturer
                {
                    ProductId         = productCopy.Id,
                    ManufacturerId    = productManufacturers.ManufacturerId,
                    IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
                    DisplayOrder      = productManufacturers.DisplayOrder
                };

                _manufacturerService.InsertProductManufacturer(productManufacturerCopy);
            }

            // product <-> releated products mappings
            foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true))
            {
                _productService.InsertRelatedProduct(
                    new RelatedProduct
                {
                    ProductId1   = productCopy.Id,
                    ProductId2   = relatedProduct.ProductId2,
                    DisplayOrder = relatedProduct.DisplayOrder
                });
            }

            // product <-> cross sells mappings
            foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
            {
                _productService.InsertCrossSellProduct(
                    new CrossSellProduct
                {
                    ProductId1 = productCopy.Id,
                    ProductId2 = csProduct.ProductId2,
                });
            }

            // product specifications
            foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
            {
                var psaCopy = new ProductSpecificationAttribute
                {
                    ProductId       = productCopy.Id,
                    AttributeTypeId = productSpecificationAttribute.AttributeTypeId,
                    SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                    CustomValue       = productSpecificationAttribute.CustomValue,
                    AllowFiltering    = productSpecificationAttribute.AllowFiltering,
                    ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                    DisplayOrder      = productSpecificationAttribute.DisplayOrder
                };
                _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
            }

            //store mapping
            var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);

            foreach (var id in selectedStoreIds)
            {
                _storeMappingService.InsertStoreMapping(productCopy, id);
            }


            // product <-> attributes mappings
            var associatedAttributes      = new Dictionary <int, int>();
            var associatedAttributeValues = new Dictionary <int, int>();

            foreach (var productAttributeMapping in _productAttributeService.GetProductAttributeMappingsByProductId(product.Id))
            {
                var productAttributeMappingCopy = new ProductAttributeMapping
                {
                    ProductId                       = productCopy.Id,
                    ProductAttributeId              = productAttributeMapping.ProductAttributeId,
                    TextPrompt                      = productAttributeMapping.TextPrompt,
                    IsRequired                      = productAttributeMapping.IsRequired,
                    AttributeControlTypeId          = productAttributeMapping.AttributeControlTypeId,
                    DisplayOrder                    = productAttributeMapping.DisplayOrder,
                    ValidationMinLength             = productAttributeMapping.ValidationMinLength,
                    ValidationMaxLength             = productAttributeMapping.ValidationMaxLength,
                    ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions,
                    ValidationFileMaximumSize       = productAttributeMapping.ValidationFileMaximumSize,
                    DefaultValue                    = productAttributeMapping.DefaultValue,
                    //UNDONE copy ConditionAttributeXml (we should replace attribute IDs with new values)
                };
                _productAttributeService.InsertProductAttributeMapping(productAttributeMappingCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productAttributeMapping.Id, productAttributeMappingCopy.Id);

                // product attribute values
                var productAttributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id);
                foreach (var productAttributeValue in productAttributeValues)
                {
                    int attributeValuePictureId = 0;
                    if (originalNewPictureIdentifiers.ContainsKey(productAttributeValue.PictureId))
                    {
                        attributeValuePictureId = originalNewPictureIdentifiers[productAttributeValue.PictureId];
                    }
                    var attributeValueCopy = new ProductAttributeValue
                    {
                        ProductAttributeMappingId = productAttributeMappingCopy.Id,
                        AttributeValueTypeId      = productAttributeValue.AttributeValueTypeId,
                        AssociatedProductId       = productAttributeValue.AssociatedProductId,
                        Name             = productAttributeValue.Name,
                        ColorSquaresRgb  = productAttributeValue.ColorSquaresRgb,
                        PriceAdjustment  = productAttributeValue.PriceAdjustment,
                        WeightAdjustment = productAttributeValue.WeightAdjustment,
                        Cost             = productAttributeValue.Cost,
                        Quantity         = productAttributeValue.Quantity,
                        IsPreSelected    = productAttributeValue.IsPreSelected,
                        DisplayOrder     = productAttributeValue.DisplayOrder,
                        PictureId        = attributeValuePictureId,
                    };
                    _productAttributeService.InsertProductAttributeValue(attributeValueCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productAttributeValue.Id, attributeValueCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(attributeValueCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }
            //attribute combinations
            foreach (var combination in _productAttributeService.GetAllProductAttributeCombinations(product.Id))
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml        = "";
                var    parsedProductAttributes = _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml);
                foreach (var oldAttribute in parsedProductAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldAttribute.Id))
                    {
                        var newAttribute = _productAttributeService.GetProductAttributeMappingById(associatedAttributes[oldAttribute.Id]);
                        if (newAttribute != null)
                        {
                            var oldAttributeValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldAttribute.Id);
                            foreach (var oldAttributeValueStr in oldAttributeValuesStr)
                            {
                                if (newAttribute.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldAttributeValue = int.Parse(oldAttributeValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldAttributeValue))
                                    {
                                        var newAttributeValue = _productAttributeService.GetProductAttributeValueById(associatedAttributeValues[oldAttributeValue]);
                                        if (newAttributeValue != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                           newAttribute, newAttributeValue.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                   newAttribute, oldAttributeValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductAttributeCombination
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,
                    Sku = combination.Sku,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Gtin                        = combination.Gtin,
                    OverriddenPrice             = combination.OverriddenPrice,
                    NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow
                };
                _productAttributeService.InsertProductAttributeCombination(combinationCopy);
            }

            //tier prices
            foreach (var tierPrice in product.TierPrices)
            {
                _productService.InsertTierPrice(
                    new TierPrice
                {
                    ProductId      = productCopy.Id,
                    StoreId        = tierPrice.StoreId,
                    CustomerRoleId = tierPrice.CustomerRoleId,
                    Quantity       = tierPrice.Quantity,
                    Price          = tierPrice.Price
                });
            }

            // product <-> discounts mapping
            foreach (var discount in product.AppliedDiscounts)
            {
                productCopy.AppliedDiscounts.Add(discount);
                _productService.UpdateProduct(productCopy);
            }


            //update "HasTierPrices" and "HasDiscountsApplied" properties
            _productService.UpdateHasTierPricesProperty(productCopy);
            _productService.UpdateHasDiscountsApplied(productCopy);


            //associated products
            if (copyAssociatedProducts)
            {
                var associatedProducts = _productService.GetAssociatedProducts(product.Id, showHidden: true);
                foreach (var associatedProduct in associatedProducts)
                {
                    var associatedProductCopy = CopyProduct(associatedProduct, string.Format("Copy of {0}", associatedProduct.Name),
                                                            isPublished, copyImages, false);
                    associatedProductCopy.ParentGroupedProductId = productCopy.Id;
                    _productService.UpdateProduct(productCopy);
                }
            }

            return(productCopy);
        }
Exemplo n.º 34
0
        public static Task <AssetModel> GetAsset(BundleConfig.BundleTypes type, string assetGuid, string name = null,
                                                 IProgress <Tuple <string, float> > progressCallback          = null)
        {
            Assert.IsNotNull(assetGuid, $"{nameof(assetGuid)} must not be null when trying to get ${BundleConfig.singularOf(type)} asset.");

            Init();
            var assetService = new AssetService();
            var found        = assetService.Get(assetGuid);

            if (found != null)
            {
                if (File.Exists(found.LocalPath))
                {
                    return(Task.FromResult(found));
                }
                else
                {
                    Debug.Log($"removing stale entry from assetService due to missing file: {found.LocalPath}");
                    assetService.Delete(assetGuid);
                }
            }

            var typeString = BundleConfig.singularOf(type);

            if (name == null)
            {
                name = typeString;
            }

            string localPath = WebUtilities.GenerateLocalPath(assetGuid, type);

            Uri uri = new Uri(Config.CloudUrl + "/api/v1/assets/download/bundle/" + assetGuid);

            var progressState = new Tuple <string, float>(name, 0.0f);

            progressCallback?.Report(new Tuple <string, float>(name, 0.0f));
            Debug.Log($"{name} Download at 0%");
            var t        = new TaskCompletionSource <AssetModel>();
            var download = new Download(uri, localPath, name);

            download.OnUpdated += (IProgressTask t) =>
            {
                progressCallback?.Report(new Tuple <string, float>(name, t.Progress * 100));
                Debug.Log($"{name} Download at {t.Progress * 100}%");
            };

            download.OnCompleted += (IProgressTask pt, bool success, Exception ex) =>
            {
                if (success)
                {
                    try
                    {
                        var model = new AssetModel()
                        {
                            AssetGuid = assetGuid,
                            Type      = typeString,
                            Name      = name,
                            LocalPath = localPath,
                            DateAdded = DateTime.UtcNow.ToString()
                        };
                        assetService.Add(model);
                        Debug.Log($"{name} Download Complete.");
                        progressCallback?.Report(new Tuple <string, float>(name, 100));
                        t.TrySetResult(model);
                    }
                    catch (Exception e)
                    {
                        t.TrySetException(e);
                    }
                }
                else if (ex != null)
                {
                    t.TrySetException(ex);
                }
            };

            downloads.Enqueue(download);
            TaskProgressManager.Instance.AddTask(download);
            return(t.Task);
        }
Exemplo n.º 35
0
        /// <summary>
        /// Try BundlePath first, then arm manifest, then cygwin on server
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private async Task <string> CheckandGetSITLImage(string filename)
        {
            if (BundledPath != "")
            {
                filename = filename.Replace(".elf", "");
                var file = filename;
                if (!File.Exists(BundledPath + System.IO.Path.DirectorySeparatorChar + file))
                {
                    string[] checks = new string[] { "{0}", "{0}.exe", "lib{0}.so", "{0}.so", "{0}.elf" };

                    foreach (var template in checks)
                    {
                        file = String.Format(template, filename);
                        if (File.Exists(BundledPath + System.IO.Path.DirectorySeparatorChar + file))
                        {
                            return(BundledPath + System.IO.Path.DirectorySeparatorChar + file);
                        }
                        file = file.ToLower();
                        if (File.Exists(BundledPath + System.IO.Path.DirectorySeparatorChar + file))
                        {
                            return(BundledPath + System.IO.Path.DirectorySeparatorChar + file);
                        }
                    }
                }

                return("");
            }

            if ((RuntimeInformation.OSArchitecture == Architecture.X64 ||
                 RuntimeInformation.OSArchitecture == Architecture.X86) && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var type = APFirmware.MAV_TYPE.Copter;
                if (filename.ToLower().Contains("copter"))
                {
                    type = APFirmware.MAV_TYPE.Copter;
                }
                if (filename.ToLower().Contains("plane"))
                {
                    type = APFirmware.MAV_TYPE.FIXED_WING;
                }
                if (filename.ToLower().Contains("rover"))
                {
                    type = APFirmware.MAV_TYPE.GROUND_ROVER;
                }
                if (filename.ToLower().Contains("heli"))
                {
                    type = APFirmware.MAV_TYPE.HELICOPTER;
                }

                var fw = APFirmware.GetOptions(new DeviceInfo()
                {
                    board = "", hardwareid = ""
                }, APFirmware.RELEASE_TYPES.OFFICIAL, type);
                fw = fw.Where(a => a.Platform == "SITL_x86_64_linux_gnu").ToList();
                if (fw.Count > 0)
                {
                    var path = sitldirectory + Path.GetFileNameWithoutExtension(filename);
                    if (!chk_skipdownload.Checked)
                    {
                        Download.getFilefromNet(fw.First().Url.AbsoluteUri, path);
                        try
                        {
                            int _0755 = S_IRUSR | S_IXUSR | S_IWUSR
                                        | S_IRGRP | S_IXGRP
                                        | S_IROTH | S_IXOTH;

                            chmod(path, _0755);
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex);
                        }
                    }
                    return(path);
                }
            }

            if (RuntimeInformation.OSArchitecture == Architecture.Arm ||
                RuntimeInformation.OSArchitecture == Architecture.Arm64)
            {
                var type = APFirmware.MAV_TYPE.Copter;
                if (filename.ToLower().Contains("copter"))
                {
                    type = APFirmware.MAV_TYPE.Copter;
                }
                if (filename.ToLower().Contains("plane"))
                {
                    type = APFirmware.MAV_TYPE.FIXED_WING;
                }
                if (filename.ToLower().Contains("rover"))
                {
                    type = APFirmware.MAV_TYPE.GROUND_ROVER;
                }
                if (filename.ToLower().Contains("heli"))
                {
                    type = APFirmware.MAV_TYPE.HELICOPTER;
                }

                var fw = APFirmware.GetOptions(new DeviceInfo()
                {
                    board = "", hardwareid = ""
                }, APFirmware.RELEASE_TYPES.OFFICIAL, type);
                fw = fw.Where(a => a.Platform == "SITL_arm_linux_gnueabihf").ToList();
                if (fw.Count > 0)
                {
                    var path = sitldirectory + Path.GetFileNameWithoutExtension(filename);
                    if (!chk_skipdownload.Checked)
                    {
                        Download.getFilefromNet(fw.First().Url.AbsoluteUri, path);
                        try {
                            int _0755 = S_IRUSR | S_IXUSR | S_IWUSR
                                        | S_IRGRP | S_IXGRP
                                        | S_IROTH | S_IXOTH;

                            chmod(path, _0755);
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex);
                        }
                    }
                    return(path);
                }
            }

            if (!chk_skipdownload.Checked)
            {
                var url    = sitlmasterurl;
                var result = CustomMessageBox.Show("Select the version you want to use?", "Select your version", CustomMessageBox.MessageBoxButtons.YesNo, CustomMessageBox.MessageBoxIcon.Question, "Latest(Dev)", "Stable");

                if (result == CustomMessageBox.DialogResult.Yes)
                {
                    // master by default
                }
                else if (result == CustomMessageBox.DialogResult.No)
                {
                    if (filename.ToLower().Contains("copter"))
                    {
                        url = sitlcopterstableurl;
                    }
                    if (filename.ToLower().Contains("rover"))
                    {
                        url = sitlroverstableurl;
                    }
                    if (filename.ToLower().Contains("plane"))
                    {
                        url = sitlplanestableurl;
                    }
                }

                Uri fullurl = new Uri(url, filename);

                var load = Common.LoadingBox("Downloading", "Downloading sitl software");

                var t1 = Download.getFilefromNetAsync(fullurl.ToString(),
                                                      sitldirectory + Path.GetFileNameWithoutExtension(filename) + ".exe");

                load.Refresh();

                var files = new string[] { "cygatomic-1.dll",
                                           "cyggcc_s-1.dll",
                                           "cyggomp-1.dll",
                                           "cygquadmath-0.dll",
                                           "cygssp-0.dll",
                                           "cygstdc++-6.dll",
                                           "cygwin1.dll" };

                // dependancys

                Parallel.ForEach(files, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 2
                }, (a, b) =>
                {
                    var depurl = new Uri(url, a);
                    var t2     = Download.getFilefromNet(depurl.ToString(), sitldirectory + depurl.Segments[depurl.Segments.Length - 1]);
                });

                load.Close();
            }

            return(sitldirectory + Path.GetFileNameWithoutExtension(filename) + ".exe");
        }
Exemplo n.º 36
0
 public static DisconnectedStrategy <T> Register <T>(Download download, Upload upload) where T : Entity
 {
     return(Register(new DisconnectedStrategy <T>(download, null, upload, null, new BasicImporter <T>())));
 }
Exemplo n.º 37
0
 private void btnAdd_Click(object sender, EventArgs e)
 {
     Download = CreateDownload();
     RememberState();
     DialogResult = DialogResult.OK;
 }
Exemplo n.º 38
0
 public static DisconnectedStrategy <T> Register <T>(Download download, Expression <Func <T, bool> > uploadSubset) where T : Entity
 {
     return(Register(new DisconnectedStrategy <T>(download, null, Upload.Subset, uploadSubset, new UpdateImporter <T>())));
 }
Exemplo n.º 39
0
        public void RejectBasicAuth_Without_Password()
        {
            var d = new Download(From, To, auth: Download.AuthType.Basic, username: "******", password: null);

            this.AssertInitializationFails(d, "Basic Auth is enabled, but password is not specified");
        }
Exemplo n.º 40
0
        /// <summary>
        /// Try BundlePath first, then arm manifest, then cygwin on server
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private async Task <string> CheckandGetSITLImage(string filename)
        {
            if (BundledPath != "")
            {
                filename = filename.Replace(".elf", "");
                var file = filename;
                if (!File.Exists(BundledPath + System.IO.Path.DirectorySeparatorChar + file))
                {
                    string[] checks = new string[] { "{0}", "{0}.exe", "lib{0}.so", "{0}.so", "{0}.elf" };

                    foreach (var template in checks)
                    {
                        file = String.Format(template, filename);
                        if (File.Exists(BundledPath + System.IO.Path.DirectorySeparatorChar + file))
                        {
                            return(BundledPath + System.IO.Path.DirectorySeparatorChar + file);
                        }
                        file = file.ToLower();
                        if (File.Exists(BundledPath + System.IO.Path.DirectorySeparatorChar + file))
                        {
                            return(BundledPath + System.IO.Path.DirectorySeparatorChar + file);
                        }
                    }
                }

                return("");
            }

            if (RuntimeInformation.OSArchitecture == Architecture.Arm ||
                RuntimeInformation.OSArchitecture == Architecture.Arm64)
            {
                var type = APFirmware.MAV_TYPE.Copter;
                if (filename.ToLower().Contains("copter"))
                {
                    type = APFirmware.MAV_TYPE.Copter;
                }
                if (filename.ToLower().Contains("plane"))
                {
                    type = APFirmware.MAV_TYPE.FIXED_WING;
                }
                if (filename.ToLower().Contains("rover"))
                {
                    type = APFirmware.MAV_TYPE.GROUND_ROVER;
                }
                if (filename.ToLower().Contains("heli"))
                {
                    type = APFirmware.MAV_TYPE.HELICOPTER;
                }

                var fw = APFirmware.GetOptions(new DeviceInfo()
                {
                    board = "", hardwareid = ""
                }, APFirmware.RELEASE_TYPES.OFFICIAL, type);
                fw = fw.Where(a => a.Platform == "SITL_arm_linux_gnueabihf").ToList();
                if (fw.Count > 0)
                {
                    if (!chk_skipdownload.Checked)
                    {
                        Download.getFilefromNetAsync(fw.First().Url.AbsoluteUri, sitldirectory + Path.GetFileNameWithoutExtension(filename));
                    }
                    return(sitldirectory + Path.GetFileNameWithoutExtension(filename));
                }
            }

            if (!chk_skipdownload.Checked)
            {
                Uri fullurl = new Uri(sitlurl, filename);

                var load = Common.LoadingBox("Downloading", "Downloading sitl software");

                var t1 = Download.getFilefromNetAsync(fullurl.ToString(),
                                                      sitldirectory + Path.GetFileNameWithoutExtension(filename) + ".exe");

                load.Refresh();

                var files = new string[] { "cygatomic-1.dll",
                                           "cyggcc_s-1.dll",
                                           "cyggomp-1.dll",
                                           "cygquadmath-0.dll",
                                           "cygssp-0.dll",
                                           "cygstdc++-6.dll",
                                           "cygwin1.dll" };

                // dependancys

                Parallel.ForEach(files, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 2
                }, (a, b) =>
                {
                    var depurl = new Uri(sitlurl, a);
                    var t2     = Download.getFilefromNet(depurl.ToString(), sitldirectory + depurl.Segments[depurl.Segments.Length - 1]);
                });

                load.Close();
            }

            return(sitldirectory + Path.GetFileNameWithoutExtension(filename) + ".exe");
        }
Exemplo n.º 41
0
        private void but_getfw_Click(object sender, EventArgs e)
        {
            var basedir = Settings.GetDataDirectory() + "History";

            Directory.CreateDirectory(basedir);

            var fw = new Firmware();

            var list = fw.getFWList();

            using (
                var xmlwriter = new XmlTextWriter(basedir + Path.DirectorySeparatorChar + @"firmware2.xml",
                                                  Encoding.ASCII))
            {
                xmlwriter.Formatting = Formatting.Indented;

                xmlwriter.WriteStartDocument();

                xmlwriter.WriteStartElement("options");

                int a = 0;

                foreach (var software in list)
                {
                    a++;
                    Loading.ShowLoading(((a - 1) / (float)list.Count) * 100.0 + "% " + software.name, this);

                    //if (!software.name.Contains("Copter"))
                    //  continue;

                    xmlwriter.WriteStartElement("Firmware");

                    if (software.url != "")
                    {
                        xmlwriter.WriteElementString("url", new Uri(software.url).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.url2560 != "")
                    {
                        xmlwriter.WriteElementString("url2560", new Uri(software.url2560).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.url2560_2 != "")
                    {
                        xmlwriter.WriteElementString("url2560-2",
                                                     new Uri(software.url2560_2).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlpx4v1 != "")
                    {
                        xmlwriter.WriteElementString("urlpx4", new Uri(software.urlpx4v1).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlpx4v2 != "")
                    {
                        xmlwriter.WriteElementString("urlpx4v2",
                                                     new Uri(software.urlpx4v2).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlpx4v4 != "")
                    {
                        xmlwriter.WriteElementString("urlpx4v4",
                                                     new Uri(software.urlpx4v4).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlpx4v4pro != "")
                    {
                        xmlwriter.WriteElementString("urlpx4v4pro",
                                                     new Uri(software.urlpx4v4pro).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv40 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv40",
                                                     new Uri(software.urlvrbrainv40).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv45 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv45",
                                                     new Uri(software.urlvrbrainv45).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv50 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv50",
                                                     new Uri(software.urlvrbrainv50).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv51 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv51",
                                                     new Uri(software.urlvrbrainv51).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv52 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv52",
                                                     new Uri(software.urlvrbrainv52).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrbrainv54 != "")
                    {
                        xmlwriter.WriteElementString("urlvrbrainv54",
                                                     new Uri(software.urlvrbrainv54).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrcorev10 != "")
                    {
                        xmlwriter.WriteElementString("urlvrcorev10",
                                                     new Uri(software.urlvrcorev10).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrubrainv51 != "")
                    {
                        xmlwriter.WriteElementString("urlvrubrainv51",
                                                     new Uri(software.urlvrubrainv51).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlvrubrainv52 != "")
                    {
                        xmlwriter.WriteElementString("urlvrubrainv52",
                                                     new Uri(software.urlvrubrainv52).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urlbebop2 != "")
                    {
                        xmlwriter.WriteElementString("urlbebop2",
                                                     new Uri(software.urlbebop2).LocalPath.TrimStart('/', '\\'));
                    }
                    if (software.urldisco != "")
                    {
                        xmlwriter.WriteElementString("urldisco",
                                                     new Uri(software.urldisco).LocalPath.TrimStart('/', '\\'));
                    }
                    xmlwriter.WriteElementString("name", software.name);
                    xmlwriter.WriteElementString("desc", software.desc);
                    xmlwriter.WriteElementString("format_version", software.k_format_version.ToString());

                    xmlwriter.WriteEndElement();

                    if (software.url != "")
                    {
                        Download.getFilefromNet(software.url, basedir + new Uri(software.url).LocalPath);
                    }
                    if (software.url2560 != "")
                    {
                        Download.getFilefromNet(software.url2560, basedir + new Uri(software.url2560).LocalPath);
                    }
                    if (software.url2560_2 != "")
                    {
                        Download.getFilefromNet(software.url2560_2, basedir + new Uri(software.url2560_2).LocalPath);
                    }
                    if (software.urlpx4v1 != "")
                    {
                        Download.getFilefromNet(software.urlpx4v1, basedir + new Uri(software.urlpx4v1).LocalPath);
                    }
                    if (software.urlpx4v2 != "")
                    {
                        Download.getFilefromNet(software.urlpx4v2, basedir + new Uri(software.urlpx4v2).LocalPath);
                    }
                    if (software.urlpx4v4 != "")
                    {
                        Download.getFilefromNet(software.urlpx4v4, basedir + new Uri(software.urlpx4v4).LocalPath);
                    }
                    if (software.urlpx4v4pro != "")
                    {
                        Download.getFilefromNet(software.urlpx4v4pro, basedir + new Uri(software.urlpx4v4pro).LocalPath);
                    }

                    if (software.urlvrbrainv40 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv40,
                                                basedir + new Uri(software.urlvrbrainv40).LocalPath);
                    }
                    if (software.urlvrbrainv45 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv45,
                                                basedir + new Uri(software.urlvrbrainv45).LocalPath);
                    }
                    if (software.urlvrbrainv50 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv50,
                                                basedir + new Uri(software.urlvrbrainv50).LocalPath);
                    }
                    if (software.urlvrbrainv51 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv51,
                                                basedir + new Uri(software.urlvrbrainv51).LocalPath);
                    }
                    if (software.urlvrbrainv52 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv52,
                                                basedir + new Uri(software.urlvrbrainv52).LocalPath);
                    }
                    if (software.urlvrbrainv54 != "")
                    {
                        Download.getFilefromNet(software.urlvrbrainv54,
                                                basedir + new Uri(software.urlvrbrainv54).LocalPath);
                    }
                    if (software.urlvrcorev10 != "")
                    {
                        Download.getFilefromNet(software.urlvrcorev10, basedir + new Uri(software.urlvrcorev10).LocalPath);
                    }
                    if (software.urlvrubrainv51 != "")
                    {
                        Download.getFilefromNet(software.urlvrubrainv51,
                                                basedir + new Uri(software.urlvrubrainv51).LocalPath);
                    }
                    if (software.urlvrubrainv52 != "")
                    {
                        Download.getFilefromNet(software.urlvrubrainv52,
                                                basedir + new Uri(software.urlvrubrainv52).LocalPath);
                    }
                    if (software.urlbebop2 != "")
                    {
                        Download.getFilefromNet(software.urlbebop2,
                                                basedir + new Uri(software.urlbebop2).LocalPath);
                    }
                    if (software.urldisco != "")
                    {
                        Download.getFilefromNet(software.urldisco,
                                                basedir + new Uri(software.urldisco).LocalPath);
                    }
                }

                xmlwriter.WriteEndElement();
                xmlwriter.WriteEndDocument();
            }

            Loading.Close();
        }
		private static Download BuildDownload()
		{
			var price = new PackagePrice
			{
				CurrencyCode = "GBP",
				RecommendedRetailPrice = 10.00m,
				SevendigitalPrice = 9.75m
			};

			var download = new Download
			{
				Packages = new List<Package>
				{
					new Package
					{
						Id = 2,
						Price = price
					}
				}
			};
			return download;
		}
Exemplo n.º 43
0
        /// <param name="download_url">Url of file to download</param>
        /// <param name="download_dest">Directory where to save the file</param>
        /// <param name="checksumField">Checksum instance of file or null</param>
        /// <returns>
        /// An <see cref="Capuchin.Downloaders.AbstractDownloader" /> instance to
        /// download the given file
        /// </returns>
        internal int DownloadFile(string download_url, string download_dest,
                                   string signature, checksum checksumField)
        {
            Download dl = new Download(this.downloadsIndex, download_url, download_dest, signature, checksumField);

            Downloaders.AbstractDownloader downloader = this.GetDownloader(this.downloadsIndex, dl);
            downloader.Status += new Downloaders.StatusHandler( this.OnDownloadStatus );
            downloader.Finished += new Downloaders.FinishedHandler( this.DownloadFinishedCallback );

            Thread downloaderThread = new Thread( new ThreadStart(downloader.Download) );
            dl.Downloader = downloaderThread;
            lock (this) {
                this.Downloads.Add( this.downloadsIndex, dl );
                this.downloadsIndex++;
                downloaderThread.Start();
            }

            Log.Info("Started downloading file {0} to {1} with id '{2}'",
                     download_url, download_dest, this.downloadsIndex-1);

            return (this.downloadsIndex-1);
        }
Exemplo n.º 44
0
        /// <summary>
        /// Create a copy of product variant with all depended data
        /// </summary>
        /// <param name="productVariant">The product variant to copy</param>
        /// <param name="productId">The product identifier</param>
        /// <param name="newName">The name of product variant duplicate</param>
        /// <param name="isPublished">A value indicating whether the product variant duplicate should be published</param>
        /// <param name="copyImage">A value indicating whether the product variant image should be copied</param>
        /// <returns>Product variant copy</returns>
        public virtual ProductVariant CopyProductVariant(ProductVariant productVariant, int productId,
                                                         string newName, bool isPublished, bool copyImage)
        {
            if (productVariant == null)
            {
                throw new ArgumentNullException("productVariant");
            }

            var languages = _languageService.GetAllLanguages(true);

            // product variant picture
            int pictureId = 0;

            if (copyImage)
            {
                var picture = _pictureService.GetPictureById(productVariant.PictureId);
                if (picture != null)
                {
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(productVariant.Name),
                        true);
                    pictureId = pictureCopy.Id;
                }
            }

            // product variant download & sample download
            int downloadId       = productVariant.DownloadId;
            int sampleDownloadId = productVariant.SampleDownloadId;

            if (productVariant.IsDownload)
            {
                var download = _downloadService.GetDownloadById(productVariant.DownloadId);
                if (download != null)
                {
                    var downloadCopy = new Download()
                    {
                        DownloadGuid   = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl    = download.DownloadUrl,
                        DownloadBinary = download.DownloadBinary,
                        ContentType    = download.ContentType,
                        Filename       = download.Filename,
                        Extension      = download.Extension,
                        IsNew          = download.IsNew,
                    };
                    _downloadService.InsertDownload(downloadCopy);
                    downloadId = downloadCopy.Id;
                }

                if (productVariant.HasSampleDownload)
                {
                    var sampleDownload = _downloadService.GetDownloadById(productVariant.SampleDownloadId);
                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download()
                        {
                            DownloadGuid   = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl    = sampleDownload.DownloadUrl,
                            DownloadBinary = sampleDownload.DownloadBinary,
                            ContentType    = sampleDownload.ContentType,
                            Filename       = sampleDownload.Filename,
                            Extension      = sampleDownload.Extension,
                            IsNew          = sampleDownload.IsNew
                        };
                        _downloadService.InsertDownload(sampleDownloadCopy);
                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            // product variant
            var productVariantCopy = new ProductVariant()
            {
                ProductId                 = productId,
                Name                      = newName,
                Sku                       = productVariant.Sku,
                Description               = productVariant.Description,
                AdminComment              = productVariant.AdminComment,
                ManufacturerPartNumber    = productVariant.ManufacturerPartNumber,
                Gtin                      = productVariant.Gtin,
                IsGiftCard                = productVariant.IsGiftCard,
                GiftCardType              = productVariant.GiftCardType,
                RequireOtherProducts      = productVariant.RequireOtherProducts,
                RequiredProductVariantIds = productVariant.RequiredProductVariantIds,
                AutomaticallyAddRequiredProductVariants = productVariant.AutomaticallyAddRequiredProductVariants,
                IsDownload                    = productVariant.IsDownload,
                DownloadId                    = downloadId,
                UnlimitedDownloads            = productVariant.UnlimitedDownloads,
                MaxNumberOfDownloads          = productVariant.MaxNumberOfDownloads,
                DownloadExpirationDays        = productVariant.DownloadExpirationDays,
                DownloadActivationType        = productVariant.DownloadActivationType,
                HasSampleDownload             = productVariant.HasSampleDownload,
                SampleDownloadId              = sampleDownloadId,
                HasUserAgreement              = productVariant.HasUserAgreement,
                UserAgreementText             = productVariant.UserAgreementText,
                IsRecurring                   = productVariant.IsRecurring,
                RecurringCycleLength          = productVariant.RecurringCycleLength,
                RecurringCyclePeriod          = productVariant.RecurringCyclePeriod,
                RecurringTotalCycles          = productVariant.RecurringTotalCycles,
                IsShipEnabled                 = productVariant.IsShipEnabled,
                IsFreeShipping                = productVariant.IsFreeShipping,
                AdditionalShippingCharge      = productVariant.AdditionalShippingCharge,
                IsTaxExempt                   = productVariant.IsTaxExempt,
                TaxCategoryId                 = productVariant.TaxCategoryId,
                ManageInventoryMethod         = productVariant.ManageInventoryMethod,
                StockQuantity                 = productVariant.StockQuantity,
                DisplayStockAvailability      = productVariant.DisplayStockAvailability,
                DisplayStockQuantity          = productVariant.DisplayStockQuantity,
                MinStockQuantity              = productVariant.MinStockQuantity,
                LowStockActivityId            = productVariant.LowStockActivityId,
                NotifyAdminForQuantityBelow   = productVariant.NotifyAdminForQuantityBelow,
                BackorderMode                 = productVariant.BackorderMode,
                AllowBackInStockSubscriptions = productVariant.AllowBackInStockSubscriptions,
                OrderMinimumQuantity          = productVariant.OrderMinimumQuantity,
                OrderMaximumQuantity          = productVariant.OrderMaximumQuantity,
                AllowedQuantities             = productVariant.AllowedQuantities,
                DisableBuyButton              = productVariant.DisableBuyButton,
                DisableWishlistButton         = productVariant.DisableWishlistButton,
                CallForPrice                  = productVariant.CallForPrice,
                Price        = productVariant.Price,
                OldPrice     = productVariant.OldPrice,
                ProductCost  = productVariant.ProductCost,
                SpecialPrice = productVariant.SpecialPrice,
                SpecialPriceStartDateTimeUtc = productVariant.SpecialPriceStartDateTimeUtc,
                SpecialPriceEndDateTimeUtc   = productVariant.SpecialPriceEndDateTimeUtc,
                CustomerEntersPrice          = productVariant.CustomerEntersPrice,
                MinimumCustomerEnteredPrice  = productVariant.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice  = productVariant.MaximumCustomerEnteredPrice,
                Weight    = productVariant.Weight,
                Length    = productVariant.Length,
                Width     = productVariant.Width,
                Height    = productVariant.Height,
                PictureId = pictureId,
                AvailableStartDateTimeUtc = productVariant.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc   = productVariant.AvailableEndDateTimeUtc,
                Published    = isPublished,
                Deleted      = productVariant.Deleted,
                DisplayOrder = productVariant.DisplayOrder,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow
            };

            _productService.InsertProductVariant(productVariantCopy);

            //localization
            foreach (var lang in languages)
            {
                var name = productVariant.GetLocalized(x => x.Name, lang.Id, false, false);
                if (!String.IsNullOrEmpty(name))
                {
                    _localizedEntityService.SaveLocalizedValue(productVariantCopy, x => x.Name, name, lang.Id);
                }

                var description = productVariant.GetLocalized(x => x.Description, lang.Id, false, false);
                if (!String.IsNullOrEmpty(description))
                {
                    _localizedEntityService.SaveLocalizedValue(productVariantCopy, x => x.Description, description, lang.Id);
                }
            }

            // product variant <-> attributes mappings
            var associatedAttributes      = new Dictionary <int, int>();
            var associatedAttributeValues = new Dictionary <int, int>();

            foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductVariantId(productVariant.Id))
            {
                var productVariantAttributeCopy = new ProductVariantAttribute()
                {
                    ProductVariantId       = productVariantCopy.Id,
                    ProductAttributeId     = productVariantAttribute.ProductAttributeId,
                    TextPrompt             = productVariantAttribute.TextPrompt,
                    IsRequired             = productVariantAttribute.IsRequired,
                    AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId,
                    DisplayOrder           = productVariantAttribute.DisplayOrder
                };
                _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id);

                // product variant attribute values
                var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id);
                foreach (var productVariantAttributeValue in productVariantAttributeValues)
                {
                    var pvavCopy = new ProductVariantAttributeValue()
                    {
                        ProductVariantAttributeId = productVariantAttributeCopy.Id,
                        Name             = productVariantAttributeValue.Name,
                        ColorSquaresRgb  = productVariantAttributeValue.ColorSquaresRgb,
                        PriceAdjustment  = productVariantAttributeValue.PriceAdjustment,
                        WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                        IsPreSelected    = productVariantAttributeValue.IsPreSelected,
                        DisplayOrder     = productVariantAttributeValue.DisplayOrder
                    };
                    _productAttributeService.InsertProductVariantAttributeValue(pvavCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productVariantAttributeValue.Id, pvavCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productVariantAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(pvavCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }
            foreach (var combination in _productAttributeService.GetAllProductVariantAttributeCombinations(productVariant.Id))
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml = "";
                var    parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml);
                foreach (var oldPva in parsedProductVariantAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldPva.Id))
                    {
                        int newPvaId = associatedAttributes[oldPva.Id];
                        var newPva   = _productAttributeService.GetProductVariantAttributeById(newPvaId);
                        if (newPva != null)
                        {
                            var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id);
                            foreach (var oldPvaValueStr in oldPvaValuesStr)
                            {
                                if (newPva.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldPvaValue = int.Parse(oldPvaValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldPvaValue))
                                    {
                                        int newPvavId = associatedAttributeValues[oldPvaValue];
                                        var newPvav   = _productAttributeService.GetProductVariantAttributeValueById(newPvavId);
                                        if (newPvav != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                           newPva, newPvav.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                   newPva, oldPvaValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductVariantAttributeCombination()
                {
                    ProductVariantId      = productVariantCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,
                    Sku = combination.Sku,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Gtin = combination.Gtin
                };
                _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy);
            }

            // product variant tier prices
            foreach (var tierPrice in productVariant.TierPrices)
            {
                _productService.InsertTierPrice(
                    new TierPrice()
                {
                    ProductVariantId = productVariantCopy.Id,
                    CustomerRoleId   = tierPrice.CustomerRoleId,
                    Quantity         = tierPrice.Quantity,
                    Price            = tierPrice.Price
                });
            }

            // product variant <-> discounts mapping
            foreach (var discount in productVariant.AppliedDiscounts)
            {
                productVariantCopy.AppliedDiscounts.Add(discount);
                _productService.UpdateProductVariant(productVariantCopy);
            }


            //update "HasTierPrices" and "HasDiscountsApplied" properties
            _productService.UpdateHasTierPricesProperty(productVariantCopy);
            _productService.UpdateHasDiscountsApplied(productVariantCopy);


            return(productVariantCopy);
        }
Exemplo n.º 45
0
        /// <summary>Returns the appropriate <see cref="Capuchin.Downloaders.AbstractDownloader" /></summary>
        internal Downloaders.AbstractDownloader GetDownloader(int id, Download dl)
        {
            Uri uri = new Uri(dl.Url);

            if (uri.Scheme == "http")
            {
                return new Downloaders.HttpDownloader(id, dl);
            //            } else if (uri.Scheme == "ftp") {
            //                return new Downloaders.FtpDownloader(id, dl);
            } else {
                throw new NotImplementedException("Scheme '"+ uri.Scheme + "' is not supported");
            }
        }
Exemplo n.º 46
0
        public virtual ActionResult UploadFileReturnRequest()
        {
            if (!_orderSettings.ReturnRequestsEnabled && !_orderSettings.ReturnRequestsAllowFiles)
            {
                return(Json(new
                {
                    success = false,
                    downloadGuid = Guid.Empty,
                }, MimeTypes.TextPlain));
            }

            //we process it distinct ways based on a browser
            //find more info here http://stackoverflow.com/questions/4884920/mvc3-valums-ajax-file-upload
            Stream stream      = null;
            var    fileName    = "";
            var    contentType = "";

            if (String.IsNullOrEmpty(Request["qqfile"]))
            {
                // IE
                HttpPostedFileBase httpPostedFile = Request.Files[0];
                if (httpPostedFile == null)
                {
                    throw new ArgumentException("No file uploaded");
                }
                stream      = httpPostedFile.InputStream;
                fileName    = Path.GetFileName(httpPostedFile.FileName);
                contentType = httpPostedFile.ContentType;
            }
            else
            {
                //Webkit, Mozilla
                stream   = Request.InputStream;
                fileName = Request["qqfile"];
            }

            var fileBinary = new byte[stream.Length];

            stream.Read(fileBinary, 0, fileBinary.Length);

            var fileExtension = Path.GetExtension(fileName);

            if (!String.IsNullOrEmpty(fileExtension))
            {
                fileExtension = fileExtension.ToLowerInvariant();
            }

            int validationFileMaximumSize = _orderSettings.ReturnRequestsFileMaximumSize;

            if (validationFileMaximumSize > 0)
            {
                //compare in bytes
                var maxFileSizeBytes = validationFileMaximumSize * 1024;
                if (fileBinary.Length > maxFileSizeBytes)
                {
                    //when returning JSON the mime-type must be set to text/plain
                    //otherwise some browsers will pop-up a "Save As" dialog.
                    return(Json(new
                    {
                        success = false,
                        message = string.Format(_localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), validationFileMaximumSize),
                        downloadGuid = Guid.Empty,
                    }, MimeTypes.TextPlain));
                }
            }

            var download = new Download
            {
                DownloadGuid   = Guid.NewGuid(),
                UseDownloadUrl = false,
                DownloadUrl    = "",
                DownloadBinary = fileBinary,
                ContentType    = contentType,
                //we store filename without extension for downloads
                Filename  = Path.GetFileNameWithoutExtension(fileName),
                Extension = fileExtension,
                IsNew     = true
            };

            _downloadService.InsertDownload(download);

            //when returning JSON the mime-type must be set to text/plain
            //otherwise some browsers will pop-up a "Save As" dialog.
            return(Json(new
            {
                success = true,
                message = _localizationService.GetResource("ShoppingCart.FileUploaded"),
                downloadUrl = Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }),
                downloadGuid = download.DownloadGuid,
            }, MimeTypes.TextPlain));
        }
Exemplo n.º 47
0
        private void CheckForUpdates(bool autoCheck)
        {
            ThreadStart ts = new ThreadStart(delegate()
            {
                string oldBtnText = null;
                if (btnCheckUpdate.InvokeRequired)
                {
                    btnCheckUpdate.Invoke(new MethodInvoker(delegate()
                    {
                        oldBtnText = btnCheckUpdate.Text;
                        btnCheckUpdate.Text = "Stop Checking";
                    }));
                }

                try
                {
                    String URLString = "http://dl.dropbox.com/u/176693/keymagic.xml";
                    //String URLString = "file://///psf/Home/Dropbox/Public/keymagic.xml";

                    WebRequest webReq = WebRequest.Create(URLString);
                    webReq.Proxy = WebRequest.GetSystemWebProxy();
                    webReq.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
                    webReq.Proxy.Credentials = CredentialCache.DefaultCredentials;

                    XmlTextReader reader = new XmlTextReader(webReq.GetResponse().GetResponseStream());

                    Dictionary<string, Download> Downloads = new Dictionary<string, Download>();
                    String CurrentKey = null;

                    if (reader.Read() && !reader.Name.Equals("KeyMagic"))
                    {
                        throw new Exception("Invalid XML");
                    }

                    while (reader.Read())
                    {
                        switch (reader.NodeType)
                        {
                            case XmlNodeType.Element: // The node is an element.
                                if (string.IsNullOrEmpty(CurrentKey))
                                {
                                    CurrentKey = reader.Name;
                                    reader.Read();
                                    Downloads[CurrentKey] = new Download();
                                    Downloads[CurrentKey].Version = reader.Value;
                                }
                                else if (reader.Name.Equals("DownloadURL"))
                                {
                                    reader.Read();
                                    Downloads[CurrentKey].DownloadURL = reader.Value;

                                    CurrentKey = null;
                                }
                                break;
                        }
                    }

                    string latestVersion;

                    const string latestBetaVersion = "LatestBetaVersion";
                    const string latestStableVersion = "LatestStableVersion";

                    if (Properties.Settings.Default.BetaRelease)
                    {
                        latestVersion = latestBetaVersion;
                    }
                    else
                    {
                        latestVersion = latestStableVersion;
                    }

                    if (Downloads.ContainsKey(latestVersion))
                    {
                        while (Downloads[latestVersion].Version.StartsWith("="))
                        {
                            latestVersion = Downloads[latestVersion].Version.Substring(1);
                            Debug.WriteLine("Redirect to " + latestVersion);
                        }
                        if (new Version(Downloads[latestVersion].Version) > new Version(AboutKeyMagic.AssemblyVersion))
                        {
                            if (MessageBox.Show(string.Format("There is new update ({0}) available. Do you want to open download page now?", Downloads[latestVersion].Version), "Update Available",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            {
                                Process.Start(Downloads[latestVersion].DownloadURL);
                            }
                        }
                        else if (new Version(Downloads[latestVersion].Version) < new Version(AboutKeyMagic.AssemblyVersion))
                        {
                            if (!autoCheck) MessageBox.Show("You have the future release version of KeyMagic which is not even released yet. Seems like you are using private release, do you?", "Ooh!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                        else
                        {
                            // Check if there is stable release for this beta
                            if (Properties.Settings.Default.BetaRelease && Downloads.ContainsKey(latestStableVersion))
                            {
                                if (new Version(Downloads[latestStableVersion].Version) == new Version(AboutKeyMagic.AssemblyVersion))
                                {
                                    if (MessageBox.Show(string.Format("There is stable release ({0}) available for this beta version. Do you want to open download page now?", Downloads[latestStableVersion].Version), "Update Available",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                                    {
                                        Process.Start(Downloads[latestStableVersion].DownloadURL);
                                    }
                                }
                                else
                                {
                                    if (!autoCheck) MessageBox.Show("You have the latest version of KeyMagic", "No Update Available", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                            else
                            {
                                if (!autoCheck) MessageBox.Show("You have the latest version of KeyMagic", "No Update Available", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                }
                catch (ThreadAbortException) {}
                catch (WebException) {}
                catch (Exception ex)
                {
                    if (!autoCheck) MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                if (btnCheckUpdate.InvokeRequired)
                {
                    btnCheckUpdate.Invoke(new MethodInvoker(delegate() { btnCheckUpdate.Text = oldBtnText; }));
                }

                Properties.Settings.Default.LastCheckUpdateDate = new DateTime();
            }
            );

            if (threads.ContainsKey("CheckForUpdate") == false)
            {
                threads["CheckForUpdate"] = null;
            }

            Thread updateThread = threads["CheckForUpdate"];

            if (updateThread != null)
            {
                if (updateThread.IsAlive)
                {
                    updateThread.Abort();
                }
                if (btnCheckUpdate.Text == "Stop Checking")
                {
                    btnCheckUpdate.Text = "Check For Updates";
                    return;
                }
            }

            updateThread = new Thread(ts);
            updateThread.Start();

            threads["CheckForUpdate"] = updateThread;
        }
Exemplo n.º 48
0
 private void DownloadAndSaveItem(System.IO.Stream stream, string name, long maxsize)
 {
     if(stream != null)
     {
         var dialog = new SaveFileDialog();
         dialog.FileName = name;          
         dialog.Filter = "All Files (*.*)|*.*";
         var result = dialog.ShowDialog();
         if (result != System.Windows.Forms.DialogResult.OK)
         {
             return;
         }
         down = new FileDownload(dialog.FileName, stream, maxsize);
         down.StreamCompleteCallback += webclient_DownloadFileCompleted;
         down.StreamProgressCallback += webclient_UploadProgressChanged;
         down.StreamControlCallBack += down_StreamControlCallBack;
         down.Start();
     }
 }
		public override bool OnDownloadStarted (Download downloadItem)
		{
			UnityEngine.Debug.Log("Downloads are disabled when using the default Unity3D SystemListener!");
			return false;
		}
Exemplo n.º 50
0
        static void handleException(Exception ex)
        {
            if (ex.Message == "Safe handle has been closed")
            {
                return;
            }

            if (MainV2.instance != null && MainV2.instance.IsDisposed)
            {
                return;
            }

            MissionPlanner.Utilities.Tracking.AddException(ex);

            log.Debug(ex.ToString());

            GetStackTrace(ex);

            // hyperlinks error
            if (ex.Message == "Requested registry access is not allowed." ||
                ex.ToString().Contains("System.Windows.Forms.LinkUtilities.GetIELinkBehavior"))
            {
                return;
            }

            if (ex.Message.Contains("The port is closed"))
            {
                CustomMessageBox.Show("Serial connection has been lost");
                return;
            }

            if (ex.Message.Contains("Array.Empty"))
            {
                CustomMessageBox.Show("Please install Microsoft Dot Net 4.6.2");
                Application.Exit();
                return;
            }

            if (ex.Message.Contains("A device attached to the system is not functioning"))
            {
                CustomMessageBox.Show("Serial connection has been lost");
                return;
            }

            if (ex.GetType() == typeof(MissingMethodException) || ex.GetType() == typeof(TypeLoadException))
            {
                CustomMessageBox.Show("Please Update - Some older library dlls are causing problems\n" + ex.Message);
                return;
            }

            if (ex.GetType() == typeof(ObjectDisposedException) || ex.GetType() == typeof(InvalidOperationException))
            // something is trying to update while the form, is closing.
            {
                log.Error(ex);
                return; // ignore
            }

            if (ex.GetType() == typeof(FileNotFoundException) || ex.GetType() == typeof(BadImageFormatException))
            // i get alot of error from people who click the exe from inside a zip file.
            {
                CustomMessageBox.Show(
                    "You are missing some DLL's. Please extract the zip file somewhere. OR Use the update feature from the menu " +
                    ex.ToString());
                // return;
            }

            // windows and mono
            if (ex.StackTrace != null && ex.StackTrace.Contains("System.IO.Ports.SerialStream.Dispose") ||
                ex.StackTrace != null && ex.StackTrace.Contains("System.IO.Ports.SerialPortStream.Dispose"))
            {
                log.Error(ex);
                return; // ignore
            }

            log.Info("Th Name " + Thread?.Name);

            var dr =
                CustomMessageBox.Show("An error has occurred\n" + ex.ToString() + "\n\nReport this Error???",
                                      "Send Error", MessageBoxButtons.YesNo);

            if ((int)DialogResult.Yes == dr)
            {
                try
                {
                    string data = "";
                    foreach (System.Collections.DictionaryEntry de in ex.Data)
                    {
                        data += String.Format("-> {0}: {1}", de.Key, de.Value);
                    }

                    string message = "";

                    try
                    {
                        Controls.InputBox.Show("Message", "Please enter a message about this error if you can.",
                                               ref message);
                    }
                    catch
                    {
                    }

                    string processinfo = "";

                    try
                    {
                        var result = new Dictionary <int, string[]>();

                        var pid = Process.GetCurrentProcess().Id;

                        using (var dataTarget = DataTarget.AttachToProcess(pid, 5000, AttachFlag.Passive))
                        {
                            ClrInfo runtimeInfo = dataTarget.ClrVersions[0];
                            var     runtime     = runtimeInfo.CreateRuntime();

                            foreach (var t in runtime.Threads)
                            {
                                result.Add(
                                    t.ManagedThreadId,
                                    t.StackTrace.Select(f =>
                                {
                                    if (f.Method != null)
                                    {
                                        return(f.Method.Type.Name + "." + f.Method.Name);
                                    }

                                    return(null);
                                }).ToArray()
                                    );
                            }
                        }

                        processinfo =
                            result.ToJSON(Formatting.Indented); //;Process.GetCurrentProcess().Modules.ToJSON();
                    }
                    catch
                    {
                    }

                    string postData = "message=" + Environment.OSVersion.VersionString + " " +
                                      System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
                                      + " " + Application.ProductVersion
                                      + "\nException " + ex.ToString().Replace('&', ' ').Replace('=', ' ')
                                      + "\nStack: " + ex.StackTrace.ToString().Replace('&', ' ').Replace('=', ' ')
                                      + "\nTargetSite " + ex.TargetSite + " " + ex.TargetSite.DeclaringType
                                      + "\ndata " + data
                                      + "\nmessage " + message.Replace('&', ' ').Replace('=', ' ')
                                      + "\n\n" + processinfo;
                    _ = Download.PostAsync("http://vps.oborne.me/mail.php", postData).ConfigureAwait(false);
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.ToString());
                    log.Error(exp);
                    CustomMessageBox.Show("Could not send report! Typically due to lack of internet connection.");
                }
            }
        }
 public CelotTelnet(Download download, string Hostname, int Port)
     : base(Hostname, Port)
 {
     this.download = download;
 }
Exemplo n.º 52
0
 /// <summary>
 /// Updates the download
 /// </summary>
 /// <param name="download">Download</param>
 public virtual void UpdateDownload(Download download)
 {
     _downloadRepository.Update(download);
 }
Exemplo n.º 53
0
        void RefreshServerList()
        {
            // Query in progress
            if (currentQuery != null)
                return;

            searchStatus = SearchStatus.Fetching;

            Action<DownloadDataCompletedEventArgs, bool> onComplete = (i, cancelled) =>
            {
                currentQuery = null;

                if (i.Error != null || cancelled)
                {
                    RefreshServerListInner(null);
                    return;
                }

                var data = Encoding.UTF8.GetString(i.Result);
                var yaml = MiniYaml.FromString(data);

                var games = yaml.Select(a => FieldLoader.Load<GameServer>(a.Value))
                    .Where(gs => gs.Address != null);

                RefreshServerListInner(games);
                Game.RunAfterTick(() => RefreshServerListInner(games));
            };

            currentQuery = new Download(Game.Settings.Server.MasterServer + "list.php", _ => {}, onComplete);
        }
Exemplo n.º 54
0
        void ShowDownloadDialog()
        {
            statusLabel.GetText       = () => "Fetching list of mirrors...";
            progressBar.Indeterminate = true;

            var retryButton = panel.Get <ButtonWidget>("RETRY_BUTTON");

            retryButton.IsVisible = () => false;

            var cancelButton = panel.Get <ButtonWidget>("CANCEL_BUTTON");

            var mirrorsFile = Platform.ResolvePath("^", "Content", Game.modData.Manifest.Mod.Id, "mirrors.txt");
            var file        = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            var dest        = Platform.ResolvePath("^", "Content", Game.modData.Manifest.Mod.Id);

            Action <DownloadProgressChangedEventArgs> onDownloadProgress = i =>
            {
                var dataReceived = 0.0f;
                var dataTotal    = 0.0f;
                var mag          = 0;
                var dataSuffix   = "";

                if (i.TotalBytesToReceive < 0)
                {
                    dataTotal    = float.NaN;
                    dataReceived = i.BytesReceived;
                    dataSuffix   = SizeSuffixes[0];
                }
                else
                {
                    mag          = (int)Math.Log(i.TotalBytesToReceive, 1024);
                    dataTotal    = i.TotalBytesToReceive / (float)(1L << (mag * 10));
                    dataReceived = i.BytesReceived / (float)(1L << (mag * 10));
                    dataSuffix   = SizeSuffixes[mag];
                }


                progressBar.Indeterminate = false;
                progressBar.Percentage    = i.ProgressPercentage;

                statusLabel.GetText = () => "Downloading from {4} {1:0.00}/{2:0.00} {3} ({0}%)".F(i.ProgressPercentage,
                                                                                                  dataReceived, dataTotal, dataSuffix,
                                                                                                  mirror != null ? new Uri(mirror).Host : "unknown host");
            };

            Action <string> onExtractProgress = s => Game.RunAfterTick(() => statusLabel.GetText = () => s);

            Action <string> onError = s => Game.RunAfterTick(() =>
            {
                statusLabel.GetText   = () => "Error: " + s;
                retryButton.IsVisible = () => true;
            });

            Action <AsyncCompletedEventArgs, bool> onDownloadComplete = (i, cancelled) =>
            {
                if (i.Error != null)
                {
                    onError(Download.FormatErrorMessage(i.Error));
                    return;
                }
                else if (cancelled)
                {
                    onError("Download cancelled");
                    return;
                }

                // Automatically extract
                statusLabel.GetText       = () => "Extracting...";
                progressBar.Indeterminate = true;
                if (InstallUtils.ExtractZip(file, dest, onExtractProgress, onError))
                {
                    Game.RunAfterTick(() =>
                    {
                        Ui.CloseWindow();
                        afterInstall();
                    });
                }
            };

            Action <AsyncCompletedEventArgs, bool> onFetchMirrorsComplete = (i, cancelled) =>
            {
                progressBar.Indeterminate = true;

                if (i.Error != null)
                {
                    onError(Download.FormatErrorMessage(i.Error));
                    return;
                }
                else if (cancelled)
                {
                    onError("Download cancelled");
                    return;
                }

                var mirrorList = new List <string>();
                using (var r = new StreamReader(mirrorsFile))
                {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        if (!string.IsNullOrEmpty(line))
                        {
                            mirrorList.Add(line);
                        }
                    }
                }
                mirror = mirrorList.Random(new MersenneTwister());

                // Save the package to a temp file
                var dl = new Download(mirror, file, onDownloadProgress, onDownloadComplete);
                cancelButton.OnClick = () => { dl.Cancel(); Ui.CloseWindow(); };
                retryButton.OnClick  = () => { dl.Cancel(); ShowDownloadDialog(); };
            };

            // Get the list of mirrors
            var updateMirrors = new Download(mirrorListUrl, mirrorsFile, onDownloadProgress, onFetchMirrorsComplete);

            cancelButton.OnClick = () => { updateMirrors.Cancel(); Ui.CloseWindow(); };
            retryButton.OnClick  = () => { updateMirrors.Cancel(); ShowDownloadDialog(); };
        }
Exemplo n.º 55
0
        void ShowDownloadDialog()
        {
            statusLabel.GetText = () => "Fetching list of mirrors...";
            progressBar.Indeterminate = true;

            var retryButton = panel.Get<ButtonWidget>("RETRY_BUTTON");
            retryButton.IsVisible = () => false;

            var cancelButton = panel.Get<ButtonWidget>("CANCEL_BUTTON");

            var mirrorsFile = Platform.ResolvePath("^", "Content", Game.modData.Manifest.Mod.Id, "mirrors.txt");
            var file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            var dest = Platform.ResolvePath("^", "Content", Game.modData.Manifest.Mod.Id);

            Action<DownloadProgressChangedEventArgs> onDownloadProgress = i =>
            {
                var dataReceived = 0.0f;
                var dataTotal = 0.0f;
                var mag = 0;
                var dataSuffix = "";

                if (i.TotalBytesToReceive < 0)
                {
                    dataTotal = float.NaN;
                    dataReceived = i.BytesReceived;
                    dataSuffix = SizeSuffixes[0];
                }
                else
                {
                    mag = (int)Math.Log(i.TotalBytesToReceive, 1024);
                    dataTotal = i.TotalBytesToReceive / (float)(1L << (mag * 10));
                    dataReceived = i.BytesReceived / (float)(1L << (mag * 10));
                    dataSuffix = SizeSuffixes[mag];
                }

                progressBar.Indeterminate = false;
                progressBar.Percentage = i.ProgressPercentage;

                statusLabel.GetText = () => "Downloading from {4} {1:0.00}/{2:0.00} {3} ({0}%)".F(i.ProgressPercentage,
                    dataReceived, dataTotal, dataSuffix,
                    mirror != null ? new Uri(mirror).Host : "unknown host");
            };

            Action<string> onExtractProgress = s => Game.RunAfterTick(() => statusLabel.GetText = () => s);

            Action<string> onError = s => Game.RunAfterTick(() =>
            {
                statusLabel.GetText = () => "Error: " + s;
                retryButton.IsVisible = () => true;
            });

            Action<AsyncCompletedEventArgs, bool> onDownloadComplete = (i, cancelled) =>
            {
                if (i.Error != null)
                {
                    onError(Download.FormatErrorMessage(i.Error));
                    return;
                }
                else if (cancelled)
                {
                    onError("Download cancelled");
                    return;
                }

                // Automatically extract
                statusLabel.GetText = () => "Extracting...";
                progressBar.Indeterminate = true;
                if (InstallUtils.ExtractZip(file, dest, onExtractProgress, onError))
                {
                    Game.RunAfterTick(() =>
                    {
                        Ui.CloseWindow();
                        afterInstall();
                    });
                }
            };

            Action<AsyncCompletedEventArgs, bool> onFetchMirrorsComplete = (i, cancelled) =>
            {
                progressBar.Indeterminate = true;

                if (i.Error != null)
                {
                    onError(Download.FormatErrorMessage(i.Error));
                    return;
                }
                else if (cancelled)
                {
                    onError("Download cancelled");
                    return;
                }

                var mirrorList = new List<string>();
                using (var r = new StreamReader(mirrorsFile))
                {
                    string line;
                    while ((line = r.ReadLine()) != null)
                        if (!string.IsNullOrEmpty(line))
                            mirrorList.Add(line);
                }
                mirror = mirrorList.Random(new MersenneTwister());

                // Save the package to a temp file
                var dl = new Download(mirror, file, onDownloadProgress, onDownloadComplete);
                cancelButton.OnClick = () => { dl.Cancel(); Ui.CloseWindow(); };
                retryButton.OnClick = () => { dl.Cancel(); ShowDownloadDialog(); };
            };

            // Get the list of mirrors
            var updateMirrors = new Download(mirrorListUrl, mirrorsFile, onDownloadProgress, onFetchMirrorsComplete);
            cancelButton.OnClick = () => { updateMirrors.Cancel(); Ui.CloseWindow(); };
            retryButton.OnClick = () => { updateMirrors.Cancel(); ShowDownloadDialog(); };
        }
Exemplo n.º 56
0
        /// <summary>
        /// Copy product
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="newName">New product name</param>
        /// <param name="isPublished">A value indicating whether a new product is published</param>
        /// <returns></returns>
        protected virtual Product CopyBaseProductData(Product product, string newName, bool isPublished)
        {
            //product download & sample download
            var downloadId       = product.DownloadId;
            var sampleDownloadId = product.SampleDownloadId;

            if (product.IsDownload)
            {
                var download = _downloadService.GetDownloadById(product.DownloadId);
                if (download != null)
                {
                    var downloadCopy = new Download
                    {
                        DownloadGuid   = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl    = download.DownloadUrl,
                        DownloadBinary = download.DownloadBinary,
                        ContentType    = download.ContentType,
                        Filename       = download.Filename,
                        Extension      = download.Extension,
                        IsNew          = download.IsNew
                    };
                    _downloadService.InsertDownload(downloadCopy);
                    downloadId = downloadCopy.Id;
                }

                if (product.HasSampleDownload)
                {
                    var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId);
                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download
                        {
                            DownloadGuid   = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl    = sampleDownload.DownloadUrl,
                            DownloadBinary = sampleDownload.DownloadBinary,
                            ContentType    = sampleDownload.ContentType,
                            Filename       = sampleDownload.Filename,
                            Extension      = sampleDownload.Extension,
                            IsNew          = sampleDownload.IsNew
                        };
                        _downloadService.InsertDownload(sampleDownloadCopy);
                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            var newSku = !string.IsNullOrWhiteSpace(product.Sku)
                ? string.Format(_localizationService.GetResource("Admin.Catalog.Products.Copy.SKU.New"), product.Sku)
                : product.Sku;
            // product
            var productCopy = new Product
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                VendorId             = product.VendorId,
                ProductTemplateId    = product.ProductTemplateId,
                AdminComment         = product.AdminComment,
                ShowOnHomePage       = product.ShowOnHomePage,
                MetaKeywords         = product.MetaKeywords,
                MetaDescription      = product.MetaDescription,
                MetaTitle            = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores      = product.LimitedToStores,
                Sku = newSku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin                             = product.Gtin,
                IsGiftCard                       = product.IsGiftCard,
                GiftCardType                     = product.GiftCardType,
                OverriddenGiftCardAmount         = product.OverriddenGiftCardAmount,
                RequireOtherProducts             = product.RequireOtherProducts,
                RequiredProductIds               = product.RequiredProductIds,
                AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
                IsDownload                       = product.IsDownload,
                DownloadId                       = downloadId,
                UnlimitedDownloads               = product.UnlimitedDownloads,
                MaxNumberOfDownloads             = product.MaxNumberOfDownloads,
                DownloadExpirationDays           = product.DownloadExpirationDays,
                DownloadActivationType           = product.DownloadActivationType,
                HasSampleDownload                = product.HasSampleDownload,
                SampleDownloadId                 = sampleDownloadId,
                HasUserAgreement                 = product.HasUserAgreement,
                UserAgreementText                = product.UserAgreementText,
                IsRecurring                      = product.IsRecurring,
                RecurringCycleLength             = product.RecurringCycleLength,
                RecurringCyclePeriod             = product.RecurringCyclePeriod,
                RecurringTotalCycles             = product.RecurringTotalCycles,
                IsRental                         = product.IsRental,
                RentalPriceLength                = product.RentalPriceLength,
                RentalPricePeriod                = product.RentalPricePeriod,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                ShipSeparately                   = product.ShipSeparately,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                DeliveryDateId                   = product.DeliveryDateId,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                IsTelecommunicationsOrBroadcastingOrElectronicServices =
                    product.IsTelecommunicationsOrBroadcastingOrElectronicServices,
                ManageInventoryMethod      = product.ManageInventoryMethod,
                ProductAvailabilityRangeId = product.ProductAvailabilityRangeId,
                UseMultipleWarehouses      = product.UseMultipleWarehouses,
                WarehouseId                   = product.WarehouseId,
                StockQuantity                 = product.StockQuantity,
                DisplayStockAvailability      = product.DisplayStockAvailability,
                DisplayStockQuantity          = product.DisplayStockQuantity,
                MinStockQuantity              = product.MinStockQuantity,
                LowStockActivityId            = product.LowStockActivityId,
                NotifyAdminForQuantityBelow   = product.NotifyAdminForQuantityBelow,
                BackorderMode                 = product.BackorderMode,
                AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions,
                OrderMinimumQuantity          = product.OrderMinimumQuantity,
                OrderMaximumQuantity          = product.OrderMaximumQuantity,
                AllowedQuantities             = product.AllowedQuantities,
                AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations,
                NotReturnable         = product.NotReturnable,
                DisableBuyButton      = product.DisableBuyButton,
                DisableWishlistButton = product.DisableWishlistButton,
                AvailableForPreOrder  = product.AvailableForPreOrder,
                PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc,
                CallForPrice                = product.CallForPrice,
                Price                       = product.Price,
                OldPrice                    = product.OldPrice,
                ProductCost                 = product.ProductCost,
                CustomerEntersPrice         = product.CustomerEntersPrice,
                MinimumCustomerEnteredPrice = product.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice = product.MaximumCustomerEnteredPrice,
                BasepriceEnabled            = product.BasepriceEnabled,
                BasepriceAmount             = product.BasepriceAmount,
                BasepriceUnitId             = product.BasepriceUnitId,
                BasepriceBaseAmount         = product.BasepriceBaseAmount,
                BasepriceBaseUnitId         = product.BasepriceBaseUnitId,
                MarkAsNew                   = product.MarkAsNew,
                MarkAsNewStartDateTimeUtc   = product.MarkAsNewStartDateTimeUtc,
                MarkAsNewEndDateTimeUtc     = product.MarkAsNewEndDateTimeUtc,
                Weight                      = product.Weight,
                Length                      = product.Length,
                Width                       = product.Width,
                Height                      = product.Height,
                AvailableStartDateTimeUtc   = product.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc     = product.AvailableEndDateTimeUtc,
                DisplayOrder                = product.DisplayOrder,
                Published                   = isPublished,
                Deleted                     = product.Deleted,
                CreatedOnUtc                = DateTime.UtcNow,
                UpdatedOnUtc                = DateTime.UtcNow
            };

            //validate search engine name
            _productService.InsertProduct(productCopy);

            //search engine name
            _urlRecordService.SaveSlug(productCopy, _urlRecordService.ValidateSeName(productCopy, string.Empty, productCopy.Name, true), 0);
            return(productCopy);
        }
Exemplo n.º 57
0
        void ShowDownloadDialog()
        {
            statusLabel.GetText = () => "Initializing...";
            progressBar.SetIndeterminate(true);
            var retryButton = panel.Get<ButtonWidget>("RETRY_BUTTON");
            retryButton.IsVisible = () => false;

            var cancelButton = panel.Get<ButtonWidget>("CANCEL_BUTTON");

            // Save the package to a temp file
            var file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            var dest = new string[] { Platform.SupportDir, "Content", Game.modData.Manifest.Mods[0] }.Aggregate(Path.Combine);

            Action<DownloadProgressChangedEventArgs> onDownloadProgress = i =>
            {
                if (progressBar.Indeterminate)
                    progressBar.SetIndeterminate(false);

                progressBar.Percentage = i.ProgressPercentage;
                statusLabel.GetText = () => "Downloading {1}/{2} kB ({0}%)".F(i.ProgressPercentage, i.BytesReceived / 1024, i.TotalBytesToReceive / 1024);
            };

            Action<string> onExtractProgress = s =>
            {
                    Game.RunAfterTick(() => statusLabel.GetText = () => s);
            };

            Action<string> onError = s =>
            {
                Game.RunAfterTick(() =>
                {
                    statusLabel.GetText = () => "Error: "+s;
                    retryButton.IsVisible = () => true;
                });
            };

            Action<AsyncCompletedEventArgs, bool> onDownloadComplete = (i, cancelled) =>
            {
                if (i.Error != null)
                {
                    onError(Download.FormatErrorMessage(i.Error));
                    return;
                }
                else if (cancelled)
                {
                    onError("Download cancelled");
                    return;
                }

                // Automatically extract
                statusLabel.GetText = () => "Extracting...";
                progressBar.SetIndeterminate(true);
                if (InstallUtils.ExtractZip(file, dest, onExtractProgress, onError))
                {
                    Game.RunAfterTick(() =>
                    {
                        Ui.CloseWindow();
                        afterInstall();
                    });
                }
            };

            var dl = new Download(installData["PackageURL"], file, onDownloadProgress, onDownloadComplete);

            cancelButton.OnClick = () => { dl.Cancel(); Ui.CloseWindow(); };
            retryButton.OnClick = () => { dl.Cancel(); ShowDownloadDialog(); };
        }
        /// <summary>
        /// 启动游戏
        /// </summary>
        /// <param name="version">版本</param>
        /// <param name="java">java</param>
        /// <param name="RAM">虚拟内存</param>
        /// <param name="name">游戏名</param>
        /// <param name="uuid">uuid</param>
        /// <param name="token">token</param>
        /// <param name="yggdrasilURLORID">ID</param>
        /// <param name="JVMparameter">JVM</param>
        /// <param name="RearParameter">后置参数</param>
        /// <param name="authentication">验证方式</param>
        public async Task StartGame(string version, string java, int RAM, string name, string uuid, string token, string yggdrasilURLORID, string JVMparameter, string RearParameter, AuthenticationServerMode authentication)
        {
            GacDownload GacDownload = new GacDownload();
            string      str3        = null;
            Download    download    = new Download();

            if (authentication == AuthenticationServerMode.yggdrasil)
            {
                if (SLC.FileExist(System.Directory.GetCurrentDirectory() + @"\SquareMinecraftLauncher\yggdrasilSquareMinecraftLauncher.jar") != null)
                {
                    this.SLC.SetFile("SquareMinecraftLauncher");
                    GacDownload.Download(System.Directory.GetCurrentDirectory() + @"\SquareMinecraftLauncher\yggdrasilSquareMinecraftLauncher.jar", "https://bmclapi2.bangbang93.com/mirrors/authlib-injector/artifact/39/authlib-injector-1.1.39.jar");
                    while (true)
                    {
                        if (GacDownload.Complete == 0 && GacDownload.Failure == 1)
                        {
                            throw new SquareMinecraftLauncherException("yggdrasil下载失败");
                        }
                        else if (GacDownload.Complete == 1)
                        {
                            break;
                        }
                        ForgeInstallCore.Delay(2000);
                    }
                }
                string s = download.getHtml(yggdrasilURLORID);
                if (s == null)
                {
                    throw new SquareMinecraftLauncherException("启动失败,无法获取相关信息");
                }
                byte[]   bytes      = Encoding.Default.GetBytes(s);
                string[] textArray1 = new string[] { "-javaagent:", System.Directory.GetCurrentDirectory(), @"\SquareMinecraftLauncher\yggdrasilSquareMinecraftLauncher.jar=", yggdrasilURLORID, " -Dauthlibinjector.side=client -Dauthlibinjector.yggdrasil.prefetched=", Convert.ToBase64String(bytes) };
                str3 = string.Concat(textArray1);
            }
            else
            {
                if (SLC.FileExist(System.Directory.GetCurrentDirectory() + @"\SquareMinecraftLauncher\UnifiedPassSquareMinecraftLauncher.jar") != null)
                {
                    this.SLC.SetFile("SquareMinecraftLauncher");
                    GacDownload.Download(System.Directory.GetCurrentDirectory() + @"\SquareMinecraftLauncher\UnifiedPassSquareMinecraftLauncher.jar", "https://login2.nide8.com:233/download/nide8auth.jar");
                    while (true)
                    {
                        if (GacDownload.Complete == 0 && GacDownload.Failure == 1)
                        {
                            throw new SquareMinecraftLauncherException("统一通行证下载失败");
                        }
                        else if (GacDownload.Complete == 1)
                        {
                            break;
                        }
                        ForgeInstallCore.Delay(2000);
                    }
                }
                str3 = "-javaagent:" + System.Directory.GetCurrentDirectory() + @"\SquareMinecraftLauncher\UnifiedPassSquareMinecraftLauncher.jar=" + yggdrasilURLORID;
            }
            if ((JVMparameter != null) && (JVMparameter != ""))
            {
                str3 = str3 + "," + JVMparameter;
            }
            await this.StartGame(version, java, RAM, name, uuid, token, str3, RearParameter);
        }
Exemplo n.º 59
0
        public virtual IActionResult AsyncUpload()
        {
            var httpPostedFile = Request.Form.Files.FirstOrDefault();

            if (httpPostedFile == null)
            {
                return(Json(new
                {
                    success = false,
                    message = "No file uploaded"
                }));
            }

            var fileBinary = _downloadService.GetDownloadBits(httpPostedFile);

            var qqFileNameParameter = "qqfilename";
            var fileName            = httpPostedFile.FileName;

            if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter))
            {
                fileName = Request.Form[qqFileNameParameter].ToString();
            }
            //remove path (passed in IE)
            fileName = _fileProvider.GetFileName(fileName);

            var contentType = httpPostedFile.ContentType;

            var fileExtension = _fileProvider.GetFileExtension(fileName);

            if (!string.IsNullOrEmpty(fileExtension))
            {
                fileExtension = fileExtension.ToLowerInvariant();
            }

            var download = new Download
            {
                DownloadGuid   = Guid.NewGuid(),
                UseDownloadUrl = false,
                DownloadUrl    = string.Empty,
                DownloadBinary = fileBinary,
                ContentType    = contentType,
                //we store filename without extension for downloads
                Filename  = _fileProvider.GetFileNameWithoutExtension(fileName),
                Extension = fileExtension,
                IsNew     = true
            };

            try
            {
                _downloadService.InsertDownload(download);

                //when returning JSON the mime-type must be set to text/plain
                //otherwise some browsers will pop-up a "Save As" dialog.
                return(Json(new
                {
                    success = true,
                    downloadId = download.Id,
                    downloadUrl = Url.Action("DownloadFile", new { downloadGuid = download.DownloadGuid })
                }));
            }
            catch (Exception exc)
            {
                _logger.Error(exc.Message, exc, _workContext.CurrentCustomer);

                return(Json(new
                {
                    success = false,
                    message = "File cannot be saved"
                }));
            }
        }
Exemplo n.º 60
0
        public virtual async Task <IActionResult> UploadFileContactAttribute(string attributeId,
                                                                             [FromServices] IDownloadService downloadService,
                                                                             [FromServices] IContactAttributeService contactAttributeService)
        {
            var attribute = await contactAttributeService.GetContactAttributeById(attributeId);

            if (attribute == null || attribute.AttributeControlType != AttributeControlType.FileUpload)
            {
                return(Json(new
                {
                    success = false,
                    downloadGuid = Guid.Empty,
                }));
            }
            var form = await HttpContext.Request.ReadFormAsync();

            var httpPostedFile = form.Files.FirstOrDefault();

            if (httpPostedFile == null)
            {
                return(Json(new
                {
                    success = false,
                    message = "No file uploaded",
                    downloadGuid = Guid.Empty,
                }));
            }

            var fileBinary = httpPostedFile.GetDownloadBits();

            var qqFileNameParameter = "qqfilename";
            var fileName            = httpPostedFile.FileName;

            if (String.IsNullOrEmpty(fileName) && form.ContainsKey(qqFileNameParameter))
            {
                fileName = form[qqFileNameParameter].ToString();
            }
            //remove path (passed in IE)
            fileName = Path.GetFileName(fileName);

            var contentType = httpPostedFile.ContentType;

            var fileExtension = Path.GetExtension(fileName);

            if (!String.IsNullOrEmpty(fileExtension))
            {
                fileExtension = fileExtension.ToLowerInvariant();
            }

            if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions))
            {
                var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.ToLowerInvariant()
                                            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                            .ToList();
                if (!allowedFileExtensions.Contains(fileExtension.ToLowerInvariant()))
                {
                    return(Json(new
                    {
                        success = false,
                        message = _translationService.GetResource("ShoppingCart.ValidationFileAllowed"),
                        downloadGuid = Guid.Empty,
                    }));
                }
            }

            if (attribute.ValidationFileMaximumSize.HasValue)
            {
                //compare in bytes
                var maxFileSizeBytes = attribute.ValidationFileMaximumSize.Value * 1024;
                if (fileBinary.Length > maxFileSizeBytes)
                {
                    //when returning JSON the mime-type must be set to text/plain
                    //otherwise some browsers will pop-up a "Save As" dialog.
                    return(Json(new
                    {
                        success = false,
                        message = string.Format(_translationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), attribute.ValidationFileMaximumSize.Value),
                        downloadGuid = Guid.Empty,
                    }));
                }
            }

            var download = new Download
            {
                DownloadGuid   = Guid.NewGuid(),
                UseDownloadUrl = false,
                DownloadUrl    = "",
                DownloadBinary = fileBinary,
                ContentType    = contentType,
                //we store filename without extension for downloads
                Filename  = Path.GetFileNameWithoutExtension(fileName),
                Extension = fileExtension,
                IsNew     = true
            };

            await downloadService.InsertDownload(download);

            //when returning JSON the mime-type must be set to text/plain
            //otherwise some browsers will pop-up a "Save As" dialog.
            return(Json(new
            {
                success = true,
                message = _translationService.GetResource("ShoppingCart.FileUploaded"),
                downloadUrl = Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }),
                downloadGuid = download.DownloadGuid,
            }));
        }