Exemple #1
0
        public void Read(SnpCollection snps, CancellationToken cancel, Progress progress) {
            if (this.filename == null) throw new ArgumentNullException("filename cannot be null.");
            if (String.IsNullOrWhiteSpace(filename)) throw new ArgumentOutOfRangeException("filename cannot be empty.");

            string ext = Path.GetExtension(filename);
            if (ext.EndsWith("csv", StringComparison.InvariantCultureIgnoreCase)) {
                try {
                    Read(Genome.GenomeType.Ftdna, snps, cancel, progress);
                    return;
                }
                catch (Exception) { }
                genome.Clear();
                try {
                    Read(Genome.GenomeType.MeAnd23v2, snps, cancel, progress);
                    return;
                }
                catch (Exception) { }
            } else {
                try {
                    Read(Genome.GenomeType.MeAnd23v2, snps, cancel, progress);
                    return;
                }
                catch (Exception) { }
                genome.Clear();
                try {
                    Read(Genome.GenomeType.Ftdna, snps, cancel, progress);
                    return;
                }
                catch (Exception) { }
            }
            throw new ApplicationException("Could not read as either format.");
        }
Exemple #2
0
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();

        if (args.Length == 0) {
            Application.Run(new About());
        } else if (args.Length > 1 && args[0] == "--map") {
            if (File.Exists(SFMpq.DLL))
            {
                parsing = new Progress();
                parsing = new Progress();
                parsing.Visible = true;
                parsing.SetMapPath(args[1]);
                map = new Map(Application.StartupPath, args[1]);
                parsing.SetProgress(20, "comments and empty lines...");
                Preprocessor.SplitComments(map.script);
                map.script = Format.SplitEmptyLines(map.script);
                parsing.SetProgress(20, "comments and empty lines... DONE!");
                parsing.SetProgress(40, "user functions...");
                Analyzer.FindUserFunctions(map.script);
                Analyzer.GetGlobals(map.script);
                parsing.SetProgress(40, "user functions and structs... DONE!");
                parsing.SetProgress(60, "\"//! jasp\" blocks...");
                Preprocessor.ParseJaspBlock(map.script);
                parsing.SetProgress(60, "\"//! jasp\" blocks... DONE!");
                parsing.SetProgress(80, "Rebuilding parsed script...");
                map.script = Format.StringsToString(map.script).Split('\n');
                parsing.SetProgress(80, "Rebuilding parsed script... DONE!");
                parsing.SetProgress(100, "errors...");
                Preprocessor.SearchErrors(map.script);
            } else
                MessageBox.Show("File \"SFMpq.dll\" isn't exists.\nSorry :(", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    public void PrintPagesVoid()
    {
        CommandLineInterpreter oCLI = new CommandLineInterpreter();
        ActionCallingContext acc = new ActionCallingContext();

        string strPages = string.Empty;
        acc.AddParameter("TYPE", "PAGES");
        oCLI.Execute("selectionset", acc);
        acc.GetParameter("PAGES", ref strPages);

        Progress oProgress = new Progress("SimpleProgress");
        oProgress.SetAllowCancel(true);
        oProgress.SetAskOnCancel(true);
        oProgress.SetNeededSteps(3);
        oProgress.SetTitle("Drucken");
        oProgress.ShowImmediately();

        foreach (string Page in strPages.Split(';'))
        {
            if (!oProgress.Canceled())
            {
                acc.AddParameter("PAGENAME", Page);
                oCLI.Execute("print", acc);
            }
            else
            {
                break;
            }
        }
        oProgress.EndPart(true);

        return;
    }
Exemple #4
0
        /// <summary>
        /// Read data into the specified SnpCollection from the SnpCollection
        /// file having the specified filename (which may include a path). 
        /// The specified CancellationToken can be used to abort the read. 
        /// The progress parameter will be updated by this method with a 
        /// value of 0-100 to reflect the percent progress of the read.
        /// </summary>
        /// <param name="snps">The SnpCollection to receive the read data.</param>
        /// <param name="filename">The path and filename of the SnpCollection file.</param>
        /// <param name="cancel">The CancellationToken that can be used to abort the read.</param>
        /// <param name="progress">The progress parameter that will be updated to reflect 
        /// the percent progress of the read.</param>
        public static void Read(SnpCollection snps, string filename, CancellationToken cancel, Progress progress) {
            if (snps == null) throw new ArgumentNullException("The SnpCollection cannot be null.");
            if (filename == null) throw new ArgumentNullException("filename cannot be null.");
            if (String.IsNullOrWhiteSpace(filename)) throw new ArgumentOutOfRangeException("filename cannot be empty.");

            using (StreamReader reader = new StreamReader(filename)) {
                long length = 0;
                if (progress != null) length = reader.BaseStream.Length;
                string[] columns = new string[6];
                string line;
                while ((line = reader.ReadLine()) != null) {
                    cancel.ThrowIfCancellationRequested();
                    line.FastSplit(',', columns);
                    byte chr = Convert.ToByte(columns[2]);
                    if (chr == 0) chr = 23; // handles legacy use of 0 for X 
                    Snp snp;
                    if ((!String.IsNullOrWhiteSpace(columns[3]) && Char.IsDigit(columns[3][0]))) {
                        // new format snp file
                        snp = new Snp(columns[0], chr, Convert.ToInt32(columns[3]), Convert.ToSingle(columns[4]), columns[1], columns[5]);
                    } else {
                        // old SnpMap format snp file
                        snp = new Snp(columns[0], chr, -1, -1, columns[1], columns[3]);
                    }
                    snps.Add(snp);
                    if (progress != null) progress.Set(reader.BaseStream.Position, length);

                }
            }
        }
        public ProgressViewModel()
        {
            this.Bookmarks = new ObservableCollection<Bookmark>();
            this.Bookmarks.CollectionChanged += Bookmarks_CollectionChanged;

            this.progress = new Progress();
        }
Exemple #6
0
        void btn_list_Click(object sender, EventArgs e)
        {
            string RecievedData=null;
            names.Clear();
            ips.Clear();
            using (Client client = new Client())
            {
                Thread t = new Thread(() => RecievedData = client.Retrieve(Player.Name));
                t.Start();
                Progress p = new Progress();
                p.ShowDialog();
                string name = RecievedData.Substring(0, RecievedData.IndexOf('&'));
                string ip = RecievedData.Substring(RecievedData.IndexOf('&') + 1);

                for (int startindx = 0, length = name.IndexOf('*'), prv = length; startindx < name.Length; )
                {
                    names.Add(name.Substring(startindx, length));
                    startindx = prv + 1;
                    prv = name.IndexOf('*', startindx);
                    length = prv - startindx;

                }

                for (int startindx = 0, length = ip.IndexOf('*'), prv = length; prv != -1; )
                {
                    ips.Add(ip.Substring(startindx, length));
                    startindx = prv + 1;
                    prv = ip.IndexOf('*', startindx);
                    length = prv - startindx;

                }
                foreach (string s in names)
                    AvailablePlayers.Items.Add(s);
            }
        }
 public DownloadViewModel()
 {
     if (IsInDesignMode)
     {
         Progress = new Progress() { Saved = 50, Total = 100 };
     }
 }
Exemple #8
0
        protected override Image3D OnProcess(Image3D image, Progress progress)
        {
            if (cache == null)
            {
                if (!CombineFilesToSlices)
                {
                    using (var reader = new DicomReader(Path))
                    {
                        cache = reader.ReadImage3D(progress);
                        cache.Minimum = reader.MinValue;
                        cache.Maximum = reader.MaxValue;
                    }
                }
                else
                {
                    using (var reader = new FileToSliceDicomReader(Path))
                    {
                        cache = reader.ReadImage3D(progress);
                        cache.Minimum = reader.MinValue;
                        cache.Maximum = reader.MaxValue;
                    }
                }

                Log.I("Image loaded. min: " + cache.Minimum + "; max: " + cache.Maximum);
            }

            return cache;
        }
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // create a loader page
            Progress loader = new Progress();

            // set the visual root to loader page
            this.RootVisual = loader;

            // Debug helper -> make sure we have html params!
            if (e.InitParams.Count == 0)
            {
                MessageBox.Show("Error: You must tell your loader what files to load in your web page(init params) or manually in the code!", "Loader Error Message", MessageBoxButton.OK);
                //throw new Exception("Loader init params error");
                return;
            }
            // create package download manager and start the download process using html supplied InitParams
            // note the last param sets a 100KB max download speed for debuging and simulation mode!
            PackageDownloadManager pdm = new PackageDownloadManager(loader, e.InitParams, 0);

            // another option is to use a hand coded list ->
            //List<Uri> myDownloadList = new List<Uri>();
            //myDownloadList.Add(new Uri("ClientBin/Beegger.xap", UriKind.RelativeOrAbsolute));
            //ParamUtil.fixRelativeLinks(ref myDownloadList);
            //PackageDownloadManager pdm = new PackageDownloadManager(loader, myDownloadList, 50);
        }
Exemple #10
0
 /// <summary>
 /// Instantiates a <c>BuilderVisitor</c> object.
 /// </summary>
 /// <param name="filter">The list of filters to pass in.</param>
 /// <param name="typeConflicts">A list to keep track of invalid type conflicts.</param>
 /// <param name="progress">A progress object to keep track of the progress.</param>
 public BuilderVisitor(List<Filter> filter, List<string> typeConflicts, Progress progress)
 {
     _filter = filter;
     _filterChain = new FilterChain();
     _typeConflicts = typeConflicts;
     _progress = progress;
 }
Exemple #11
0
		public ContainerForm(CleanerController controller)
			: base(WorkshareFormUtility.DialogLevel.Primary, WorkshareFormUtility.BrandType.Protect, "Batch Clean")
		{
			InitializeComponent();
			TopMost = true;

			m_controller = controller;
			m_controller.CleanProcessComplete += OnCleanProcessComplete;
			m_controller.CleanProcessCancelled += OnCleanProcessCancelled;
			m_controller.ProcessComplete += OnProcessComplete;

			m_optionCtl = new Options(controller);
			m_progessCtl = new Progress(controller);
			m_reportCtl = new Report(controller);

			m_optionCtl.Visible = true;
			m_optionCtl.ShowSavingGroupBox(true);
			m_progessCtl.Visible = false;
			m_reportCtl.Visible = false;

			pnlDetail.Controls.Add(m_optionCtl);
			pnlDetail.Controls.Add(m_progessCtl);
			pnlDetail.Controls.Add(m_reportCtl);

			if (!m_optionCtl.HasValidFiles())
				btnClean_Click(this, new EventArgs());
		}
Exemple #12
0
        private void button_backup_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            DialogResult result = fbd.ShowDialog();
            if (result == DialogResult.OK)
            {
                int lastFoo = (int)Enum.GetValues(typeof(ECRComms.program)).Cast<ECRComms.program>().Last();

                for (int p = 0; p <= lastFoo; p++)
                {
                    Progress pr = new Progress(Program.ecr);
                    pr.Show();

                    string  name = ((ECRComms.program)p).ToString();
                    data = Program.ecr.getprogram((ECRComms.program)p);

                    pr.Close();

                    try
                    {
                        writedata(data.ToArray(),  Path.Combine(fbd.SelectedPath, name + ".dat"));
                    }
                    catch (Exception _Exception)
                    {
                        Console.WriteLine("Exception caught saving file{0}", _Exception.ToString());
                    }

                }
            }
        }
        internal Progress(int pluginNumber, Progress.Callback progress)
        {
            if (progress == null) throw new ArgumentNullException("progress");

            this.pluginNumber = pluginNumber;
            this.progress = progress;
        }
        static void WriteProgressIndicator(Progress? progress)
        {
            if (progress == null)
                return;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write("({0}) ", progress.Value);
        }
Exemple #15
0
        private Game()
        {
            m_graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            IsMouseVisible = true;

            m_progress = new Progress("fin");
        }
Exemple #16
0
        private Rectangle _rectangle; // mask bounds

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Create a GSImage backed with an existing Drawable.
        /// </summary>
        /// <param name="drawable"></param>
        public GSImage(Drawable drawable)
        {
            _image = drawable.Image;
            _drawable = drawable;
            _rectangle = _drawable.MaskBounds;
            Tile.CacheDefault(_drawable);
            Progress = new Progress("Halftone Laboratory");
        }
Exemple #17
0
 private static void WriteMessage(string message, Progress progress, MessageType type)
 {
     var c = Control;
     if (c!= null)
     {
         c.Write(message, progress, type);
     }
 }
Exemple #18
0
        public static BindingList<DataItem> Decode(string[] toDecode)
        {
            BatchInsert.toDecode = toDecode;

            Progress p = new Progress(0, 100, "Decoding..", "starting..", Decoding, null, null, true, true);
            p.StartWorker();

            return decodedDS;
        }
Exemple #19
0
 public UserAccount(string userName)
 {
     if (userName == null)
         throw new ArgumentNullException("userName");
     if (string.IsNullOrWhiteSpace(userName))
         throw new ArgumentException(Resources.UserAccount_Invalid_user_name, "userName");
     _userName = userName;
     _gameProgress = new Progress();
 }
 public ProgressWindow(Progress progress)
 {
     this.Progress = progress;
     this.Progress.ProgressChanged += s =>
     {
         this.OnPropertyChanged("Progress");
     };
     this.InitializeComponent();
 }
Exemple #21
0
 private void Button_Click_2(object sender, RoutedEventArgs e)
 {
     string value_id = this.taskIdField.Text;
     string value_name = this.userNameField.Text;
     Progress progress = new Progress();
     progress.TaskIDValue = value_id;
     progress.UserNameValue = value_name;
     progress.ShowDialog();
 }
    public void Function()
    {
        string strProjectpath =
            PathMap.SubstitutePath("$(PROJECTPATH)");
        string strProjectname = PathMap.SubstitutePath("$(PROJECTNAME)");
        string strFullProjectname = PathMap.SubstitutePath("$(P)");

        string strDate = DateTime.Now.ToString("yyyy-MM-dd");
        string strTime = DateTime.Now.ToString("hh-mm-ss");
        string strBackupDirectory = strProjectpath + @"\Backup\";
        string strBackupFilename = strProjectname + "_Backup_"
            + strDate + "_" + strTime;

        if (!System.IO.Directory.Exists(strBackupDirectory))
        {
            System.IO.Directory.CreateDirectory(strBackupDirectory);
        }

        Progress oProgress = new Progress("SimpleProgress");
        oProgress.SetAllowCancel(true);
        oProgress.SetAskOnCancel(true);
        oProgress.BeginPart(100, "");
        oProgress.SetTitle("Backup");
        oProgress.ShowImmediately();

        if (!oProgress.Canceled())
        {
            CommandLineInterpreter oCLI = new CommandLineInterpreter();
            ActionCallingContext acc = new ActionCallingContext();

            acc.AddParameter("BACKUPMEDIA", "DISK");
            acc.AddParameter("ARCHIVENAME", strBackupFilename);
            acc.AddParameter("BACKUPMETHOD", "BACKUP");
            acc.AddParameter("COMPRESSPRJ", "1");
            acc.AddParameter("INCLEXTDOCS", "1");
            acc.AddParameter("BACKUPAMOUNT", "BACKUPAMOUNT_ALL");
            acc.AddParameter("INCLIMAGES", "1");
            acc.AddParameter("LogMsgActionDone", "true");
            acc.AddParameter("DESTINATIONPATH", strBackupDirectory);
            acc.AddParameter("PROJECTNAME", strFullProjectname);
            acc.AddParameter("TYPE", "PROJECT");

            oCLI.Execute("backup", acc);
        }

        oProgress.EndPart(true);

        MessageBox.Show(
            "Backup wurde erfolgreich erstellt:\n"
            + strBackupFilename,
            "Hinweis",
            MessageBoxButtons.OK,
            MessageBoxIcon.Information
            );

        return;
    }
Exemple #23
0
        public ProgressWorker(Progress window, int total)
        {
            this.total = total;
            this.window = window;
            this.WorkerReportsProgress = true;
            this.WorkerSupportsCancellation = true;

            ReportProgress(0);
        }
 public async Task<TempPackage> FetchAsync(Package pkg, Progress progress)
 {
     var result = new TempPackage
     {
         FileName = Path.GetFileName(pkg.Location.LocalPath),
         Package = pkg,
         WorkDirectory = new NonTempItem(pkg.Location.LocalPath)
     };
     return await Task.FromResult(result);
 }
 public ProgressWindow BeginPopupProgressWindow(Progress progress)
 {
     ProgressWindow progressWindow = null;
     this.Dispatcher.InvokeAsync(() =>
     {
         progressWindow = new ProgressWindow(null, progress);
         progressWindow.Show();
     });
     return progressWindow;
 }
Exemple #26
0
        public static Progress StartProgress(string completionMessage)
        {
            if (currentProgess != null)
                throw new InvalidOperationException("The maximum number of concurent progresses has been reached.");

            currentProgess = new Progress(completionMessage);
            currentProgess.Disposed += CurrentProgess_Disposed;
            display.StartProgress(currentProgess);
            return currentProgess;
        }
    public void Function()
    {
        string strProjectpath =
            PathMap.SubstitutePath("$(PROJECTPATH)" + @"\");

        Progress progress = new Progress("SimpleProgress");
        progress.BeginPart(100, "");
        progress.SetAllowCancel(true);
        if (!progress.Canceled())
        {
            progress.BeginPart(50,
                "Artikelsummenstückliste wird erstellt...");
            ActionCallingContext labellingContext =
                new ActionCallingContext();
            labellingContext.AddParameter("CONFIGSCHEME",
                "Summarized parts list");
            labellingContext.AddParameter("DESTINATIONFILE",
                strProjectpath + "Artikelsummenstückliste.xls");
            labellingContext.AddParameter("FILTERSCHEME", "");
            labellingContext.AddParameter("LANGUAGE", "de_DE");
            labellingContext.AddParameter("LogMsgActionDone", "true");
            labellingContext.AddParameter("SHOWOUTPUT", "1");
            labellingContext.AddParameter("RECREPEAT", "1");
            labellingContext.AddParameter("SORTSCHEME", "");
            labellingContext.AddParameter("TASKREPEAT", "1");
            new CommandLineInterpreter().Execute("label",
                labellingContext);
            progress.EndPart();
        }
        if (!progress.Canceled())
        {
            progress.BeginPart(50,
                "Betriebsmittelbeschriftung wird erstellt...");
            ActionCallingContext labellingContext1 =
                new ActionCallingContext();
            labellingContext1.AddParameter("CONFIGSCHEME",
                "Device tag list");
            labellingContext1.AddParameter("DESTINATIONFILE",
                strProjectpath + "Betriebsmittelbeschriftung.xls");
            labellingContext1.AddParameter("FILTERSCHEME", "");
            labellingContext1.AddParameter("LANGUAGE", "de_DE");
            labellingContext1.AddParameter("LogMsgActionDone", "true");
            labellingContext1.AddParameter("SHOWOUTPUT", "1");
            labellingContext1.AddParameter("RECREPEAT", "1");
            labellingContext1.AddParameter("SORTSCHEME", "");
            labellingContext1.AddParameter("TASKREPEAT", "1");
            new CommandLineInterpreter().Execute("label",
                labellingContext1);
            progress.EndPart();
        }

        progress.EndPart(true);

        return;
    }
Exemple #28
0
 /// <summary>
 /// Create a GSImage backed with a new %Gimp# Image.
 /// </summary>
 /// <param name="width"></param>
 /// <param name="height"></param>
 public GSImage(int width, int height)
 {
     _image = new Gimp.Image(width, height, ImageBaseType.Gray);
     Layer layer = new Layer(_image, "default", width, height,
         ImageType.Gray, 100, LayerModeEffects.Normal);
     _image.AddLayer(layer, 0);
     _drawable = _image.ActiveDrawable;
     _rectangle = _drawable.MaskBounds;
     Tile.CacheDefault(_drawable);
     Progress = new Progress("Halftone Laboratory");
 }
Exemple #29
0
    float totalDistance; // of progress bar

    #endregion Fields

    #region Methods

    void InitializeReferences()
    {
        if (startPoint == null)
            startPoint = GameObject.Find(GameObjectIDS.PROGRESS_HUD_START).transform;
        if (endPoint == null)
            endPoint = GameObject.Find(GameObjectIDS.PROGRESS_HUD_END).transform;
        if (playerIcon == null)
            playerIcon = GameObject.Find (GameObjectIDS.PROGRESS_PLAYER_ICON).transform;
        if (progressScript == null)
            progressScript = GameObject.Find(GameObjectIDS.PROGRESS_MANAGER).GetComponent<Progress>();
    }
Exemple #30
0
        protected override Image3D OnProcess(Image3D image, Progress progress)
        {
            OnValidate(image);
            Size size = OnDetermineDisplaySize(image);
            int w = (int)Math.Round(size.Width);
            int h = (int)Math.Round(size.Height);

            displayImage = Display.GetDisplay(w, h);
            var result = base.OnProcess(image, progress);
            return result;
        }
 public async Task DownloadFileAsync(Progress <int> progress)
 {
     await FileManager.DownloadAudioFileOfSoundAsync(Uuid, progress);
 }
Exemple #32
0
        private async void ExecuteButton_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("Renaming cannot be undone. Proceed?", "Attention!", MessageBoxButton.OKCancel, MessageBoxImage.Warning);

            if (result == MessageBoxResult.OK)
            {
                LogsTabItem.Focus();
                var targetFolder   = _renamer.TargetFolder;
                var progressWindow = new ProgressWindow();
                progressWindow.Topmost = true;
                progressWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                progressWindow.Owner = this;

                var progressReport = new Progress <RenamerProgress>(p =>
                {
                    progressWindow.ProgressTextBlock.Text   = p.Message;
                    progressWindow.RenamerProgressBar.Value = p.Percentage * 100d;

                    if (p.Logger != null)
                    {
                        if (p.IsError)
                        {
                            p.Logger.WriteWarning(p.Message);
                        }
                        else
                        {
                            p.Logger.WriteInfo(p.Message);
                        }
                    }
                });
                progressWindow.Show();
                IsEnabled = false;

                try
                {
                    await Task.Run(() => _renamer.DoRename(progressReport));

                    progressWindow.Hide();

                    if (_renamer.Completed)
                    {
                        if (MessageBox.Show("Renaming complete! Do you want to clean the bin and obj folders?", "Success", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            CleanBinObjFolders();
                        }

                        MessageBox.Show("Renaming complete! A log file will be created on the file system.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        MessageBox.Show("Problems were encountered. See the log tab for more information.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    IsEnabled = true;
                    progressWindow.Close();
                    ExecuteButton.IsEnabled = _renamer.Ready;

                    // TODO: this should go into the filesystem class intead.
                    File.WriteAllText(Path.Combine(Path.GetDirectoryName(targetFolder), "RenamerLog.txt"), LogsTextBox.Text);
                }

                LogsTextBox.ScrollToLine(LogsTextBox.LineCount - 1);
            }
        }
Exemple #33
0
 public static void OnProcess(int v)
 {
     Progress?.Invoke(v);
 }
Exemple #34
0
 /// <summary>
 /// Unfreezes the mod.
 /// </summary>
 public static void Unfreeze(ManagedMods mods, int index, Action <Progress> ProgressChanged = null)
 {
     ModActions.Unfreeze(mods[index]);
     mods.Save();
     ProgressChanged?.Invoke(Progress.Done("Mod thawed."));
 }
 public pgeThreadingTaskProgress()
 {
     InitializeComponent();
     progressCom = new Progress <int>(refreshProgressBar);
 }
        public static IRavenAzureClient Create(AzureSettings settings, BackupConfiguration configuration, Progress progress = null, CancellationToken cancellationToken = default)
        {
            if (configuration.AzureLegacy)
            {
                return(new LegacyRavenAzureClient(settings, progress, cancellationToken: cancellationToken));
            }

            return(new RavenAzureClient(settings, configuration, progress, cancellationToken));
        }
Exemple #37
0
        public override IEnumerable <string> Process()
        {
            Dictionary <string, List <GtfItem> > map = new Dictionary <string, List <GtfItem> >();

            var namemap = new Dictionary <string, string>();

            if (File.Exists(options.MapFile))
            {
                namemap = new MapReader(0, 1, hasHeader: false).ReadFromFile(options.MapFile);
            }

            using (var gtf = new GtfItemFile(options.InputFile))
            {
                GtfItem item;
                int     count = 0;
                while ((item = gtf.Next()) != null)
                {
                    count++;
                    if ((count % 100000) == 0)
                    {
                        Progress.SetMessage("{0} gtf item processed", count);
                    }
                    List <GtfItem> oldItems;

                    var id = string.IsNullOrEmpty(options.Key) ? item.GeneId : item.GetAttribute(options.Key);

                    if (!map.TryGetValue(id, out oldItems))
                    {
                        map[id] = new[] { item }.ToList();
                    }
                    else
                    {
                        if (IsExon(item))
                        {
                            oldItems.RemoveAll(m => !IsExon(m));
                            oldItems.Add(item);
                        }
                        else
                        {
                            if (oldItems.All(m => !IsExon(m)))
                            {
                                oldItems.Add(item);
                            }
                        }
                    }
                }
            }

            //      map[item.GeneId] = item.Attributes.StringAfter("gene_name \"").StringBefore("\"");
            var keys = (from key in map.Keys
                        orderby key
                        select key).ToList();

            using (StreamWriter sw = new StreamWriter(options.OutputFile))
                using (StreamWriter swBed = new StreamWriter(options.OutputFile + ".bed"))
                {
                    bool bHasGeneName = map.Values.Any(l => l.Any(m => m.Attributes.Contains("gene_name")));
                    if (!bHasGeneName && !File.Exists(options.MapFile))
                    {
                        throw new Exception(string.Format("No gene_name found in {0} and no id/name map file defined.", options.InputFile));
                    }

                    sw.Write("gene_id\tgene_name\tlength\tchr\tstart\tend");
                    bool bHasGeneBiotype = map.Values.Any(l => l.Any(m => m.Attributes.Contains("gene_biotype")));
                    bool bHasGeneType    = map.Values.Any(l => l.Any(m => m.Attributes.Contains("gene_type")));
                    if (bHasGeneBiotype || bHasGeneType)
                    {
                        sw.Write("\tgene_biotype");
                    }
                    sw.WriteLine();

                    foreach (var key in keys)
                    {
                        var    gtfs = map[key];
                        string name;
                        var    gtf = gtfs.FirstOrDefault(m => m.Attributes.Contains("gene_name"));
                        gtfs.CombineCoordinates();
                        string biotype;
                        if (gtf == null)
                        {
                            biotype = string.Empty;
                            if (!namemap.TryGetValue(key, out name))
                            {
                                name = key;
                            }
                        }
                        else
                        {
                            biotype = gtf.GetBiotype();
                            name    = gtf.Attributes.StringAfter("gene_name \"").StringBefore("\"");
                        }

                        sw.Write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", key, name, gtfs.Sum(m => m.Length), gtfs.First().Seqname, gtfs.Min(l => l.Start), gtfs.Max(l => l.End));
                        if (bHasGeneBiotype || bHasGeneType)
                        {
                            sw.Write("\t{0}", biotype);
                        }
                        sw.WriteLine();
                        swBed.WriteLine("{0}\t{1}\t{2}\t{3}_{4}", gtfs.First().Seqname, gtfs.Min(l => l.Start), gtfs.Max(l => l.End), key.StringBefore("."), name);
                    }
                }

            return(new string[] { options.OutputFile });
        }
Exemple #38
0
        private ProgressThrottler <DownloadProgress> SetupThrottledQueueListProgress(QueueListItem queueListItem)
        {
            var progressHandler = new Progress <DownloadProgress>(value => queueListItem.Progress = value.Progress);

            return(new ProgressThrottler <DownloadProgress>(progressHandler, _shellService.Settings.ProgressUpdateInterval));
        }
        private RavenAzureClient(AzureSettings azureSettings, BackupConfiguration configuration, Progress progress = null, CancellationToken cancellationToken = default)
        {
            if (azureSettings == null)
            {
                throw new ArgumentNullException(nameof(azureSettings));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var hasAccountKey = string.IsNullOrWhiteSpace(azureSettings.AccountKey) == false;
            var hasSasToken   = string.IsNullOrWhiteSpace(azureSettings.SasToken) == false;

            if (hasAccountKey == false && hasSasToken == false)
            {
                throw new ArgumentException($"{nameof(AzureSettings.AccountKey)} and {nameof(AzureSettings.SasToken)} cannot be both null or empty");
            }

            if (hasAccountKey && hasSasToken)
            {
                throw new ArgumentException($"{nameof(AzureSettings.AccountKey)} and {nameof(AzureSettings.SasToken)} cannot be used simultaneously");
            }

            if (string.IsNullOrWhiteSpace(azureSettings.AccountName))
            {
                throw new ArgumentException($"{nameof(AzureSettings.AccountName)} cannot be null or empty");
            }

            if (string.IsNullOrWhiteSpace(azureSettings.StorageContainer))
            {
                throw new ArgumentException($"{nameof(AzureSettings.StorageContainer)} cannot be null or empty");
            }

            var serverUrlForContainer = new Uri($"https://{azureSettings.AccountName}.blob.core.windows.net/{azureSettings.StorageContainer.ToLower()}", UriKind.Absolute);

            var options = new BlobClientOptions
            {
                Retry =
                {
                    NetworkTimeout = configuration.CloudStorageOperationTimeout.AsTimeSpan
                }
            };

            if (hasAccountKey)
            {
                _client = new BlobContainerClient(serverUrlForContainer, new StorageSharedKeyCredential(azureSettings.AccountName, azureSettings.AccountKey), options);
            }

            if (hasSasToken)
            {
                VerifySasToken(azureSettings.SasToken);
                _client = new BlobContainerClient(serverUrlForContainer, new AzureSasCredential(azureSettings.SasToken), options);
            }

            _progress          = progress;
            _cancellationToken = cancellationToken;
            _storageContainer  = azureSettings.StorageContainer;
            RemoteFolderName   = azureSettings.RemoteFolderName;
        }
Exemple #40
0
        void ReplicationProgress(object replication, ReplicationChangeEventArgs args)
        {
            var active = args.Source;

            Debug.WriteLine(String.Format("Push: {0}, Pull: {1}", push.Status, pull.Status));

            int lastTotal = 0;

            if (_leader == null)
            {
                if (active.IsPull && (pull.Status == ReplicationStatus.Active && push.Status != ReplicationStatus.Active))
                {
                    _leader = pull;
                }
                else if (!active.IsPull && (push.Status == ReplicationStatus.Active && pull.Status != ReplicationStatus.Active))
                {
                    _leader = push;
                }
                else
                {
                    _leader = null;
                }
            }
            if (active == pull)
            {
                lastTotal = _lastPullCompleted;
            }
            else
            {
                lastTotal = _lastPushCompleted;
            }

            Debug.WriteLine(String.Format("Sync: {2} Progress: {0}/{1};", active.CompletedChangesCount - lastTotal, active.ChangesCount - lastTotal, active == push ? "Push" : "Pull"));

            var progress = (float)(active.CompletedChangesCount - lastTotal) / (float)(Math.Max(active.ChangesCount - lastTotal, 1));

            if (AppDelegate.CurrentSystemVersion < AppDelegate.iOS7)
            {
                ShowSyncStatusLegacy();
            }
            else
            {
                ShowSyncStatus();
            }

            Debug.WriteLine(String.Format("({0:F})", progress));

            if (active == pull)
            {
                if (AppDelegate.CurrentSystemVersion >= AppDelegate.iOS7)
                {
                    Progress.TintColor = UIColor.White;
                }
            }
            else
            {
                if (AppDelegate.CurrentSystemVersion >= AppDelegate.iOS7)
                {
                    Progress.TintColor = UIColor.LightGray;
                }
            }

            Progress.Hidden = false;

            if (progress < Progress.Progress)
            {
                Progress.SetProgress(progress, false);
            }
            else
            {
                Progress.SetProgress(progress, false);
            }

            if (!(pull.Status != ReplicationStatus.Active && push.Status != ReplicationStatus.Active))
            {
                if (progress < 1f)
                {
                    return;
                }
            }
            if (active == null)
            {
                return;
            }
            var initiatorName = active.IsPull ? "Pull" : "Push";

            _lastPushCompleted = push.ChangesCount;
            _lastPullCompleted = pull.ChangesCount;

            if (Progress == null)
            {
                return;
            }
            Progress.Hidden = false;
            Progress.SetProgress(1f, false);

            var t = new System.Timers.Timer(300);

            t.Elapsed += (sender, e) => {
                InvokeOnMainThread(() => {
                    t.Dispose();
                    Progress.Hidden = true;
                    Progress.SetProgress(0f, false);
                    Debug.WriteLine(String.Format("{0} Sync Session Finished.", initiatorName));
                    ShowSyncButton();
                });
            };
            t.Start();
        }
Exemple #41
0
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                BulkService = new BulkServiceManager(authorizationData);

                var progress = new Progress <BulkOperationProgressInfo>(x =>
                                                                        OutputStatusMessage(String.Format("{0} % Complete",
                                                                                                          x.PercentComplete.ToString(CultureInfo.InvariantCulture))));

                #region Add

                const int targetIdKey   = -1;
                const int campaignIdKey = -123;

                // Prepare the bulk entities that you want to upload. Each bulk entity contains the corresponding campaign management object,
                // and additional elements needed to read from and write to a bulk file.

                var bulkCampaign = new BulkCampaign
                {
                    // ClientId may be used to associate records in the bulk upload file with records in the results file. The value of this field
                    // is not used or stored by the server; it is simply copied from the uploaded record to the corresponding result record.
                    // Note: This bulk file Client Id is not related to an application Client Id for OAuth.
                    ClientId = "YourClientIdGoesHere",
                    Campaign = new Campaign
                    {
                        // When using the Campaign Management service, the Id cannot be set. In the context of a BulkCampaign, the Id is optional
                        // and may be used as a negative reference key during bulk upload. For example the same negative value set for the campaign Id
                        // will be used when associating this new campaign with a new call ad extension in the BulkCampaignCallAdExtension object below.
                        Id             = campaignIdKey,
                        Name           = "Women's Shoes " + DateTime.UtcNow,
                        Description    = "Red shoes line.",
                        BudgetType     = BudgetLimitType.MonthlyBudgetSpendUntilDepleted,
                        MonthlyBudget  = 1000.00,
                        TimeZone       = "PacificTimeUSCanadaTijuana",
                        DaylightSaving = true
                    }
                };

                // Prepare targets for upload

                var bulkCampaignDayTimeTarget = new BulkCampaignDayTimeTarget
                {
                    CampaignId    = campaignIdKey,
                    TargetId      = targetIdKey,
                    DayTimeTarget = new DayTimeTarget
                    {
                        Bids = new List <DayTimeTargetBid>
                        {
                            new DayTimeTargetBid
                            {
                                BidAdjustment = 10,
                                Day           = Day.Friday,
                                FromHour      = 11,
                                FromMinute    = Minute.Zero,
                                ToHour        = 13,
                                ToMinute      = Minute.Fifteen
                            },
                            new DayTimeTargetBid
                            {
                                BidAdjustment = 20,
                                Day           = Day.Saturday,
                                FromHour      = 11,
                                FromMinute    = Minute.Zero,
                                ToHour        = 13,
                                ToMinute      = Minute.Fifteen
                            }
                        }
                    }
                };

                var bulkCampaignLocationTarget = new BulkCampaignLocationTarget
                {
                    CampaignId = campaignIdKey,
                    TargetId   = targetIdKey,

                    IntentOption = IntentOption.PeopleIn,
                    CityTarget   = new CityTarget
                    {
                        Bids = new List <CityTargetBid>
                        {
                            new CityTargetBid
                            {
                                BidAdjustment = 15,
                                City          = "Toronto, Toronto ON CA",
                                IsExcluded    = false
                            }
                        }
                    },
                    CountryTarget = new CountryTarget
                    {
                        Bids = new List <CountryTargetBid>
                        {
                            new CountryTargetBid
                            {
                                BidAdjustment    = 15,
                                CountryAndRegion = "CA",
                                IsExcluded       = false
                            }
                        }
                    },
                    MetroAreaTarget = new MetroAreaTarget
                    {
                        Bids = new List <MetroAreaTargetBid>
                        {
                            new MetroAreaTargetBid
                            {
                                BidAdjustment = 15,
                                MetroArea     = "Seattle-Tacoma, WA, WA US",
                                IsExcluded    = false
                            }
                        }
                    },
                    StateTarget = new StateTarget
                    {
                        Bids = new List <StateTargetBid>
                        {
                            new StateTargetBid
                            {
                                BidAdjustment = 15,
                                State         = "US-WA",
                                IsExcluded    = false
                            }
                        }
                    },
                    PostalCodeTarget = new PostalCodeTarget
                    {
                        Bids = new List <PostalCodeTargetBid>
                        {
                            new PostalCodeTargetBid
                            {
                                // Bid adjustments are not allowed for location exclusions.
                                // If IsExcluded is true, this element will be ignored.
                                BidAdjustment = 10,
                                PostalCode    = "98052, WA US",
                                IsExcluded    = false
                            }
                        }
                    }
                };

                var bulkCampaignRadiusTarget = new BulkCampaignRadiusTarget
                {
                    CampaignId = campaignIdKey,
                    TargetId   = targetIdKey,

                    RadiusTarget = new RadiusTarget2
                    {
                        Bids = new List <RadiusTargetBid2>
                        {
                            new RadiusTargetBid2
                            {
                                BidAdjustment    = 50,
                                LatitudeDegrees  = 47.755367,
                                LongitudeDegrees = -122.091827,
                                Radius           = 11,
                                RadiusUnit       = DistanceUnit.Kilometers
                            }
                        }
                    }
                };


                // Write the entities created above, to the specified file.
                // Dependent entities such as BulkCampaignLocationTarget must be written after any dependencies,
                // for example a BulkCampaign.

                Writer = new BulkFileWriter(FileDirectory + UploadFileName);

                Writer.WriteEntity(bulkCampaign);

                Writer.WriteEntity(bulkCampaignDayTimeTarget);
                Writer.WriteEntity(bulkCampaignLocationTarget);
                Writer.WriteEntity(bulkCampaignRadiusTarget);

                Writer.Dispose();

                var fileUploadParameters = new FileUploadParameters
                {
                    ResultFileDirectory = FileDirectory,
                    ResultFileName      = ResultFileName,
                    OverwriteResultFile = true,
                    UploadFilePath      = FileDirectory + UploadFileName,
                    ResponseMode        = ResponseMode.ErrorsAndResults
                };

                // UploadFileAsync will upload the file you finished writing and will download the results file

                OutputStatusMessage("Starting UploadFileAsync . . .\n");
                var bulkFilePath =
                    await BulkService.UploadFileAsync(fileUploadParameters, progress, CancellationToken.None);

                Reader = new BulkFileReader(bulkFilePath, ResultFileType.Upload, FileType);
                OutputStatusMessage("Upload Results Bulk File Path" + Reader.BulkFilePath + "\n");
                OutputStatusMessage("Added Entities\n");

                // Write the upload output

                var bulkEntities = Reader.ReadEntities().ToList();

                var campaignResults = bulkEntities.OfType <BulkCampaign>().ToList();
                OutputBulkCampaigns(campaignResults);

                var campaignDayTimeTargetResults = bulkEntities.OfType <BulkCampaignDayTimeTarget>().ToList();
                OutputBulkCampaignDayTimeTargets(campaignDayTimeTargetResults);

                var campaignLocationTargetResults = bulkEntities.OfType <BulkCampaignLocationTarget>().ToList();
                OutputBulkCampaignLocationTargets(campaignLocationTargetResults);

                var campaignRadiusTargetResults = bulkEntities.OfType <BulkCampaignRadiusTarget>().ToList();
                OutputBulkCampaignRadiusTargets(campaignRadiusTargetResults);

                Reader.Dispose();

                #endregion Add

                #region Update

                // Update the day and time target.
                // Do not create a BulkAdGroupDayTimeTarget for update, unless you want to replace all existing DayTime target bids
                // with the specified day and time target set for the current bulk upload.
                // Instead you should upload one or more bids as a list of BulkCampaignDayTimeTargetBid.

                var bulkCampaignDayTimeTargetBids = new List <BulkCampaignDayTimeTargetBid>
                {
                    new BulkCampaignDayTimeTargetBid
                    {
                        CampaignId       = campaignDayTimeTargetResults[0].CampaignId,
                        TargetId         = targetIdKey,
                        DayTimeTargetBid = new DayTimeTargetBid
                        {
                            BidAdjustment = 15,
                            Day           = Day.Friday,
                            FromHour      = 11,
                            FromMinute    = Minute.Zero,
                            ToHour        = 13,
                            ToMinute      = Minute.Fifteen
                        }
                    }
                };

                // Write the updated target to the file

                Writer = new BulkFileWriter(FileDirectory + UploadFileName);

                foreach (var bulkCampaignDayTimeTargetBid in bulkCampaignDayTimeTargetBids)
                {
                    Writer.WriteEntity(bulkCampaignDayTimeTargetBid);
                }

                Writer.Dispose();

                fileUploadParameters = new FileUploadParameters
                {
                    ResultFileDirectory = FileDirectory,
                    ResultFileName      = ResultFileName,
                    OverwriteResultFile = true,
                    UploadFilePath      = FileDirectory + UploadFileName,
                    ResponseMode        = ResponseMode.ErrorsAndResults
                };

                // UploadFileAsync will upload the file you finished writing and will download the results file

                OutputStatusMessage("Starting UploadFileAsync . . .\n");
                bulkFilePath = await BulkService.UploadFileAsync(fileUploadParameters, progress, CancellationToken.None);

                Reader = new BulkFileReader(bulkFilePath, ResultFileType.Upload, FileType);
                OutputStatusMessage("Upload Results Bulk File Path: " + Reader.BulkFilePath + "\n");
                OutputStatusMessage("Updated Entities\n");


                // Write any upload errors

                var campaignDayTimeTargetBidResults =
                    Reader.ReadEntities().OfType <BulkCampaignDayTimeTargetBid>().ToList();
                OutputBulkCampaignDayTimeTargetBids(campaignDayTimeTargetBidResults);

                Reader.Dispose();

                #endregion Update

                #region Delete

                // Prepare the bulk entities that you want to delete. You must set the Id field to the corresponding
                // entity identifier, and the Status field to Deleted.

                var campaignId = campaignResults[0].Campaign.Id;
                bulkCampaign = new BulkCampaign
                {
                    Campaign = new Campaign
                    {
                        Id     = campaignId,
                        Status = CampaignStatus.Deleted
                    }
                };

                var targetId = campaignDayTimeTargetResults[0].TargetId;

                bulkCampaignDayTimeTarget = new BulkCampaignDayTimeTarget
                {
                    Status     = Status.Deleted,
                    CampaignId = campaignId,
                    TargetId   = targetId
                };

                bulkCampaignLocationTarget = new BulkCampaignLocationTarget
                {
                    Status     = Status.Deleted,
                    CampaignId = campaignId,
                    TargetId   = targetId
                };

                bulkCampaignRadiusTarget = new BulkCampaignRadiusTarget
                {
                    Status     = Status.Deleted,
                    CampaignId = campaignId,
                    TargetId   = targetId
                };


                // Write the entities that you want deleted, to the specified file.

                Writer = new BulkFileWriter(FileDirectory + UploadFileName);

                Writer.WriteEntity(bulkCampaign);

                Writer.WriteEntity(bulkCampaignDayTimeTarget);
                Writer.WriteEntity(bulkCampaignLocationTarget);
                Writer.WriteEntity(bulkCampaignRadiusTarget);

                Writer.Dispose();

                fileUploadParameters = new FileUploadParameters
                {
                    ResultFileDirectory = FileDirectory,
                    ResultFileName      = ResultFileName,
                    OverwriteResultFile = true,
                    UploadFilePath      = FileDirectory + UploadFileName,
                    ResponseMode        = ResponseMode.ErrorsAndResults
                };

                // UploadFileAsync will upload the file you finished writing and will download the results file

                OutputStatusMessage("Starting UploadFileAsync . . .\n");
                bulkFilePath = await BulkService.UploadFileAsync(fileUploadParameters, progress, CancellationToken.None);

                Reader = new BulkFileReader(bulkFilePath, ResultFileType.Upload, FileType);
                OutputStatusMessage("Upload Results Bulk File Path" + Reader.BulkFilePath + "\n");
                OutputStatusMessage("Deleted Entities\n");

                // Write the upload output

                bulkEntities = Reader.ReadEntities().ToList();

                campaignResults = bulkEntities.OfType <BulkCampaign>().ToList();
                OutputBulkCampaigns(campaignResults);

                campaignDayTimeTargetResults = bulkEntities.OfType <BulkCampaignDayTimeTarget>().ToList();
                OutputBulkCampaignDayTimeTargets(campaignDayTimeTargetResults);

                campaignLocationTargetResults = bulkEntities.OfType <BulkCampaignLocationTarget>().ToList();
                OutputBulkCampaignLocationTargets(campaignLocationTargetResults);

                campaignRadiusTargetResults = bulkEntities.OfType <BulkCampaignRadiusTarget>().ToList();
                OutputBulkCampaignRadiusTargets(campaignRadiusTargetResults);

                Reader.Dispose();

                #endregion Delete
            }
            // Catch Microsoft Account authorization exceptions.
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Bulk service exceptions
            catch (FaultException <Microsoft.BingAds.Bulk.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.Bulk.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (BulkOperationInProgressException ex)
            {
                OutputStatusMessage("The result file for the bulk operation is not yet available for download.");
                OutputStatusMessage(ex.Message);
            }
            catch (BulkOperationCouldNotBeCompletedException <DownloadStatus> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (BulkOperationCouldNotBeCompletedException <UploadStatus> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
            finally
            {
                if (Reader != null)
                {
                    Reader.Dispose();
                }
                if (Writer != null)
                {
                    Writer.Dispose();
                }
            }
        }
Exemple #42
0
        private async void cmdUpload_Click(object sender, EventArgs e)
        {
            txtStatus.Text    = string.Empty;
            cmdUpload.Enabled = false;

            USER_NAME      = txtUserName.Text;
            SECRET_KEY     = txtSecretKey.Text;
            BUCKET_NAME    = txtBucketName.Text;
            PICS_TO_UPLOAD = Convert.ToInt16(cmbPictureCount.Text);
            PICS_UPLOADED  = 0;

            List <Picture> picturesToUpload = new List <Picture>();

            DateTime startDate = DateTime.Now;

            CancellationTokenSource cts = new CancellationTokenSource();

            // Uri
            string host    = string.Empty;
            string scheme  = string.Empty;
            string port    = string.Empty;
            bool   useHttp = true;

            if (USER_NAME.Length == 0 || SECRET_KEY.Length == 0 || BUCKET_NAME.Length == 0 || PICS_TO_UPLOAD == 0 || txtIpAddress.Text.Length == 0)
            {
                updateStatus("Please provide an endpoint ip, user name, secret key, bucket name and number of pictures to upload.");
                cmdUpload.Enabled = true;
                return;
            }

            try {
                port = cmbPort.Text;
                host = txtIpAddress.Text;

                if (port == "9020")
                {
                    scheme = "http://";
                }
                else
                {
                    scheme  = "https://";
                    useHttp = true;
                }

                ENDPOINT_URL = string.Format("{0}{1}:{2}", scheme, host, port);

                //bool isValid = System.Net.IPAddress.TryParse(txtIpAddress.Text, out ip);
                //if (isValid)
                //{
                //    temp = string.Format("{0}{1}:{2}", scheme, ip, port);
                //}
                //else
                //{
                //    updateStatus("Please provide a valid IP address.");
                //    cmdUpload.Enabled = true;
                //    return;
                //}

                //ENDPOINT_URL = new Uri(temp);
            }
            catch (Exception ex)
            {
                updateStatus(ex.Message);
                cmdUpload.Enabled = true;
                return;
            }

            var progress = new Progress <UploadProgress>(update =>
            {
                if (update.cancelLoop)
                {
                    cts.Cancel();
                }

                if (update.errorMessage != null)
                {
                    updateStatus(update.errorMessage);
                }
                else
                {
                    double percentage = (double)PICS_UPLOADED / PICS_TO_UPLOAD;
                    updateStatus(string.Format("{0} of {1} uploaded - size {2}b - progress: {3}", Convert.ToString(PICS_UPLOADED), Convert.ToString(PICS_TO_UPLOAD), update.imageSize, percentage.ToString("0%")));
                }
            });

            updateStatus("Checking that specified bucket exists.");

            bool result = false;

            await Task.Run(() =>
            {
                IProgress <UploadProgress> report = progress;

                try
                {
                    BasicAWSCredentials creds = new BasicAWSCredentials(USER_NAME, SECRET_KEY);

                    AmazonS3Config cc = new AmazonS3Config()
                    {
                        ServiceURL     = ENDPOINT_URL,
                        ForcePathStyle = true,
                        UseHttp        = useHttp,
                        Timeout        = TimeSpan.FromSeconds(5),
                        MaxErrorRetry  = 0
                    };

                    AmazonS3Client client = new AmazonS3Client(creds, cc);
                    ListBucketsRequest listBucketsRequest   = new ListBucketsRequest();
                    ListBucketsResponse listBucketsResponse = client.ListBuckets(listBucketsRequest);

                    foreach (var bucket in listBucketsResponse.Buckets)
                    {
                        if (bucket.BucketName == BUCKET_NAME)
                        {
                            result = true;
                        }
                    }

                    if (!result)
                    {
                        report.Report(new UploadProgress {
                            errorMessage = "Unable to locate specified bucket.  Did you provide the correct bucket name?"
                        });
                    }
                }
                catch (AmazonS3Exception amazonS3Exception)
                {
                    report.Report(new UploadProgress {
                        errorMessage = string.Format("An error occured while communicating with ECS.  Error: {0}", amazonS3Exception.Message)
                    });
                }
                catch (Exception ex)
                {
                    report.Report(new UploadProgress {
                        errorMessage = "An error occured while attempting to access specified bucket.  Please check all provided parameters."
                    });
                }
            });

            if (!result)
            {
                cmdUpload.Enabled = true;
                return;
            }

            updateStatus(string.Format("Successfully verified that bucket '{0}' exists.", BUCKET_NAME));

            var engine  = new FileHelperEngine <Pictures>();
            var records = engine.ReadFile(ConfigurationManager.AppSettings["CSV_FILE_LOCATION"]);

            int recordsIndex = 0;

            foreach (var record in records)
            {
                recordsIndex++;

                int    height    = record.height;
                int    width     = record.width;
                double longitude = record.longitude;
                double latitude  = record.latitude;
                int    viewCount = record.viewCount;
                string fileName  = record.fileName;
                string filePath  = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["IMAGE_FOLDER_LOCATION"], fileName);
                string thumbPath = string.Format("{0}\\thumbnails\\{1}", ConfigurationManager.AppSettings["IMAGE_FOLDER_LOCATION"], fileName);

                picturesToUpload.Add(new Picture(recordsIndex, height, width, fileName, filePath, thumbPath, longitude, latitude, viewCount, this));

                if (!(recordsIndex < PICS_TO_UPLOAD))
                {
                    break;
                }
            }

            await Task.Run(() => {
                ParallelOptions po   = new ParallelOptions();
                po.CancellationToken = cts.Token;

                try
                {
                    Parallel.ForEach(picturesToUpload, po, (image) =>
                    {
                        try
                        {
                            image.uploadTheImage(progress);
                        }
                        finally
                        {
                            Interlocked.Increment(ref PICS_UPLOADED);
                        }
                    });
                } catch (OperationCanceledException ex)
                {
                }
            });

            if (!cts.IsCancellationRequested)
            {
                DateTime endDate = DateTime.Now;
                updateStatus(string.Format("Done:  Process took: {0} seconds.", (endDate - startDate).TotalSeconds.ToString()));
            }

            cmdUpload.Enabled = true;
        }
        public async Task Acquire(Acquirable acquirable)
        {
            var result = await acquirable.Fetch(_httpClient);

            if (!result.IsSuccess)
            {
                return;
            }

            if (await CheckSdkExists(result.Version))
            {
                _textWriter.WriteLine($"SDK version {result.Version} is already installed.");
                return;
            }

            using var channelResponse = await JsonDocument.ParseAsync(await _httpClient.GetStreamAsync(result.ChannelJson));

            var file = channelResponse
                       .RootElement.GetProperty("releases").EnumerateArray()
                       .SelectMany(x =>
            {
                IEnumerable <JsonElement> GetSdks()
                {
                    yield return(x.GetProperty("sdk"));

                    if (x.TryGetProperty("sdks", out var sdks))
                    {
                        foreach (var y in sdks.EnumerateArray())
                        {
                            yield return(y);
                        }
                    }
                }

                return(GetSdks());
            })
                       .First(x => x.GetProperty("version").GetString() == result.Version)
                       .GetProperty("files")
                       .EnumerateArray()
                       .First(FileFilter);

            var name         = file.GetProperty("name").GetString();
            var installerUrl = file.GetProperty("url").GetString();
            var fileHash     = file.GetProperty("hash").GetString();

            var filePath = Path.Combine(Path.GetTempPath(), name);

            _textWriter.WriteLine($"Starting download of .NET Core SDK Version {result.Version}");
            using (var installerStream = await _httpClient.GetStreamAsync(installerUrl))
            {
                using var fileStream = new FileStream(filePath, FileMode.Create);
                var progress = new Progress <long>();

                var lastReportedBytesMbs = 0;
                progress.ProgressChanged += (sender, totalBytes) =>
                {
                    var currentBytesMbs = (int)Math.Floor(totalBytes / Math.Pow(2, 20));
                    if (currentBytesMbs <= lastReportedBytesMbs)
                    {
                        return;
                    }
                    lastReportedBytesMbs = currentBytesMbs;
                    _textWriter.SetCursorPosition(0, Console.CursorTop);
                    _textWriter.Write($"Downloading: {currentBytesMbs}MB");
                };

                await CopyToWithProgress(installerStream, fileStream, progress);
            }

            CheckHash(filePath, fileHash);
            _installerLauncher.Launch(filePath);
        }
Exemple #44
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            // do not open app until db connection is valid
            bool isDbConnected = false;

            while (!isDbConnected)
            {
                MySqlConnectionStringBuilder sb = ConnectionStringService.ConnectionString;
                MySqlConnection testConnection  = new MySqlConnection(sb.ConnectionString);

                try
                {
                    testConnection.Open();
                }
                catch (MySqlException ex)
                {
                    var response = MessageBox.Show($@"DB connection error: {ex.Message}", @"DB Connection Error", MessageBoxButtons.RetryCancel);

                    if (response == DialogResult.Cancel)
                    {
                        Application.Exit();
                        return;
                    }

                    new MySqlConfig().ShowDialog(this);
                }

                isDbConnected = testConnection.State == System.Data.ConnectionState.Open;
            }

            var loading = new LoadingForm();

            //prevent clicking behind berfore connections made : Loki
            ToolboxTabControl.Enabled = false;
            loading.Show();
            var progress = new Progress <int>(percent =>
            {
                loading.ProgressBar.Value = percent;

                var item = percent / (100 / DatabaseManager.RegisteredObjects.Length);

                if (item < DatabaseManager.RegisteredObjects.Length)
                {
                    var type = DatabaseManager.RegisteredObjects[item].Name;
                    loading.ProgressText.Text = $@"Loading: {type}";
                }
            });

            // doing this to start loading the db
            await Task.Run(() =>
            {
                DatabaseManager.SetDatabaseConnection(progress);
            });

            loading.ProgressText.Text = @"Loading: Model Viewer";
            await Task.Run(() => ModelService.Instance);

            loading.Close();
            ToolboxTabControl.Enabled = true;
            Text = $@"Dawn of Light Database Toolbox ({ConnectionStringService.ConnectionString.Server})";
            LoadTabForms();
        }
 private async Task StartDownloadAsync(DownloadOperation obj)
 {
     var process = new Progress <DownloadOperation>(ProgressCallback);
     await obj.StartAsync().AsTask(process);
 }
        /// <summary>
        /// Downloader la BD a partir de OneDrive
        /// </summary>
        /// <returns></returns>
        public async static Task <int> ImportBD(CancellationToken ct, Progress <LiveOperationProgress> uploadProgress)
        {
            int log = 0;

            if (LiveClient == null)
            {
                log = await LogClient();
            }

            // Prepare for download, make sure there are no previous requests
            var reqList = BackgroundTransferService.Requests.ToList();

            foreach (var req in reqList)
            {
                if (req.DownloadLocation.Equals(new Uri(@"\shared\transfers\" + AppResources.DBFileName, UriKind.Relative)) ||
                    req.DownloadLocation.Equals(new Uri(@"\shared\transfers\" + AppResources.DBFileName + ".json", UriKind.Relative)))
                {
                    BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
                }
            }

            string fileID = string.Empty;

            //  get folder ID
            string folderID = await GetFolderID("checkmapp");

            if (string.IsNullOrEmpty(folderID))
            {
                return(0); // doesnt exists
            }

            //  get list of files in this folder
            LiveOperationResult loResults = await LiveClient.GetAsync(folderID + "/files");

            List <object> folder = loResults.Result["data"] as List <object>;

            //  search for our file
            foreach (object fileDetails in folder)
            {
                IDictionary <string, object> file = fileDetails as IDictionary <string, object>;
                if (string.Compare(file["name"].ToString(), AppResources.DBFileName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    //  found our file
                    fileID = file["id"].ToString();
                    break;
                }
            }

            if (string.IsNullOrEmpty(fileID))
            {
                //  file doesnt exists
                return(0);
            }

            try
            {
                //  download file from OneDrive
                LiveClient.BackgroundTransferPreferences = BackgroundTransferPreferences.AllowCellularAndBattery;
                await LiveClient.BackgroundDownloadAsync(fileID + @"/content", new Uri(@"\shared\transfers\" + AppResources.DBFileName, UriKind.RelativeOrAbsolute), ct, uploadProgress);
            }
            catch (TaskCanceledException exception)
            {
                Console.WriteLine("Exception occured while downloading file from OneDrive : " + exception.Message);
                return(2);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured while downloading file from OneDrive : " + ex.Message);
                return(0);
            }
            return(1);
        }
        public async Task MonitorEventsFiltered_Succeeds()
        {
            string newTag = $"MonitorTests-{Guid.NewGuid().ToString().Substring(1, 10)}";
            string newImageRespositoryName = Guid.NewGuid().ToString();

            await _client.Images.TagImageAsync(
                $"{_repositoryName}:{_tag}",
                new ImageTagParameters
            {
                RepositoryName = newImageRespositoryName,
                Tag            = newTag
            },
                _cts.Token
                );

            ImageInspectResponse image = await _client.Images.InspectImageAsync(
                $"{newImageRespositoryName}:{newTag}",
                _cts.Token
                );

            var progressCalledCounter = 0;

            var eventsParams = new ContainerEventsParameters()
            {
                Filters = new Dictionary <string, IDictionary <string, bool> >()
                {
                    {
                        "event", new Dictionary <string, bool>()
                        {
                            {
                                "tag", true
                            },
                            {
                                "untag", true
                            }
                        }
                    },
                    {
                        "type", new Dictionary <string, bool>()
                        {
                            {
                                "image", true
                            }
                        }
                    },
                    {
                        "image", new Dictionary <string, bool>()
                        {
                            {
                                image.ID, true
                            }
                        }
                    }
                }
            };

            var progress = new Progress <Message>((m) =>
            {
                progressCalledCounter++;
                Assert.True(m.Status == "tag" || m.Status == "untag");
                _output.WriteLine($"MonitorEventsFiltered_Succeeds: Message received: {m.Action} - {m.Status} {m.From} - {m.Type}");
            });

            using var cts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token);
            var task = Task.Run(() => _client.System.MonitorEventsAsync(eventsParams, progress, cts.Token));

            await _client.Images.CreateImageAsync(new ImagesCreateParameters { FromImage = $"{_repositoryName}:{_tag}" }, null, new Progress <JSONMessage>());

            await _client.Images.TagImageAsync($"{_repositoryName}:{_tag}", new ImageTagParameters { RepositoryName = _repositoryName, Tag = newTag });

            await _client.Images.DeleteImageAsync($"{_repositoryName}:{newTag}", new ImageDeleteParameters());

            var createContainerResponse = await _client.Containers.CreateContainerAsync(new CreateContainerParameters { Image = $"{_repositoryName}:{_tag}" });

            await _client.Containers.RemoveContainerAsync(createContainerResponse.ID, new ContainerRemoveParameters(), cts.Token);

            await Task.Delay(TimeSpan.FromSeconds(1));

            cts.Cancel();

            await Assert.ThrowsAsync <TaskCanceledException>(() => task);

            Assert.Equal(2, progressCalledCounter);
            Assert.True(task.IsCanceled);
        }
Exemple #48
0
 protected void btnSubmit_Click(object sender, System.EventArgs e)
 {
     try
     {
         if (this.isSecValidate == "1" && !FlowAuditAction.CheckAuditPwd(this.UserCode, this.txtAuditPwd.Text.Trim()))
         {
             this.JS.Text = "alert('审核密码不正确!');";
         }
         else
         {
             string auditInfo     = this.txtAuditInfo.Value.Trim();
             string value         = this.hdnType.Value;
             string insertAuditor = string.Empty;
             if (value == "前插")
             {
                 insertAuditor = this.hdnFrontPerson.Value;
             }
             if (value == "后插")
             {
                 insertAuditor = this.hdnAfterPerson.Value;
             }
             if (value == "前插" || value == "后插")
             {
                 if ((value == "前插" && this.txtFrontPerson.Text == "") || (value == "后插" && this.txtAfterPerson.Text == ""))
                 {
                     base.RegisterScript("alert('请选择" + value + "审核人');");
                 }
                 else
                 {
                     string value2 = this.txtAuditRemark.Value;
                     FlowAuditAction.InsertNode(this.InstanceID, this.UserCode, value, this.IsAllPass, insertAuditor, true, auditInfo, value2);
                     this.SendSMS(this.InstanceID);
                     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
                     //stringBuilder.Append("top.ui.refreshDesktop(); \n");
                     //stringBuilder.Append("top.ui.show('" + value + "节点成功!'); \n");
                     //stringBuilder.Append("top.ui.closeTab();\n");
                     stringBuilder.Append("alert('添加成功');");
                     stringBuilder.Append("parent.parent.location.reload();");
                     this.JS.Text = stringBuilder.ToString();
                 }
             }
             else
             {
                 int num = System.Convert.ToInt32(this.RBLRoleType.SelectedValue);
                 if (!FlowAuditAction.GetNextOperator(this.InstanceID) && this.txtnextperson.Text == "" && num == 1)
                 {
                     this.JS.Text = "alert('请选择流程下一个审核人');";
                 }
                 else
                 {
                     if (!FlowAuditAction.GetNextOperator(this.InstanceID) && this.txtnextperson.Text != "" && num == 1)
                     {
                         string project = FlowAuditAction.GetProject(this.BusinessCode, this.InstanceCode);
                         if (!FlowAuditAction.SelectNextOperate(this.InstanceID, this.hdnNextPerson.Value.Trim(), int.Parse(this.NodeType.Value), this.UserCode, project))
                         {
                             this.JS.Text = "alert('请找管理员设置" + this.txtnextperson.Text + "的流程负责人');";
                             return;
                         }
                     }
                     if (num == -3 || num == -2)
                     {
                         string[] allFront = FlowAuditAction.GetAllFront(this.InstanceID);
                         for (int i = 0; i < allFront.Length; i++)
                         {
                             this.AddMsg(allFront[i]);
                         }
                         this.DealAgent();
                     }
                     if (num == 1)
                     {
                         this.SendSMS(this.InstanceID);
                     }
                     this.RecieveMsgAdd();
                     FlowAuditAction.ProcessFlow(this.InstanceID, this.IsAllPass, this.UserCode, num, auditInfo);
                     string maxSing = FlowAuditAction.GetMaxSing(this.InstanceID);
                     WFBusinessCodeService wFBusinessCodeService = new WFBusinessCodeService();
                     WFBusinessCode        byId = wFBusinessCodeService.GetById(this.BusinessCode);
                     string path     = base.Server.MapPath("~/SelfEventInfo.xml");
                     string typeName = SelfEventAction.GetTypeName(path, byId.LinkTable, byId.StateField);
                     if (!string.IsNullOrWhiteSpace(typeName))
                     {
                         ISelfEvent selfEvent = (ISelfEvent)System.Reflection.Assembly.Load("PmBusinessLogic").CreateInstance(typeName);
                         if (selfEvent != null)
                         {
                             if (num == 1 && maxSing == "1")
                             {
                                 selfEvent.CommitEvent(this.InstanceCode.ToString());
                             }
                             if (num == -2)
                             {
                                 selfEvent.RefuseEvent(this.InstanceCode.ToString());
                             }
                             if (num == -3)
                             {
                                 selfEvent.RestatedEvent(this.InstanceCode.ToString());
                             }
                         }
                     }
                     if (this.BusinessCode == "089")
                     {
                         PTPrjInfoZTB byId2 = this.ptInfoZTbSer.GetById(this.InstanceCode);
                         if (maxSing == "1" && num == 1)
                         {
                             this.ptInfoZTbSer.UpdatePrjState(byId2, new int?(2));
                         }
                     }
                     else
                     {
                         if (this.BusinessCode == "100")
                         {
                             if (maxSing == "1" && num == 1)
                             {
                                 PrjMember.AddLimit(this.InstanceCode);
                             }
                         }
                         else
                         {
                             if (this.BusinessCode == "107")
                             {
                                 if (maxSing == "1" && num == 1)
                                 {
                                     Progress.UpdateLatest(this.InstanceCode.ToString());
                                 }
                             }
                             else
                             {
                                 if (this.BusinessCode == "108" && maxSing == "1" && num == 1)
                                 {
                                     cn.justwin.BLL.ProgressManagement.Version.UpdateLatest(this.InstanceCode.ToString());
                                 }
                             }
                         }
                     }
                     if (maxSing == "1")
                     {
                         this.MsgOrganiger();
                     }
                     this.Session.Remove("HumanCode");
                     this.Session.Remove("HumanName");
                     this.JS.Text = "auditSuccess();";
                 }
             }
         }
     }
     catch
     {
         base.RegisterScript("alert('系统提示:\\n\\n此审核数据已经失效!')");
     }
 }
Exemple #49
0
        public static void DetectOptimalModInstallationOptions(ManagedMod mod, Action <Progress> ProgressChanged = null)
        {
            ProgressChanged?.Invoke(Progress.Indetermined("Detecting installation options."));

            /*
             * Searching through folder:
             */

            bool resourceFoldersFound = false;
            bool generalFoldersFound  = false;
            bool texturesFolderFound  = false;
            bool soundFoldersFound    = false;
            bool stringsFolderFound   = false;
            bool dataFolderFound      = false;
            bool videoFolderFound     = false;
            bool dllFound             = false;

            foreach (string folderPath in Directory.EnumerateDirectories(mod.ManagedFolderPath))
            {
                string folderName = Path.GetFileName(folderPath).ToLower();

                if (ModHelpers.ResourceFolders.Contains(folderName))
                {
                    resourceFoldersFound = true;
                }
                if (ModHelpers.GeneralFolders.Contains(folderName))
                {
                    generalFoldersFound = true;
                }
                if (ModHelpers.TextureFolders.Contains(folderName))
                {
                    texturesFolderFound = true;
                }
                if (ModHelpers.SoundFolders.Contains(folderName))
                {
                    soundFoldersFound = true;
                }
                if (folderName == "strings")
                {
                    stringsFolderFound = true;
                }
                if (folderName == "data")
                {
                    dataFolderFound = true;
                }
                if (folderName == "video")
                {
                    videoFolderFound = true;
                }
            }

            foreach (string filePath in Directory.EnumerateFiles(mod.ManagedFolderPath))
            {
                string fileExtension = Path.GetExtension(filePath).ToLower();

                if (fileExtension == ".dll")
                {
                    dllFound = true;
                }
            }


            /*
             * Detecting optimal installation options:
             */

            if (resourceFoldersFound)
            {
                mod.Method      = ManagedMod.DeploymentMethod.SeparateBA2;
                mod.Format      = ManagedMod.ArchiveFormat.Auto;
                mod.Compression = ManagedMod.ArchiveCompression.Auto;
                mod.RootFolder  = "Data";
            }

            if (stringsFolderFound || videoFolderFound)
            {
                mod.Method     = ManagedMod.DeploymentMethod.LooseFiles;
                mod.RootFolder = "Data";
            }

            if (dllFound || dataFolderFound)
            {
                mod.Method     = ManagedMod.DeploymentMethod.LooseFiles;
                mod.RootFolder = ".";
            }

            if (generalFoldersFound)
            {
                mod.Method      = ManagedMod.DeploymentMethod.SeparateBA2;
                mod.Format      = ManagedMod.ArchiveFormat.General;
                mod.Compression = ManagedMod.ArchiveCompression.Compressed;
                mod.RootFolder  = "Data";
            }

            if (texturesFolderFound)
            {
                mod.Method      = ManagedMod.DeploymentMethod.SeparateBA2;
                mod.Format      = ManagedMod.ArchiveFormat.Textures;
                mod.Compression = ManagedMod.ArchiveCompression.Compressed;
                mod.RootFolder  = "Data";
            }

            if (soundFoldersFound)
            {
                mod.Method      = ManagedMod.DeploymentMethod.SeparateBA2;
                mod.Format      = ManagedMod.ArchiveFormat.General;
                mod.Compression = ManagedMod.ArchiveCompression.Uncompressed;
                mod.RootFolder  = "Data";
            }

            if (generalFoldersFound && texturesFolderFound ||
                generalFoldersFound && soundFoldersFound ||
                texturesFolderFound && soundFoldersFound)
            {
                mod.Method      = ManagedMod.DeploymentMethod.BundledBA2;
                mod.Format      = ManagedMod.ArchiveFormat.Auto;
                mod.Compression = ManagedMod.ArchiveCompression.Auto;
                mod.RootFolder  = "Data";
            }
        }
Exemple #50
0
        /// <summary>
        /// Look for the default .pbf testing file in the default test file folder,
        /// plus also in the UnitTest_Files directory in this project or solution
        /// </summary>
        /// <param name="createIfMissing">If true and the .mzML file is ofund, create the .pbf file</param>
        /// <returns>Path to the file if found, otherwise the default path on Proto-2</returns>
        public static string GetPbfTestFilePath(bool createIfMissing)
        {
            var methodName = MethodBase.GetCurrentMethod().Name;

            var pbfFilePath = Path.Combine(DEFAULT_SPEC_FILES_FOLDER, PBF_TEST_FILE);

            var pbfFileInfo = GetTestFile("PbfTestFilePath", pbfFilePath, false);

            if (pbfFileInfo != null)
            {
                // Check for a lock file, which would indicate another process is creating the .pbf file
                var existingLockFile = new FileInfo(Path.Combine(pbfFileInfo.FullName + ".lock"));
                WaitForLockFile(existingLockFile, false);

                pbfFileInfo.Refresh();
                if (pbfFileInfo.Exists)
                {
                    DeleteLockFile(existingLockFile);
                    return(pbfFileInfo.FullName);
                }
            }

            if (!createIfMissing)
            {
                // Not creating the file if missing; return the default path, despite the fact that the file does not exist
                // The calling method will discover that the file is missing and act accordingly
                return(pbfFilePath);
            }

            // Create the missing file

            var mzmlFilePath = Path.Combine(DEFAULT_SPEC_FILES_FOLDER, MZML_TEST_FILE);

            var mzmlFileInfo = GetTestFile("MzmlTestFilePath", mzmlFilePath, false);

            if (mzmlFileInfo?.DirectoryName == null)
            {
                // Unable to create the pbf file; return the default path, despite the fact that the file does not exist
                return(pbfFilePath);
            }

            ShowMessage(methodName, string.Format("Creating {0} using {1}", PBF_TEST_FILE, mzmlFileInfo.FullName));

            var lockFile       = new FileInfo(Path.Combine(mzmlFileInfo.DirectoryName, Path.GetFileNameWithoutExtension(mzmlFileInfo.Name) + ".pbf.lock"));
            var newPbfFilePath = Path.Combine(mzmlFileInfo.DirectoryName, PBF_TEST_FILE);

            try
            {
                // Create a new lock file so other processes know this thread is creating the .pbf file
                WaitForLockFile(lockFile, true);

                mLastStatus = string.Empty;
                var startTime = DateTime.UtcNow;

                var reader   = MassSpecDataReaderFactory.GetMassSpecDataReader(mzmlFileInfo.FullName);
                var progress = new Progress <ProgressData>(p =>
                {
                    p.UpdateFrequencySeconds = 2;
                    if (p.Percent < 100 && (p.Percent % 25).Equals(0) || p.ShouldUpdate())
                    {
                        var statusMessage = string.Format("{0}, {1:00.0}% complete                        ", p.Status, p.Percent);

                        if (string.Equals(mLastStatus, statusMessage))
                        {
                            return;
                        }

                        mLastStatus = statusMessage;
                        Console.Write("\r{0}, {1:00.0}% complete                        ", p.Status, p.Percent);
                    }
                });

                var run = new PbfLcMsRun(mzmlFileInfo.FullName, reader, newPbfFilePath, 0, 0, progress);
                Console.WriteLine();
                ShowMessage(methodName, string.Format("Created {0} in {1:F0} seconds", run.PbfFilePath, DateTime.UtcNow.Subtract(startTime).TotalSeconds));

                DeleteLockFile(lockFile);

                return(run.PbfFilePath);
            }
            catch (Exception ex)
            {
                ShowMessage(methodName, string.Format("Exception creating {0} using {1}: {2}", PBF_TEST_FILE, mzmlFileInfo.FullName, ex.Message));

                try
                {
                    var incompletePbfFile = new FileInfo(newPbfFilePath);
                    if (incompletePbfFile.Exists)
                    {
                        incompletePbfFile.Delete();
                    }

                    DeleteLockFile(lockFile);
                }
                catch
                {
                    // Ignore errors here
                }

                // Return the default path, despite the fact that the file does not exist
                return(pbfFilePath);
            }
        }
Exemple #51
0
        public static string[] GetPrediction(string filePath, int windowInMs = 500)
        {
            var dummyProgress = new Progress <int>(_ => { });

            return(GetPredictionWithProgressReport(filePath, dummyProgress, windowInMs));
        }
Exemple #52
0
        public override IEnumerable <string> Process()
        {
            Progress.SetMessage("This pair end bam file is not sorted by name, it will cost more time/memory to generate fastq files ...");
            var map     = new Dictionary <string, FastqItem>();
            var output1 = _options.OutputPrefix + ".1.fastq";
            var output2 = _options.OutputPrefix + ".2.fastq";

            if (!_options.UnGzipped)
            {
                output1 = output1 + ".gz";
                output2 = output2 + ".gz";
            }
            var tmp1 = output1 + ".tmp";
            var tmp2 = output2 + ".tmp";

            using (var sw1 = StreamUtils.GetWriter(tmp1, !_options.UnGzipped))
            {
                using (var sw2 = StreamUtils.GetWriter(tmp2, !_options.UnGzipped))
                {
                    var sw = new[] { null, sw1, sw2 };

                    using (var sr = new FastqItemBAMParser(_options.InputFile))
                    {
                        FastqItem ss;
                        var       count       = 0;
                        var       outputCount = 0;
                        while ((ss = sr.ParseNext()) != null)
                        {
                            ss.CheckPairedName();

                            count++;

                            if (count % 100000 == 0)
                            {
                                Progress.SetMessage("{0} reads processed, {1} unpaired.", count, map.Count);
                                if (Progress.IsCancellationPending())
                                {
                                    throw new UserTerminatedException();
                                }
                            }

                            FastqItem paired;
                            if (map.TryGetValue(ss.PairName, out paired))
                            {
                                if (paired.PairIndex == ss.PairIndex)
                                {
                                    continue;
                                }
                                ss.WriteFastq(sw[ss.PairIndex]);
                                paired.WriteFastq(sw[paired.PairIndex]);
                                sr.IgnoreQuery.Add(ss.Qname);
                                sr.IgnoreQuery.Add(paired.Qname);
                                map.Remove(ss.PairName);
                                outputCount++;
                                if (outputCount % 100000 == 0)
                                {
                                    var temp = new Dictionary <string, FastqItem>(map);
                                    map.Clear();
                                    map = temp;
                                    GC.Collect();
                                    GC.WaitForPendingFinalizers();
                                    Progress.SetMessage("Cost memory: " + (GC.GetTotalMemory(true) / 1048576) + " MB");
                                }
                            }
                            else
                            {
                                map[ss.PairName] = ss;
                            }
                        }
                    }
                }
            }

            if (File.Exists(output1))
            {
                File.Delete(output1);
            }
            File.Move(tmp1, output1);

            if (File.Exists(output2))
            {
                File.Delete(output2);
            }
            File.Move(tmp2, output2);

            if (map.Count > 0)
            {
                var output3 = Path.ChangeExtension(_options.OutputPrefix, ".orphan.fastq");
                using (var sw3 = new StreamWriter(output3))
                {
                    foreach (var v in map.Values)
                    {
                        v.WriteFastq(sw3);
                    }
                }
            }

            return(new[] { output1, output2 });
        }
        /// <summary>
        /// Thead handling a single server.
        /// It looks for updates that can be downloaded from that server and picks what it can download.
        /// When no more work is available the task finishes.
        /// </summary>
        private async Task UpdateThread(DownloadSourceInfo updateSource, CancellationToken cancellationToken)
        {
            Exception failReason = null;

            try
            {
                // Exit early if the source keeps failing
                var failCount = 0;
                while (!cancellationToken.IsCancellationRequested)
                {
                    UpdateDownloadItem currentDownloadItem  = null;
                    UpdateItem         currentlyDownloading = null;
                    lock (_updateItems)
                    {
                        currentDownloadItem = _updateItems.FirstOrDefault(x =>
                                                                          x.Status == UpdateDownloadStatus.Waiting &&
                                                                          x.DownloadSources.ContainsKey(updateSource.Source));
                        if (currentDownloadItem != null)
                        {
                            currentDownloadItem.Status = UpdateDownloadStatus.Downloading;
                            currentlyDownloading       = currentDownloadItem.DownloadSources[updateSource.Source];
                        }
                    }

                    if (currentlyDownloading == null || cancellationToken.IsCancellationRequested)
                    {
                        Console.WriteLine($"Closing source downloader {updateSource.Source.Origin}");
                        return;
                    }

                    var progress = new Progress <double>(percent => currentDownloadItem.FinishPercent = percent);

                    try
                    {
                        currentDownloadItem.FinishPercent = 0;

                        await RetryHelper.RetryOnExceptionAsync(
                            () => currentlyDownloading.Update(progress, cancellationToken), 3, TimeSpan.FromSeconds(3),
                            cancellationToken);

                        currentDownloadItem.FinishPercent = 100;
                        currentDownloadItem.Status        = UpdateDownloadStatus.Finished;

                        failCount = 0;
                    }
                    catch (Exception e)
                    {
                        if (e is OperationCanceledException)
                        {
                            currentDownloadItem.MarkAsCancelled(e);

                            if (cancellationToken.IsCancellationRequested)
                            {
                                return;
                            }
                            else
                            {
                                continue;
                            }
                        }

                        Console.WriteLine(
                            $"Marking source {updateSource.Source.Origin} as broken because of exception: {e.ToStringDemystified()}");

                        lock (_updateItems)
                        {
                            currentDownloadItem.TryMarkSourceAsFailed(updateSource.Source, e);
                            currentDownloadItem.FinishPercent = 0;
                        }

                        // Give the source a couple of chances before ditching it
                        if (++failCount >= 2)
                        {
                            failReason = e;
                            return;
                        }
                    }
                }
            }
            finally
            {
                if (failReason != null)
                {
                    lock (_updateItems)
                    {
                        var e = new DownloadSourceCrashedException("Update source " + updateSource.Source.Origin + " closed early because of other issues", updateSource.Source, failReason);
                        foreach (var updateTask in _updateItems)
                        {
                            updateTask.TryMarkSourceAsFailed(updateSource.Source, e);
                        }
                    }
                }
            }
        }
Exemple #54
0
        private async void Find()
        {
            string path = edtPath.Text.Trim();

            path = path.Substring(path.Length - 1) == "\\" ? path : $"{path}\\";
            string pattern   = edtPattern.Text.Trim();
            int    fileCount = 0;

            if (string.IsNullOrEmpty(pattern))
            {
                lbFiles.Items.Clear();
                lbLogErros.Items.Clear();
                return;
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();

            _cts = new CancellationTokenSource();

            lblTempoDuracao.Text = "Processando...";
            lbFiles.Items.Clear();
            lbLogErros.Items.Clear();
            pbProgresso.Value = 0;
            btnCancel.Enabled = true;

            var progress = new Progress <string>(file =>
            {
                if (file.Substring(0, 1) != "*")
                {
                    pbProgresso.Value++;
                    fileCount++;
                    lbFiles.Items.Add(file);
                }
                else
                {
                    lbLogErros.Items.Add(file.Substring(1, file.Length - 1));
                }
            });

            try
            {
                var task = await FileUtil.TraverseTreeParallelForEach(path, pattern, progress, _cts.Token);

                pbProgresso.Value = 1000000;
                TimeSpan duration = new TimeSpan(0, sw.Elapsed.Hours, sw.Elapsed.Minutes, sw.Elapsed.Seconds, sw.Elapsed.Milliseconds);

                lblTempoDuracao.Text = $"Tempo decorrido: {duration.ToString("hh':'mm':'ss','fff")}. Total de {fileCount} item(s) encontrado(s).";
            }
            catch (ArgumentException)
            {
                lblTempoDuracao.Text = $@"Diretório {path} não encontrado!";
            }
            catch (OperationCanceledException)
            {
                pbProgresso.Value = 0;
                lbFiles.Items.Clear();
                lbLogErros.Items.Clear();
                lblTempoDuracao.Text = $"Operação cancelada pelo usuário";
            }
            finally
            {
                btnCancel.Enabled = false;
            }
        }
        /// <summary>
        /// Método que generar un archivo excel a partir de la lista de documentos
        /// </summary>
        private async void getExcel()
        {
            DataSet ds = new DataSet();

            //inicializamos objeto de Datatable
            DataTable table = new DataTable();

            //Incializamos los servicios de dialog.
            DialogService dialog = new DialogService();

            //Declaramos un objeto de tipo ProgressDialogController, el cual servirá para recibir el resultado el mensaje progress.
            ProgressDialogController Progress;

            //Si la lista de documentos contiene algún registro
            if (ListaDocumentos.Count != 0)
            {
                //Ejecutamos el método para enviar un mensaje de espera mientras el archivo de excel se genera
                Progress = await dialog.SendProgressAsync(StringResources.msgEspera, StringResources.msgGenerandoExcell);

                //Se añade las columnas, se especifíca el tipo fecha para dar formato a la columna
                //Se tien que especificar el tipo, si no la fecha se escribe mal en Excel
                table.Columns.Add("Numero de Documento");
                table.Columns.Add("Descripción");
                table.Columns.Add("Version");
                table.Columns.Add("Fecha de Revisión", typeof(DateTime));
                table.Columns.Add("Área");
                table.Columns.Add("Tipo de Documento");
                table.Columns.Add("Usuario Elaboró");
                table.Columns.Add("Usuario Autorizó");
                table.Columns.Add("Classification Level");

                //Iteramos la lista de documentos
                foreach (var item in ListaDocumentos)
                {
                    //Se crea una nueva fila
                    DataRow newRow = table.NewRow();

                    //Se añaden los valores a las columnas
                    newRow["Numero de Documento"] = item.nombre;
                    newRow["Descripción"]         = item.descripcion;
                    newRow["Version"]             = item.version.no_version;
                    newRow["Fecha de Revisión"]   = item.version.fecha_version;
                    newRow["Área"] = item.Departamento;
                    newRow["Tipo de Documento"]    = item.tipo.tipo_documento;
                    newRow["Usuario Elaboró"]      = item.usuario;
                    newRow["Usuario Autorizó"]     = item.usuario_autorizo;
                    newRow["Classification Level"] = item.version.ClassificationLevel.ClassificationLevel;

                    //Agregamos la fila a la tabla
                    table.Rows.Add(newRow);
                }
                //Se agrega la tabla al dataset
                ds.Tables.Add(table);

                //Ejecutamos el método para exportar el archivo
                string e = await ExportToExcel.Export(ds);

                //Si hay un error
                if (e != null)
                {
                    //Cerramos el mensaje de espera
                    await Progress.CloseAsync();

                    //Mostramos mensaje de error
                    await dialog.SendMessage(StringResources.ttlAlerta, StringResources.msgErrorGenerarArchivo);
                }
                //Ejecutamos el método para cerrar el mensaje de espera.
                await Progress.CloseAsync();
            }
        }
Exemple #56
0
        public MainWindow()
        {
            this.LogEntries = new ObservableCollection <Log>();
            progress        = new Progress <Log>(
                (log) =>
            {
                this.LogEntries.Insert(0, log);
                int maxLogLength = 100;
                while (this.LogEntries.Count > maxLogLength)
                {
                    this.LogEntries.RemoveAt(maxLogLength);
                }
            });

            InitializeComponent();

            connection = new HubConnectionBuilder().WithUrl("http://192.168.1.10:9999/deskhub")
                         .WithAutomaticReconnect()
                         .Build();

            connection.Closed += async(error) =>
            {
                LogInfo("connection to signalr was lost, reconnecting to signalr hub...");
                await Task.Delay(new Random().Next(0, 5) * 1000);

                await connection.StartAsync();
            };
            connection.Reconnecting += error =>
            {
                LogInfo("connection to signalr was lost, reconnecting to signalr hub...");
                return(Task.CompletedTask);
            };
            connection.Reconnected += connectionId =>
            {
                if (connection.State == HubConnectionState.Connected)
                {
                    ;
                }
                {
                    LogInfo("reconnected to signalr.");
                }

                // Notify users the connection was reestablished.
                // Start dequeuing messages queued while reconnecting if any.

                return(Task.CompletedTask);
            };
            connection.On <DeskStatus>(
                "ReceiveDeskStatus",
                (deskStatus) =>
            {
                this.DeskHeight = deskStatus.Height;

                // toto: set actuator heights
            });

            this.DataContext = this;

            if (DesignerProperties.GetIsInDesignMode(this))
            {
                //
                LogInfo("startup sequence initiated");
                LogInfo("pandemic mode enabled");
                LogInfo("connecting...");
            }

            //FL
            this.FrontLeftUpButton.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(FrontLeftUp_Click), handledEventsToo: true);
            this.FrontLeftUpButton.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), handledEventsToo: true);
            this.FrontLeftDownButton.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(FrontLeftDown_Click), handledEventsToo: true);
            this.FrontLeftDownButton.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), handledEventsToo: true);

            //BL
            this.BackLeftUpButton.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(BackLeftUp_Click), handledEventsToo: true);
            this.BackLeftUpButton.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), handledEventsToo: true);
            this.BackLeftDownButton.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(BackLeftDown_Click), handledEventsToo: true);
            this.BackLeftDownButton.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), handledEventsToo: true);

            //BR
            this.BackRightUpButton.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(BackRightUp_Click), handledEventsToo: true);
            this.BackRightUpButton.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), handledEventsToo: true);
            this.BackRightDownButton.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(BackRightDown_Click), handledEventsToo: true);
            this.BackRightDownButton.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), handledEventsToo: true);

            //FR
            this.FrontRightUpButton.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(FrontRightUp_Click), handledEventsToo: true);
            this.FrontRightUpButton.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), handledEventsToo: true);
            this.FrontRightDownButton.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(FrontRightDown_Click), handledEventsToo: true);
            this.FrontRightDownButton.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), handledEventsToo: true);
        }
Exemple #57
0
        private async void btnStart_Click(object sender, EventArgs e)
        {
            Progress <string> progress = new Progress <string>(s => lblMessage.Text = s);
            await Task.Factory.StartNew(() => UiThread.WriteAsync(progress, "Starting bots"));

            string botName      = txtBotName.Text.ToLower();
            string authToken    = txtAuthToken.Text.ToLower();
            int    numberOfBots = (int)txtNumBots.Value;

            client.DefaultRequestHeaders.Add("Client-ID", "3mx4acqmwya0a96b67encfry7hqwbr");

            DateTime stopTime = DateTime.Now.AddMinutes(-30);

            while (true)
            {
                if (stopTime < DateTime.Now)
                {
                    stopTime = DateTime.Now.AddMinutes(30);
                    List <string> topChannels = new List <string>();

                    //509511 - marbles twitch id
                    string URL = "https://api.twitch.tv/helix/streams?game_id=509511&first=" + numberOfBots;

                    //send request for top marble streams, serialize as objects
                    var response = await client.GetAsync(URL);

                    string            json    = response.Content.ReadAsStringAsync().Result;
                    GetStreamsRequest streams = JsonConvert.DeserializeObject <GetStreamsRequest>(json);

                    //get display names for top streams
                    for (int i = 0; i < streams.data.Count; i++)
                    {
                        URL      = "https://api.twitch.tv/helix/users?id=" + streams.data[i].user_id;
                        response = await client.GetAsync(URL);

                        json = response.Content.ReadAsStringAsync().Result;

                        GetUserInfoRequest userInfo = JsonConvert.DeserializeObject <GetUserInfoRequest>(json);
                        for (int j = 0; j < userInfo.data.Count; j++)
                        {
                            topChannels.Add(userInfo.data[j].display_name.ToLower());
                        }
                    }

                    //start bot for each of these streams
                    foreach (var channel in topChannels)
                    {
                        Bot    b      = new Bot(botName, channel, authToken, stopTime);
                        Thread thread = new Thread(new ThreadStart(b.Start));
                        thread.Start();
                    }

                    string botNamesLabelText = "Bots started on the following channels: \n" + string.Join(", ", topChannels);

                    progress = new Progress <string>(s => lblMessage.Text = s);
                    await Task.Factory.StartNew(() => UiThread.WriteAsync(progress, botNamesLabelText));

                    //wait 10 minutes
                    Thread.Sleep(600000);
                }

                //wait 1 minute - no need to run loop more often
                Thread.Sleep(60000);
            }
        }
Exemple #58
0
        internal static async Task DownloadFileWithProgressAsync(this HttpClient httpClient, string uri, string serverJobUri, string destinationFileName)
        {
            Log.Verbose($"GET {uri}");

            using var request = new HttpRequestMessage(HttpMethod.Get, uri);
            // ResponseHeadersRead is required for the content to be read later on
            using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

            response.EnsureSuccessStatusCode();

            var contentLength = 0;

            if (response.Headers.TryGetValues("FileLength", out var fileLengthHeaderValues))
            {
                int.TryParse(fileLengthHeaderValues.FirstOrDefault(), out contentLength);
            }

            using (var downloadStream = await response.Content.ReadAsStreamAsync())
            {
                var lastMeasure = DateTime.UtcNow;

                var progress = new Progress <long>(reportedLength =>
                {
                    var progressIsComplete = contentLength == reportedLength;
                    var updateProgress     = DateTime.UtcNow - lastMeasure > TimeSpan.FromMilliseconds(1000);

                    if (progressIsComplete || updateProgress)
                    {
                        lock (Console.Out)
                        {
                            if (contentLength != 0)
                            {
                                var progress = ((double)reportedLength / contentLength) * 100;
                                Console.Write($"{(reportedLength / 1024):n0} KB / {(contentLength / 1024):n0} KB ({progress:n0}%)".PadRight(100));
                            }
                            else
                            {
                                Console.Write($"{(reportedLength / 1024):n0} KB".PadRight(100));
                            }

                            lastMeasure = DateTime.UtcNow;

                            if (Environment.UserInteractive && !Console.IsOutputRedirected && Console.In != StreamReader.Null)
                            {
                                Console.CursorLeft = 0;
                            }
                            else
                            {
                                Console.WriteLine();
                            }
                        }
                    }
                });

                using (var fileStream = File.Create(destinationFileName))
                {
                    await downloadStream.CopyToAsync(fileStream, progress);
                }
            }

            Console.WriteLine();
        }
Exemple #59
0
 private static void DeleteUnnecessaryBackups()
 {
     Progress.StartDeleteUnnecessaryBackups();
     SenseNet.ContentRepository.Storage.DataBackingStore.DeleteUnnecessaryBackups();
     Progress.FinishDeleteUnnecessaryBackups();
 }
Exemple #60
0
        private void SaveItems(Dictionary <string, int> ci)
        {
            if (!fileAdded)
            {
                return;
            }

            Progress.Caption = "Guardando ítems";

            //Trae todos los items de la geografía padre para asociar.
            current.GeographyItems.Clear();
            Progress.Total = 0;
            var features = ShapeFile.ReadShapefile(Basename + ".shp");

            Progress.Total = features.Count;
            Dictionary <string, bool> done = new Dictionary <string, bool>();

            int n = 0;
            List <GeographyItem> l = new List <GeographyItem>();

            foreach (var feature in features)
            {
                GeographyItem item = new GeographyItem();
                if (iHousehold != "")
                {
                    item.Households = ParseOrZero(iHousehold, feature);
                }
                if (iChildren != "")
                {
                    item.Children = ParseOrZero(iChildren, feature);
                }
                if (iPopulation != "")
                {
                    item.Population = ParseOrZero(iPopulation, feature);
                }
                if (iUrbanity != "")
                {
                    item.Urbanity = UrbanityEnumFromInt(ParseOrZero(iUrbanity, feature));
                }
                else
                {
                    item.Urbanity = UrbanityEnum.None;
                }
                item.Code = feature.Attributes[iCode].ToString();
                if (iCaption != "")
                {
                    item.Caption = feature.Attributes[iCaption].ToString();
                }

                if (ci != null)
                {
                    var parent = feature.Attributes[iParent].ToString();
                    item.Parent = new GeographyItem(ci[parent]);
                }

                item.Geometry = (Geometry)feature.Geometry;
                if (feature.Geometry != null)
                {
                    item.AreaM2   = Projections.CalculateM2Area(feature.Geometry);
                    item.Centroid = (Point)feature.Geometry.Centroid;

                    Simplifications.FillSimplifiedGeometries(item.Geometry, item);
                }
                else
                {
                    throw new Exception("La geometría no puede ser nula.");
                }

                item.Geography = current;
                if (done.ContainsKey(item.Code) == false)
                {
                    l.Add(item);
                    done[item.Code] = true;
                    if (n % 100 == 99)
                    {
                        string sql = InsertGenerator.FromList(l);
                        context.Data.Session.SqlActions.ExecuteNonQuery(sql);
                        l.Clear();
                    }
                    n++;
                }
                Progress.Increment();
            }
            if (l.Count > 0)
            {
                string sql = InsertGenerator.FromList(l);
                context.Data.Session.SqlActions.ExecuteNonQuery(sql);
            }
            string updateAverage = "UPDATE `geography` SET geo_area_avg_m2=(select avg(gei_area_m2) from "
                                   + "geography_item where gei_geography_id = geo_id) WHERE geo_id = " + current.Id.Value.ToString();

            context.Data.Session.SqlActions.ExecuteNonQuery(updateAverage);
            // esta formula es cualquier cosa, que fitea más o menos 6 como maxzoom de provincias y 11 como maxzoom de departamentos.
            //string updateMaxZoom = "update geography set geo_max_zoom = truncate (16-(power(geo_area_avg_m2, .25) / 60),0) "
            //		+ "WHERE geo_id = " + current.Id.Value.ToString();
            //context.Data.Session.SqlActions.ExecuteNonQuery(updateAverage);
        }