Inheritance: System.Web.UI.Page
Ejemplo n.º 1
1
        protected Downloads.File GetFileStream(Downloads.File file)
        {
            using (var client = new HttpClient()) {

            try {
                var data = client.GetByteArrayAsync(file.DownloadUrl).Result;

                    if (data.Length > 0) {

                    var result = data.ToArray();
                    MemoryStream ms = new MemoryStream();
                    ms.Write(data, 0, data.Length);
                    ms.Position = 0;

                    file.FileStream = ms;
                    file.IsValidFile = true;
                    ms.Flush();

                    } else {
                        throw new Exception("Error: Unable to download file");
                    }
                } catch (AggregateException ex) {
                    //log error
                    ex.ToString();
              }
            }
              return file;
        }
Ejemplo n.º 2
0
        private static void Upload(string[] args)
        {
            if (args.Length < 2)
            {
                Usage();
                return;
            }

            var myArgs = new string[4];
            Array.Copy(args.ToArray(), myArgs, Math.Min(args.Length, myArgs.Length));

            var config = new GitConfiguration();
            var upload = new Downloads(myArgs[1], myArgs[2] ?? config.GetValue("github.user"), myArgs[3] ?? config.GetValue("github.token"));
            Console.WriteLine(upload.AddFile(myArgs[0]));
        }
Ejemplo n.º 3
0
        public static Downloads.File ConvertImageToPdf(Downloads.File file)
        {
            PdfDocument doc = new PdfDocument();
            PdfSection section = doc.Sections.Add();
            PdfPageBase page = doc.Pages.Add();
            //Load a tiff image from system
            PdfImage image = PdfImage.FromStream(file.FileStream);
            //Set image display location and size in PDF
            float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
            float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
            float fitRate = Math.Max(widthFitRate, heightFitRate);
            float fitWidth = image.PhysicalDimension.Width / fitRate;
            float fitHeight = image.PhysicalDimension.Height / fitRate;
            page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight);

            var docId = Guid.NewGuid().ToString();

            try {

                string path = Path.GetTempPath();
                var filePath = path + @"\" + docId +"-" + file.FileName;
                //save and launch the file
                doc.SaveToFile(filePath);
                file.TempLink = filePath;

            } catch (Exception) {

                var tempPath = Environment.GetEnvironmentVariable("TEMP");
                var filePath = tempPath + @"\" + docId + "-" + file.FileName;
                doc.SaveToFile(filePath);
                file.TempLink = filePath;
            }

            doc.Close();
            file.FileStream.Close();

            return file;
        }
Ejemplo n.º 4
0
 bool IExplicitHasValue.ExplicitHasValue()
 {
     return(!string.IsNullOrWhiteSpace(Version) &&
            !string.IsNullOrWhiteSpace(Description) &&
            Downloads != null && Downloads.All(x => x.HasValue()));
 }
Ejemplo n.º 5
0
        public IEnumerable <Section> GetFileDownloadGroups()
        {
            var retVal = new List <Section>();

            var allEstabData = Downloads?.Where(x => new[] { "all.edubase.data", "all.edubase.data.links" }.Contains(x.Tag)) ?? Array.Empty <FileDownload>();
            var openAcademiesAndFreeSchoolsData = Downloads?.Where(x => new[] { "all.open.academies.and.free.schools", "all.open.academies.and.free.school.links" }.Contains(x.Tag)) ?? Array.Empty <FileDownload>();
            var openStateFundedSchoolsData      = Downloads?.Where(x => new[] { "all.open.state-funded.schools", "all.open.state-funded.school.links" }.Contains(x.Tag)) ?? Array.Empty <FileDownload>();
            var openChildrensCentresData        = Downloads?.Where(x => new[] { "all.open.childrens.centres", "all.open.childrens.centres.links" }.Contains(x.Tag)) ?? Array.Empty <FileDownload>();
            var allGroupData    = Downloads?.Where(x => new[] { "all.group.records", "all.group.links.records", "all.group.with.links.records", "academies.mat.membership" }.Contains(x.Tag)) ?? Array.Empty <FileDownload>();
            var openGroupData   = Downloads?.Where(x => new[] { "academy.sponsor.and.trust.links" }.Contains(x.Tag)) ?? Array.Empty <FileDownload>();
            var allGovernorData = Downloads?.Where(x => new[] { "all.governance.records", "all.mat.governance.records", "all.academy.governance.records", "all.la.maintained.governance.records" }.Contains(x.Tag)) ?? Array.Empty <FileDownload>();

            var miscData = Downloads?.Where(x => !(allEstabData).Concat(openAcademiesAndFreeSchoolsData)
                                            .Concat(openStateFundedSchoolsData)
                                            .Concat(openChildrensCentresData)
                                            .Concat(allGroupData)
                                            .Concat(openGroupData)
                                            .Concat(allGovernorData)
                                            .Select(y => y.Tag)
                                            .Contains(x.Tag)) ?? Array.Empty <FileDownload>();


            if (allEstabData.Any() || openAcademiesAndFreeSchoolsData.Any() || openStateFundedSchoolsData.Any() || openChildrensCentresData.Any())
            {
                var section = new Section {
                    Heading = "Establishment downloads", Paragraph = "You can download the complete record for the specified establishment types. There's a separate file with links to any predecessor or successor establishments."
                };

                if (allEstabData.Any())
                {
                    section.SubSections.Add(new Section
                    {
                        Heading = "All establishment data",
                        Files   = allEstabData.Select(x => new Tuple <string, FileDownload>(FileDownloadNames.ResourceManager.GetString(CleanTag(x.Tag)) ?? x.Name, x)).ToList()
                    });
                }

                if (openAcademiesAndFreeSchoolsData.Any())
                {
                    section.SubSections.Add(new Section
                    {
                        Heading = "Open academies and free schools data",
                        Files   = openAcademiesAndFreeSchoolsData.Select(x => new Tuple <string, FileDownload>(FileDownloadNames.ResourceManager.GetString(CleanTag(x.Tag)) ?? x.Name, x)).ToList()
                    });
                }

                if (openStateFundedSchoolsData.Any())
                {
                    section.SubSections.Add(new Section
                    {
                        Heading = "Open state-funded schools data",
                        Files   = openStateFundedSchoolsData.Select(x => new Tuple <string, FileDownload>(FileDownloadNames.ResourceManager.GetString(CleanTag(x.Tag)) ?? x.Name, x)).ToList()
                    });
                }

                if (openChildrensCentresData.Any())
                {
                    section.SubSections.Add(new Section
                    {
                        Heading = "Open children's centres data ",
                        Files   = openChildrensCentresData.Select(x => new Tuple <string, FileDownload>(FileDownloadNames.ResourceManager.GetString(CleanTag(x.Tag)) ?? x.Name, x)).ToList()
                    });
                }

                retVal.Add(section);
            }

            if (allGroupData.Any() || openGroupData.Any())
            {
                var section = new Section
                {
                    Heading   = "Establishment groups",
                    Paragraph = "You can download the complete record for the specified establishment group. There's a separate file with links to any establishments associated with the groups."
                };
                if (allGroupData.Any())
                {
                    section.SubSections.Add(new Section
                    {
                        Heading = "All group data",
                        Files   = allGroupData.Select(x =>
                                                      new Tuple <string, FileDownload>(
                                                          FileDownloadNames.ResourceManager.GetString(CleanTag(x.Tag)) ?? x.Name, x)).ToList()
                    });
                }

                if (openGroupData.Any())
                {
                    section.SubSections.Add(new Section
                    {
                        Heading = "Open group data",
                        Files   = openGroupData.Select(x =>
                                                       new Tuple <string, FileDownload>(
                                                           FileDownloadNames.ResourceManager.GetString(CleanTag(x.Tag)) ?? x.Name, x)).ToList()
                    });
                }

                retVal.Add(section);
            }

            if (allGovernorData.Any())
            {
                var section = new Section {
                    Heading = "Governors", Paragraph = "You can download the complete record for all governors listed within GIAS."
                };
                section.SubSections.Add(new Section
                {
                    Heading = "All governor data",
                    Files   = allGovernorData.Select(x => new Tuple <string, FileDownload>(FileDownloadNames.ResourceManager.GetString(CleanTag(x.Tag)) ?? x.Name, x)).ToList()
                });
                retVal.Add(section);
            }

            if (miscData.Any())
            {
                miscData.ForEach(x => x.AuthenticationRequired = true);

                var section = new Section {
                    Heading = "Miscellaneous", Paragraph = ""
                };
                section.SubSections.Add(new Section
                {
                    Heading = "All data",
                    Files   = miscData.Select(x => new Tuple <string, FileDownload>(FileDownloadNames.ResourceManager.GetString(CleanTag(x.Tag)) ?? x.Name, x)).ToList()
                });
                retVal.Add(section);
            }


            /*
             * tag=all.edubase.data
             * tag=all.edubase.data.links
             *
             * tag=all.open.academies.and.free.schools
             * tag=all.open.academies.and.free.school.links
             *
             * tag=all.open.state-funded.schools
             * tag=all.open.state-funded.school.links
             *
             * tag=academy.sponsor.and.trust.links
             * tag=all.open.childrens.centres
             * tag=all.governance.records
             * tag=all.mat.governance.records
             * tag=all.academy.governance.records
             * tag=all.la.maintained.governance.records
             *
             * --
             * tag=all.edubase.data
             * tag=all.edubase.data.links
             * tag=all.open.state-funded.schools
             * tag=all.open.state-funded.school.links
             * tag=all.open.academies.and.free.schools
             * tag=all.open.academies.and.free.school.links
             * tag=academy.sponsor.and.trust.links
             * tag=all.open.childrens.centres
             +tag=all.open.childrens.centres.links
             * tag=all.governance.records
             * tag=all.mat.governance.records
             * tag=all.academy.governance.records
             * tag=all.la.maintained.governance.records
             +tag=all.group.records
             +tag=all.group.links.records
             +tag=all.group.with.links.records
             */


            return(retVal);
        }
        /// <summary>
        /// This method downloads the package represented by the PackageDownloadHandle,
        /// uninstalls its current installation if necessary, and installs the package.
        ///
        /// Note that, if the package is already installed, it must be uninstallable
        /// </summary>
        internal void DownloadAndInstall(PackageDownloadHandle packageDownloadHandle, string downloadPath)
        {
            Downloads.Add(packageDownloadHandle);

            packageDownloadHandle.DownloadState = PackageDownloadHandle.State.Downloading;

            Task.Factory.StartNew(() =>
            {
                // Attempt to download package
                string pathDl;
                var res = Model.DownloadPackage(packageDownloadHandle.Id, packageDownloadHandle.VersionName, out pathDl);

                // if you fail, update download handle and return
                if (!res.Success)
                {
                    packageDownloadHandle.Error(res.Error);
                    return;
                }

                // if success, proceed to install the package
                DynamoViewModel.UIDispatcher.BeginInvoke((Action)(() =>
                {
                    try
                    {
                        packageDownloadHandle.Done(pathDl);

                        Package dynPkg;

                        var pmExtension = DynamoViewModel.Model.GetPackageManagerExtension();
                        var firstOrDefault = pmExtension.PackageLoader.LocalPackages.FirstOrDefault(pkg => pkg.ID == packageDownloadHandle.Id);
                        if (firstOrDefault != null)
                        {
                            var dynModel = DynamoViewModel.Model;
                            try
                            {
                                firstOrDefault.UninstallCore(dynModel.CustomNodeManager, pmExtension.PackageLoader, dynModel.PreferenceSettings);
                            }
                            catch
                            {
                                MessageBox.Show(String.Format(Resources.MessageFailToUninstallPackage,
                                                              DynamoViewModel.BrandingResourceProvider.ProductName,
                                                              packageDownloadHandle.Name),
                                                Resources.UninstallFailureMessageBoxTitle,
                                                MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }

                        if (packageDownloadHandle.Extract(DynamoViewModel.Model, downloadPath, out dynPkg))
                        {
                            pmExtension.PackageLoader.LoadPackages(new List <Package> {
                                dynPkg
                            });
                            packageDownloadHandle.DownloadState = PackageDownloadHandle.State.Installed;
                        }
                        else
                        {
                            packageDownloadHandle.DownloadState = PackageDownloadHandle.State.Error;
                            packageDownloadHandle.Error(Resources.MessageInvalidPackage);
                        }
                    }
                    catch (Exception e)
                    {
                        packageDownloadHandle.Error(e.Message);
                    }
                }));
            });
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Callback method called when the "Download" method returns from an HTTPWebRequest.
        /// </summary>
        /// <param name="result">The result of the asynchronous operation.</param>
        private void ResponseCallback(IAsyncResult result)
        {
            RequestState state = (RequestState)result.AsyncState;

            try
            {
                HttpWebRequest request = state.Request as HttpWebRequest;
                if (null != request)
                {
                    // Retrieve response.
                    using (HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse)
                    {
                        if (null != response && response.StatusCode == HttpStatusCode.OK)
                        {
                            using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
                            {
                                Feed parentFeed = state.Argument as Feed;

                                if (null != parentFeed)
                                {
                                    // Collection to store all articles
                                    Collection <Article> parsedArticles = _parser.ParseItems(reader, parentFeed);

                                    // Raise event for a single feed downloaded.
                                    if (null != SingleDownloadFinished)
                                    {
                                        SingleDownloadFinished(this, new SingleDownloadFinishedEventArgs(parentFeed, parsedArticles));
                                    }

                                    // Add to all downloads dictionary and raise AllDownloadsFinished if all async requests have finished.
                                    Downloads.Add(parentFeed, parsedArticles);

                                    lock (_lockObject)
                                    {
                                        IsDownloading = ((--_numOfRequests) > 0);
                                    }
                                    if (_numOfRequests <= 0 && null != AllDownloadsFinished)
                                    {
                                        AllDownloadsFinished(this, new AllDownloadsFinishedEventArgs(Downloads));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException we)
            {
                if (null != DownloadFailed)
                {
                    DownloadFailed(this, new DownloadFailedEventArgs(we)
                    {
                        BadConnectionException = true
                    });
                }
                return;
            }
            catch (XmlException e)
            {
                if (null != DownloadFailed)
                {
                    DownloadFailed(this, new DownloadFailedEventArgs(e));
                }
                return;
            }
        }
Ejemplo n.º 8
0
 public void AddDownload(Download download)
 {
     Downloads.Add(download);
     download.Queue.AddDownload(download);
 }
 public virtual OperationResult <Wrapped <TransferStatus> > Post(string transferId, AbortReason reason)
 {
     return(SecureFunc(() => new Wrapped <TransferStatus>(Downloads.CancelTransfer(transferId, reason))));
 }
Ejemplo n.º 10
0
 private void OnDownload(Gallerie e, float f)
 {
     Downloads?.Invoke(this, e, f);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// This method downloads the package represented by the PackageDownloadHandle,
        /// uninstalls its current installation if necessary, and installs the package.
        ///
        /// Note that, if the package is already installed, it must be uninstallable
        /// </summary>
        /// <param name="packageDownloadHandle"></param>
        internal void DownloadAndInstall(PackageDownloadHandle packageDownloadHandle)
        {
            var pkgDownload = new PackageDownload(packageDownloadHandle.Header._id, packageDownloadHandle.VersionName);

            Downloads.Add(packageDownloadHandle);

            packageDownloadHandle.DownloadState = PackageDownloadHandle.State.Downloading;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    var response = Model.Client.Execute(pkgDownload);
                    var pathDl   = PackageDownload.GetFileFromResponse(response);

                    DynamoViewModel.UIDispatcher.BeginInvoke((Action)(() =>
                    {
                        try
                        {
                            packageDownloadHandle.Done(pathDl);

                            Package dynPkg;

                            var firstOrDefault = DynamoViewModel.Model.PackageLoader.LocalPackages.FirstOrDefault(pkg => pkg.Name == packageDownloadHandle.Name);
                            if (firstOrDefault != null)
                            {
                                var dynModel = DynamoViewModel.Model;
                                try
                                {
                                    firstOrDefault.UninstallCore(dynModel.CustomNodeManager, dynModel.PackageLoader, dynModel.PreferenceSettings);
                                }
                                catch
                                {
                                    MessageBox.Show("Dynamo failed to uninstall the package: " + packageDownloadHandle.Name +
                                                    "  The package may need to be reinstalled manually.", "Uninstall Failure", MessageBoxButton.OK, MessageBoxImage.Error);
                                }
                            }

                            if (packageDownloadHandle.Extract(DynamoViewModel.Model, out dynPkg))
                            {
                                var downloadPkg = Package.FromDirectory(dynPkg.RootDirectory, DynamoViewModel.Model.Logger);

                                var loader = DynamoViewModel.Model.Loader;
                                var logger = DynamoViewModel.Model.Logger;
                                var libraryServices = DynamoViewModel.EngineController.LibraryServices;
                                downloadPkg.LoadIntoDynamo(
                                    loader,
                                    logger,
                                    libraryServices,
                                    DynamoViewModel.Model.Context,
                                    DynamoModel.IsTestMode,
                                    DynamoViewModel.Model.CustomNodeManager);

                                DynamoViewModel.Model.PackageLoader.LocalPackages.Add(downloadPkg);
                                packageDownloadHandle.DownloadState = PackageDownloadHandle.State.Installed;
                            }
                        }
                        catch (Exception e)
                        {
                            packageDownloadHandle.Error(e.Message);
                        }
                    }));
                }
                catch (Exception e)
                {
                    packageDownloadHandle.Error(e.Message);
                }
            });
        }
Ejemplo n.º 12
0
 public virtual OperationResult Post(string transferId)
 {
     return(SecureAction(() => Downloads.PauseTransfer(transferId)));
 }
Ejemplo n.º 13
0
 public static void RemoveDownload(Download dl)
 {
     dl.Stop();
     Downloads.Remove(dl);
 }
Ejemplo n.º 14
0
 public static List <Download> GetDownloadsWithStatus(DownloadStatus status)
 {
     return(Downloads.Where(x => x.Status == status).ToList());
 }
Ejemplo n.º 15
0
 public void CancelDownload(Download download)
 {
     download.Cancel();
     Downloads.Remove(download);
     download.Queue.RemoveDownload(download);
 }
Ejemplo n.º 16
0
        private void DownloaderEvent(object sender, EventArgs e)
        {
            switch (e)
            {
            case DownloadItemAddedEventArgs downloadItemAddedEvent:
                DownloadItemViewModel newDownloadItemViewModel = ToDownloadItemViewModel(downloadItemAddedEvent.AddedDownloadItem);
                downloadDictionary[newDownloadItemViewModel.Id] = newDownloadItemViewModel;
                ExecuteInUiThread(() =>
                {
                    Downloads.Add(newDownloadItemViewModel);
                    UpdateNonSelectionButtonStates();
                });
                break;

            case DownloadItemChangedEventArgs downloadItemChangedEvent:
                DownloadItem          changedDownloadItem          = downloadItemChangedEvent.ChangedDownloadItem;
                DownloadItemViewModel changedDownloadItemViewModel = downloadDictionary[changedDownloadItem.Id];
                bool statusChanged = changedDownloadItemViewModel.Status != changedDownloadItem.Status;
                ExecuteInUiThread(() =>
                {
                    changedDownloadItemViewModel.Name = changedDownloadItem.FileName;
                    if (statusChanged)
                    {
                        changedDownloadItemViewModel.Status = changedDownloadItem.Status;
                    }
                    changedDownloadItemViewModel.ProgressText  = GetDownloadProgressText(changedDownloadItem);
                    changedDownloadItemViewModel.ProgressValue = GetDownloadProgressValue(changedDownloadItem);
                    if (statusChanged)
                    {
                        if (changedDownloadItemViewModel.IsSelected)
                        {
                            UpdateSelectionButtonStates();
                        }
                        UpdateNonSelectionButtonStates();
                    }
                });
                break;

            case DownloadItemRemovedEventArgs downloadItemRemovedEvent:
                DownloadItem          removedDownloadItem          = downloadItemRemovedEvent.RemovedDownloadItem;
                DownloadItemViewModel removedDownloadItemViewModel = downloadDictionary[removedDownloadItem.Id];
                ExecuteInUiThread(() =>
                {
                    bool isSelected = removedDownloadItemViewModel.IsSelected;
                    Downloads.Remove(removedDownloadItemViewModel);
                    if (isSelected)
                    {
                        UpdateSelectionButtonStates();
                    }
                    UpdateNonSelectionButtonStates();
                });
                break;

            case DownloadItemLogLineEventArgs downloadItemLogLineEvent:
                DownloadItemViewModel downloadItemViewModel = downloadDictionary[downloadItemLogLineEvent.DownloadItemId];
                if (downloadItemLogLineEvent.LineIndex >= downloadItemViewModel.Logs.Count)
                {
                    ExecuteInUiThread(() => downloadItemViewModel.Logs.Add(ToDownloadItemLogLineViewModel(downloadItemLogLineEvent.LogLine)));
                }
                break;
            }
        }
Ejemplo n.º 17
0
 private void RemoveAllCompletedDownloads()
 {
     MainModel.Downloader.RemoveDownloads(Downloads.Where(downloadItem => IsCompleted(downloadItem.Status)).Select(downloadItem => downloadItem.Id));
 }
Ejemplo n.º 18
0
 private Downloads.File GetDownloadDoc(Downloads.File file)
 {
     return GetFileStream(file);
 }
Ejemplo n.º 19
0
 public void DownloadLatestMIUIByXiaomieuToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Downloads.downloadcall("Downloading xiaomi.eu_multi_HMNote7_20.1.21_v11-10...", "https://qc1.androidfilehost.com/dl/ppdBGi8VYCMrcKSJ1tvgog/1580287554/4349826312261709661/xiaomi.eu_multi_HMNote7_20.1.21_v11-10.zip", @"C:\adb\xiaomieu\xiaomi.eu_multi_HMNote7_20.1.21_v11-10.zip");
     visual_reLoad();
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Downloads the provided List of Feeds.
        /// You cannot call download while downloads are in progress.
        /// </summary>
        /// <param name="feeds">List of feeds to download.</param>
        public void Download(IList <Feed> feeds)
        {
            // Clear any leftover stored articles/feeds in Downloads and _allRequests.
            Downloads.Clear();
            _allRequests.Clear();

            // Set the timer for timeouts if parsing syndication feeds.
            if (_parser is SynFeedParser)
            {
                int timeLimit;
                if (Settings.InitialLaunchSetting)
                {
                    timeLimit = 20000; // 20 second limit for initial launch.
                }
                else
                {
                    timeLimit = 7500; // Otherwise, 7.5 second time limit.
                }
                TimerCallback tc = new TimerCallback(TimeoutConnections);
                _timeout = new Timer(tc, this, timeLimit, Timeout.Infinite);
            }

            if (null != feeds && feeds.Count > 0)
            {
                lock (_lockObject)
                {
                    _numOfRequests += feeds.Count;
                }
                IsDownloading = true;

                // Download each separate feed.
                foreach (Feed feed in feeds)
                {
                    string feedURI = feed.FeedBaseURI;
                    if (null != feedURI)
                    {
                        HttpWebRequest feedRequest = HttpWebRequest.Create(feedURI) as HttpWebRequest;

                        // Check if the application has been set to wifi-only or not.
                        if (WifiOnly)
                        {
                            feedRequest.SetNetworkRequirement(NetworkSelectionCharacteristics.NonCellular);
                        }
                        if (null != feedRequest)
                        {
                            RequestState feedState = new RequestState()
                            {
                                // Change the owner to the parent HTTPWebRequest.
                                Request = feedRequest,
                                // Change the argument to be the current feed to be downloaded.
                                Argument = feed,
                            };

                            // Begin download.
                            feedRequest.BeginGetResponse(ResponseCallback, feedState);

                            // Keep track of the download.
                            _allRequests.Add(feed, feedRequest);
                        }
                    }
                }
            }
        }
        public ActionResult DownloadNotes(int noteid)
        {
            // get note from SellerNotes table
            var note = context.SellerNotes.Find(noteid);

            // if note is not found
            if (note == null)
            {
                return(HttpNotFound());
            }
            // get first object of seller note attachement for attachement
            var noteattachement = context.SellerNotesAttachements.Where(x => x.NoteID == note.ID).FirstOrDefault();
            // get logged in user
            var user = context.Users.Where(x => x.EmailID == User.Identity.Name).FirstOrDefault();

            // variable for attachement path
            string path;

            // note's seller if and logged in user's id is same it means user want to download his own book
            // then we need to provide downloaded note without entry in download tables
            if (note.SellerID == user.ID)
            {
                // get attavhement path
                path = Server.MapPath(noteattachement.FilePath);

                DirectoryInfo dir = new DirectoryInfo(path);
                // create zip of attachement
                using (var memoryStream = new MemoryStream())
                {
                    using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                    {
                        foreach (var item in dir.GetFiles())
                        {
                            // file path is attachement path + file name
                            string filepath = path + item.ToString();
                            ziparchive.CreateEntryFromFile(filepath, item.ToString());
                        }
                    }
                    // return zip
                    return(File(memoryStream.ToArray(), "application/zip", note.Title + ".zip"));
                }
            }

            // if note is free then we need to add entry in download table with allow download is true
            // downloaded date time is current date time for first time download
            // if user download again then we have to return zip of attachement without changes in data
            if (note.IsPaid == false)
            {
                // if user has already downloaded note then get download object
                var downloadfreenote = context.Downloads.Where(x => x.NoteID == noteid && x.Downloader == user.ID && x.IsSellerHasAllowedDownload == true && x.AttachmentPath != null).FirstOrDefault();
                // if user is not downloaded
                if (downloadfreenote == null)
                {
                    // create download object
                    Downloads download = new Downloads
                    {
                        NoteID     = note.ID,
                        Seller     = note.SellerID,
                        Downloader = user.ID,
                        IsSellerHasAllowedDownload = true,
                        AttachmentPath             = noteattachement.FilePath,
                        IsAttachmentDownloaded     = true,
                        AttachmentDownloadedDate   = DateTime.Now,
                        IsPaid         = note.IsPaid,
                        PurchasedPrice = note.SellingPrice,
                        NoteTitle      = note.Title,
                        NoteCategory   = note.NoteCategories.Name,
                        CreatedDate    = DateTime.Now,
                        CreatedBy      = user.ID,
                    };

                    // save download object in database
                    context.Downloads.Add(download);
                    context.SaveChanges();

                    path = Server.MapPath(download.AttachmentPath);
                }
                // if user is already downloaded note then get attachement path
                else
                {
                    path = Server.MapPath(downloadfreenote.AttachmentPath);
                }

                DirectoryInfo dir = new DirectoryInfo(path);
                // create zip of attachement
                using (var memoryStream = new MemoryStream())
                {
                    using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                    {
                        foreach (var item in dir.GetFiles())
                        {
                            // file path is attachement path + file name
                            string filepath = path + item.ToString();
                            ziparchive.CreateEntryFromFile(filepath, item.ToString());
                        }
                    }
                    // return zip
                    return(File(memoryStream.ToArray(), "application/zip", note.Title + ".zip"));
                }
            }
            // if note is paid
            else
            {
                // get download object
                var downloadpaidnote = context.Downloads.Where(x => x.NoteID == noteid && x.Downloader == user.ID && x.IsSellerHasAllowedDownload == true && x.AttachmentPath != null).FirstOrDefault();

                // if user is not already downloaded
                if (downloadpaidnote != null)
                {
                    // if user is download note first time then we need to update following record in download table
                    if (downloadpaidnote.IsAttachmentDownloaded == false)
                    {
                        downloadpaidnote.AttachmentDownloadedDate = DateTime.Now;
                        downloadpaidnote.IsAttachmentDownloaded   = true;
                        downloadpaidnote.ModifiedDate             = DateTime.Now;
                        downloadpaidnote.ModifiedBy = user.ID;

                        // update ans save data in database
                        context.Entry(downloadpaidnote).State = EntityState.Modified;
                        context.SaveChanges();
                    }

                    // get attachement path
                    path = Server.MapPath(downloadpaidnote.AttachmentPath);

                    DirectoryInfo dir = new DirectoryInfo(path);

                    // create zip of attachement
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                        {
                            foreach (var item in dir.GetFiles())
                            {
                                // file path is attachement path + file name
                                string filepath = path + item.ToString();
                                ziparchive.CreateEntryFromFile(filepath, item.ToString());
                            }
                        }
                        // return zip
                        return(File(memoryStream.ToArray(), "application/zip", note.Title + ".zip"));
                    }
                }
                return(RedirectToAction("Notes", "NotesDetails", new { id = noteid }));
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Callback method called when the "Download" method returns from an HTTPWebRequest.
        /// </summary>
        /// <param name="result">The result of the asynchronous operation.</param>
        private void ResponseCallback(IAsyncResult result)
        {
            RequestState state      = result.AsyncState as RequestState;
            Feed         parentFeed = state.Argument as Feed;

            if (null != parentFeed)
            {
                HttpWebRequest request = state.Request as HttpWebRequest;

                // Progress only if this download has not been timed out.

                if (null != request)
                {
                    // Retrieve response.
                    try
                    {
                        using (HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse)
                        {
                            if (null != response && response.StatusCode == HttpStatusCode.OK)
                            {
                                using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
                                {
                                    // Collection to store all articles
                                    Collection <Article> parsedArticles = _parser.ParseItems(reader, parentFeed);

                                    // Raise event for a single feed downloaded.
                                    if (null != SingleDownloadFinished)
                                    {
                                        SingleDownloadFinished(this, new SingleDownloadFinishedEventArgs(parentFeed, parsedArticles));
                                    }

                                    // Add to all downloads dictionary and raise AllDownloadsFinished if all async requests have finished.
                                    Downloads.Add(parentFeed, parsedArticles);
                                    CheckIfDone();
                                }
                            }
                        }
                    }
                    catch (WebException we)
                    {
                        if (we.Status == WebExceptionStatus.RequestCanceled)
                        {
                            // The web request was timed out. Let debug know it failed.
                            System.Diagnostics.Debug.WriteLine("ERROR: Feed \"" + parentFeed.FeedTitle + "\" was timed out.");
                            CheckIfDone();
                            return;
                        }
                        else if (we.Message == "The remote server returned an error: NotFound.")
                        {
                            // The web site did not respond. This means one of two things: Either the web site is bad, or you have no internet.
                            // If error code NotFound is received, then there is no connection. Throw the exception.
                            if ((we.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
                            {
                                // WebTools throws an exception if without connection. Warn the user.
                                CheckIfDone();
                                if (!IsDownloading)
                                {
                                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                                    {
                                        MessageBox.Show("FeedCast is unable to reach a connection. Please check your network connectivity.");
                                    });
                                }
                            }
                            // If error code InternalServerError is received, then it is a faulty site.
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("ERROR: Feed \"" + parentFeed.FeedTitle + "\" is faulty.");
                                CheckIfDone();
                                return;
                            }
                        }
                        else
                        {
                            // Unexpected web exception.
                            throw we;
                        }
                    }
                }
            }
        }
 public void ClearCompletedDownloads()
 {
     Downloads.Where((x) => x.DownloadState == PackageDownloadHandle.State.Installed ||
                     x.DownloadState == PackageDownloadHandle.State.Error).ToList().ForEach(x => Downloads.Remove(x));
 }
Ejemplo n.º 24
0
 public OperationResult <DownloadToken> Get(string transferId)
 {
     return(SecureFunc(() => Downloads.ReloadToken(transferId)));
 }
Ejemplo n.º 25
0
 internal void AddDownload(TransferEventArgs download)
 {
     Downloads.InternalAdd(download);
 }
        public ActionResult DownloadNotes(int noteid)
        {
            //find note
            var note = dobj.NoteDetail.Find(noteid);

            if (note == null)
            {
                return(HttpNotFound());
            }

            var noteattachement = dobj.NotesAttachments.Where(x => x.NoteID == note.ID).FirstOrDefault();

            var user = dobj.Users.Where(x => x.EmailID == User.Identity.Name).FirstOrDefault();

            // variable for attachement path
            string path;

            if (note.SellerID == user.ID)
            {
                // get attachement path
                path = Server.MapPath(noteattachement.FilePath);

                DirectoryInfo dir = new DirectoryInfo(path);

                // create zip of attachement
                using (var memoryStream = new MemoryStream())
                {
                    using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                    {
                        foreach (var item in dir.GetFiles())
                        {
                            // file path is attachement path + file name
                            string filepath = path + item.ToString();
                            ziparchive.CreateEntryFromFile(filepath, item.ToString());
                        }
                    }
                    // return zip
                    return(File(memoryStream.ToArray(), "application/zip", note.Title + ".zip"));
                }
            }

            // if note is free then we need to add entry in download table with allow download is true

            if (note.IsPaid == false)
            {
                // if user has already downloaded note then get download object
                var downloadfreenote = dobj.Downloads.Where(x => x.NoteID == noteid && x.Downloader == user.ID && x.IsSellerHasAllowedDownload == true && x.AttachmentPath != null).FirstOrDefault();

                // user is not downloaded note
                if (downloadfreenote == null)
                {
                    Downloads download = new Downloads
                    {
                        NoteID     = note.ID,
                        Seller     = note.SellerID,
                        Downloader = user.ID,
                        IsSellerHasAllowedDownload = true,
                        AttachmentPath             = noteattachement.FilePath,
                        IsAttachmentDownloaded     = true,
                        AttachmentDownloadedDate   = DateTime.Now,
                        IsPaid         = note.IsPaid,
                        PurchasedPrice = note.SellingPrice,
                        NoteTitle      = note.Title,
                        NoteCategory   = note.NoteCategories.Name,
                        CreatedDate    = DateTime.Now,
                        CreatedBy      = user.ID,
                    };


                    dobj.Downloads.Add(download);
                    dobj.SaveChanges();

                    path = Server.MapPath(download.AttachmentPath);
                }

                // if user is already downloaded note then get attachement path
                else
                {
                    path = Server.MapPath(downloadfreenote.AttachmentPath);
                }

                DirectoryInfo dir = new DirectoryInfo(path);


                //zip of attachment

                using (var memoryStream = new MemoryStream())
                {
                    using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                    {
                        foreach (var item in dir.GetFiles())
                        {
                            // file path is attachement path + file name
                            string filepath = path + item.ToString();
                            ziparchive.CreateEntryFromFile(filepath, item.ToString());
                        }
                    }
                    // return zip
                    return(File(memoryStream.ToArray(), "application/zip", note.Title + ".zip"));
                }
            }


            //paid note
            else
            {
                // get download object
                var downloadpaidnote = dobj.Downloads.Where(x => x.NoteID == noteid && x.Downloader == user.ID && x.IsSellerHasAllowedDownload == true && x.AttachmentPath != null).FirstOrDefault();

                // if user is not already downloaded
                if (downloadpaidnote != null)
                {
                    // if user is download note first time then we need to update following record in download table
                    if (downloadpaidnote.IsAttachmentDownloaded == false)
                    {
                        downloadpaidnote.IsAttachmentDownloaded   = true;
                        downloadpaidnote.AttachmentDownloadedDate = DateTime.Now;
                        downloadpaidnote.ModifiedDate             = DateTime.Now;
                        downloadpaidnote.ModifiedBy = user.ID;

                        // update ans save data in database
                        dobj.Entry(downloadpaidnote).State = EntityState.Modified;
                        dobj.SaveChanges();
                    }

                    path = Server.MapPath(downloadpaidnote.AttachmentPath);

                    DirectoryInfo dir = new DirectoryInfo(path);

                    //  zip of attachement
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                        {
                            foreach (var item in dir.GetFiles())
                            {
                                // file path is attachement path + file name
                                string filepath = path + item.ToString();
                                ziparchive.CreateEntryFromFile(filepath, item.ToString());
                            }
                        }

                        return(File(memoryStream.ToArray(), "application/zip", note.Title + ".zip"));
                    }
                }
                return(RedirectToAction("NoteDetail", "SearchNotes", new { id = noteid }));
            }
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Executes the task.
 /// </summary>
 protected override void ExecuteTask()
 {
     var filename = Project.GetFullPath(Filename);
     if (!File.Exists(filename))
     {
         Project.Log(this, Level.Error, string.Format("File {0} not found.", filename));
     }
     var downloads = new Downloads(Repository, UserName, UserToken);
     Project.Log(this, Level.Info, string.Format("Uploading {0} to {1}.", filename, Repository));
     downloads.AddFile(filename, Description);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Gets a download token for the <see cref="SourceFile"/> and
 /// assigns it to the <see cref="Token"/> property.
 /// </summary>
 /// <returns>The retrieved token.</returns>
 protected DownloadToken InitToken()
 {
     Token = Downloads.RequestDownloadToken(SourceFileInfo.FullName, false);
     return(Token);
 }
Ejemplo n.º 29
0
        private void CheckSteamForNewMods()
        {
            status_toolstrip_label.Text = "Checking for new mods...";

            ulong[] subscribedIDs;
            try
            {
                subscribedIDs = Workshop.GetSubscribedItems();
            }
            catch (InvalidOperationException)
            {
                // Steamworks not initialized?
                // Game taking over?
                status_toolstrip_label.Text = "Error checking for new mods.";
                return;
            }

            var change = false;

            foreach (var id in subscribedIDs)
            {
                var status = Workshop.GetDownloadStatus(id);

                if (status.HasFlag(EItemState.k_EItemStateInstalled))
                {
                    // already installed
                    continue;
                }

                if (Downloads.Any(d => d.WorkshopID == (long)id))
                {
                    // already observing
                    continue;
                }

                // Get info
                var detailsRequest = new ItemDetailsRequest(id).Send().WaitForResult();
                var details        = detailsRequest.Result;
                var link           = detailsRequest.GetPreviewURL();

                var downloadMod = new ModEntry
                {
                    Name        = details.m_rgchTitle,
                    DateCreated = DateTimeOffset.FromUnixTimeSeconds(details.m_rtimeCreated).DateTime,
                    DateUpdated = DateTimeOffset.FromUnixTimeSeconds(details.m_rtimeUpdated).DateTime,
                    //Path = Path.Combine(Settings.GetWorkshopPath(), "" + id),
                    Image      = link,
                    Source     = ModSource.SteamWorkshop,
                    WorkshopID = (int)id,
                    State      = ModState.New | ModState.NotInstalled
                };

                // Start download
                Workshop.DownloadItem(id);
                //
                Downloads.Add(downloadMod);
                change = true;
            }

            if (change)
            {
                RefreshModList();
            }

            status_toolstrip_label.Text = StatusBarIdleString;
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Gets a single download token for a given file.
 /// </summary>
 protected DownloadToken GetToken(string filePath)
 {
     return(Downloads.GetTransfersForResource(filePath).Single());
 }
Ejemplo n.º 31
0
 public StreamingService()
 {
     _stream    = new Streaming(this);
     _downloads = new Downloads();
 }
Ejemplo n.º 32
0
        public void SeedMembershipData()
        {
            #region Lorem Ipsum - Dummy Data
            var description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
            #endregion

            #region Fetch a User
            var email  = "[email protected]";
            var userId = string.Empty;

            if (Users.Any(r => r.Email.Equals(email)))
            {
                userId = Users.First(r => r.Email.Equals(email)).Id;
            }
            else
            {
                return;
            }
            #endregion

            #region Add Instructors if they don't already exist
            if (!Instructors.Any())
            {
                var instructors = new List <Instructor>
                {
                    new Instructor {
                        Name        = "John Doe",
                        Description = description.Substring(20, 50),
                        Thumbnail   = "/images/Ice-Age-Scrat-icon.png"
                    },
                    new Instructor {
                        Name        = "Jane Doe",
                        Description = description.Substring(30, 40),
                        Thumbnail   = "/images/Ice-Age-Scrat-icon.png"
                    }
                };
                Instructors.AddRange(instructors);
                SaveChanges();
            }
            if (Instructors.Count() < 2)
            {
                return;
            }
            #endregion

            #region Add Courses if they don't already exist
            if (!Courses.Any())
            {
                var instructorId1 = Instructors.First().Id;
                var instructorId2 = Instructors.Skip(1).FirstOrDefault().Id;

                var courses = new List <Course>
                {
                    new Course {
                        InstructorId    = instructorId1,
                        Title           = "Course 1",
                        Description     = description,
                        ImageUrl        = "/images/course1.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    },
                    new Course {
                        InstructorId    = instructorId2,
                        Title           = "Course 2",
                        Description     = description,
                        ImageUrl        = "/images/course2.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    },
                    new Course {
                        InstructorId    = instructorId1,
                        Title           = "Course 3",
                        Description     = description,
                        ImageUrl        = "/images/course3.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    }
                };
                Courses.AddRange(courses);
                SaveChanges();
            }
            if (Courses.Count() < 3)
            {
                return;
            }
            #endregion

            #region Fetch Course ids if any courses exists
            var courseId1 = Courses.First().Id;
            var courseId2 = Courses.Skip(1).FirstOrDefault().Id;
            var courseId3 = Courses.Skip(2).FirstOrDefault().Id;
            #endregion

            #region Add UserCourses connections if they don't already exist
            if (!UserCourses.Any())
            {
                UserCourses.Add(new UserCourse {
                    UserId = userId, CourseId = courseId1
                });
                UserCourses.Add(new UserCourse {
                    UserId = userId, CourseId = courseId2
                });
                UserCourses.Add(new UserCourse {
                    UserId = userId, CourseId = courseId3
                });

                SaveChanges();
            }
            if (UserCourses.Count() < 3)
            {
                return;
            }
            #endregion

            #region Add Modules if they don't already exist
            if (!Modules.Any())
            {
                var modules = new List <Module>
                {
                    new Module {
                        Course = Find <Course>(courseId1), Title = "Modeule 1"
                    },
                    new Module {
                        Course = Find <Course>(courseId1), Title = "Modeule 2"
                    },
                    new Module {
                        Course = Find <Course>(courseId2), Title = "Modeule 3"
                    }
                };
                Modules.AddRange(modules);
                SaveChanges();
            }
            if (Modules.Count() < 3)
            {
                return;
            }
            #endregion

            #region Fetch Module ids if any modules exist
            var module1 = Modules.First();
            var module2 = Modules.Skip(1).FirstOrDefault();
            var module3 = Modules.Skip(2).FirstOrDefault();
            #endregion

            #region Add Videos if they don't already exist
            if (!Videos.Any())
            {
                var videos = new List <Video>
                {
                    new Video {
                        ModuleId    = module1.Id, CourseId = module1.CourseId,
                        Title       = "Video 1 Title",
                        Description = description.Substring(1, 35),
                        Duration    = 50, Thumbnail = "/images/video1.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module1.Id, CourseId = module1.CourseId,
                        Title       = "Video 2 Title",
                        Description = description.Substring(5, 35),
                        Duration    = 45, Thumbnail = "/images/video2.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module1.Id, CourseId = module1.CourseId,
                        Title       = "Video 3 Title",
                        Description = description.Substring(10, 35),
                        Duration    = 41, Thumbnail = "/images/video3.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module3.Id, CourseId = module3.CourseId,
                        Title       = "Video 4 Title",
                        Description = description.Substring(15, 35),
                        Duration    = 41, Thumbnail = "/images/video4.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module2.Id, CourseId = module2.CourseId,
                        Title       = "Video 5 Title",
                        Description = description.Substring(20, 35),
                        Duration    = 42, Thumbnail = "/images/video5.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    }
                };
                Videos.AddRange(videos);
                SaveChanges();
            }
            #endregion

            #region Add Downloads if they don't already exist
            if (!Downloads.Any())
            {
                var downloads = new List <Download>
                {
                    new Download {
                        ModuleId = module1.Id, CourseId = module1.CourseId,
                        Title    = "ADO.NET 1 (PDF)", Url = "https://some-url"
                    },

                    new Download {
                        ModuleId = module1.Id, CourseId = module1.CourseId,
                        Title    = "ADO.NET 2 (PDF)", Url = "https://some-url"
                    },

                    new Download {
                        ModuleId = module3.Id, CourseId = module3.CourseId,
                        Title    = "ADO.NET 1 (PDF)", Url = "https://some-url"
                    }
                };

                Downloads.AddRange(downloads);
                SaveChanges();
            }
            #endregion
        }
Ejemplo n.º 33
0
 private void StopAllDownloads()
 {
     MainModel.Downloader.StopDownloads(Downloads.Where(downloadItem => CanBeStopped(downloadItem.Status)).Select(downloadItem => downloadItem.Id));
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Requests a download token for a given resource.
 /// </summary>
 public OperationResult <DownloadToken> Get(string filePath, bool includeFileHash)
 {
     return(SecureFunc(() => Downloads.RequestDownloadToken(filePath, includeFileHash)));
 }
Ejemplo n.º 35
0
 protected Downloads.File GetDownloadImage(Downloads.File file)
 {
     var result = GetFileStream(file);
     return ImageToPDF.ConvertImageToPdf(result);
 }
Ejemplo n.º 36
0
 private void DownloadLatestMIUIToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Downloads.downloadcall("Downloading MI Recovery GLOBAL-V11.0.4.0.PFGMIXM...", "https://bitbucket.org/Franco28/flashtool-motorola-moto-g5-g5plus/downloads/recovery.img", @"C:\adb\.settings\recovery.img");
     visual_reLoad();
 }