Esempio n. 1
0
 private void bExtractAll_Click(object sender, EventArgs e)
 {
     if (SaveAllDialog.ShowDialog() == DialogResult.OK)
     {
         ProgressForm pf = new ProgressForm("Unpacking archive", false);
         pf.EnableCancel();
         pf.SetProgressRange(Files.Length);
         pf.Show();
         int count = 0;
         try
         {
             foreach (BSAFileEntry fe in Files)
             {
                 fe.Extract(SaveAllDialog.SelectedPath, true, br, ContainsFileNameBlobs);
                 pf.UpdateProgress(count++);
                 Application.DoEvents();
             }
         }
         catch (fommCancelException)
         {
             MessageBox.Show("Operation cancelled", "Message");
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, "Error");
         }
         pf.Unblock();
         pf.Close();
     }
 }
Esempio n. 2
0
		public static bool Execute(IWin32Window parent, Action<IProgressReporter> method, bool cancellable) {
			if (method == null) throw new ArgumentNullException("method");

			Exception exception = null;

			bool canceled = false;
			using (var dialog = new ProgressForm() { CanCancel = cancellable }) {

				dialog.FadeIn();
				ThreadPool.QueueUserWorkItem(delegate {
					try {
						method(dialog);
					} catch (Exception ex) {
						exception = ex;
					} finally {
						dialog.Finished = true;
						dialog.FadeOut();
					}
					canceled = dialog.WasCanceled;
				});
				if (!dialog.IsDisposed && !dialog.Finished)
					dialog.ShowDialog(parent);
			}
			if (exception != null)
				throw new TargetInvocationException(exception);
			return !canceled;
		}
Esempio n. 3
0
        public UiProcessExporter(string encoding)
        {
            _form = new ProgressForm();
            _exporter = new ProcessExporter(encoding);
            _exporter.StartStep += new StepStartEventHandler(exporter_StartStep);
            _exporter.EndStep += new StepEndEventHandler(exporter_EndStep);

            _transition = new ExportTransitions();
            _transition.StartStep += new StepStartEventHandler(exporter_StartStep);
            _transition.EndStep += new StepEndEventHandler(exporter_EndStep);

            _maxSize = int.Parse(Resources.GetString(ResourceTokens.ShapeTextMaxSize));
            _more = Resources.GetString(ResourceTokens.ShapeTextTruncate);
        }
Esempio n. 4
0
        public static void ExecAsync(Action<IProgressReporter> userMethod, string caption, bool cancellable)
        {
            var syncContext = SynchronizationContext.Current;
            Debug.Assert(syncContext is WindowsFormsSynchronizationContext);

            Action wrapper = delegate {
                Debug.Assert(syncContext is WindowsFormsSynchronizationContext);
                isRunning = true;
                try {
                    using (var dialog = new ProgressForm {
                        Caption = caption,
                        Maximum = -1,
                        CanCancel = cancellable
                    })
                    using (var waiter = new ManualResetEvent(false)) {
                        ThreadPool.QueueUserWorkItem(delegate {
                            try {
                                userMethod(dialog);
                            } catch (Exception ex) {
                                syncContext.Post(delegate {
                                    var task = Char.ToLower(caption[0]) + caption.Substring(1).TrimEnd('.');
                                    XtraMessageBox.Show("An error occurred while " + task + ".\r\n\r\n" + ex, "Shomrei Torah Schedulizer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    dialog.Close();
                                }, null);
                                return;
                            } finally { waiter.Set(); }
                            syncContext.Post(_ => dialog.Close(), null);
                        });

                        if (waiter.WaitOne(TimeSpan.FromSeconds(.5), false))
                            return;	//If it finishes very quickly, don't show progress.  Otherwise, we get an annoying focus bounce whenever we switch cells

                        dialog.ShowDialog();
                    }
                } finally {
                    isRunning = false;
                    if (pendingActions.Count > 0)
                        BeginInvoke(pendingActions.Dequeue());
                }
            };

            if (isRunning)
                pendingActions.Enqueue(wrapper);
            else {
                isRunning = true;	//In case we get called again in this message loop before the wrapper starts
                BeginInvoke(wrapper);
            }
        }
Esempio n. 5
0
		///<summary>Executes a cancellable asynchronous operation and displays its progress.</summary>
		///<param name="parent">The form that will own the progress display.  This parameter can be null.</param>
		///<param name="method">The method to execute.  This should not do any immediate blocking work.</param>
		///<returns>False if the cancel button was clicked.</returns>
		public static async Task ExecuteAsync(IWin32Window parent, Func<IProgressReporter, CancellationToken, Task> method) {
			if (method == null) throw new ArgumentNullException("method");

			using (var dialog = new ProgressForm() { CanCancel = true }) {
				dialog.FadeIn();
				try {
					var task = method(dialog, dialog.CancellationSource.Token);
					await Task.WhenAny(task, Task.Delay(5));    // If it finishes quickly, don't bother showing the dialog.
					if (task.IsCompleted)
						return;
					SynchronizationContext.Current.Post(_ => dialog.ShowDialog(parent), null);
					await task;
				} finally {
					dialog.Finished = true;
					dialog.FadeOut();
				}
				if (dialog.WasCanceled)
					throw new TaskCanceledException();
			}
		}
Esempio n. 6
0
 private void HideProgressForm()
 {
     ProgressForm.Hide();
 }
Esempio n. 7
0
        void agentServer_OnCommand(Command command)
        {
            RanorexStepExecutionResponse stepResponse = null;

            if (command.command == "invoke")
            {
                if (!reportSetupDone)
                {
                    TestReport.Setup(Report.CurrentReportLevel, null, true, TestReport.EnableTracingScreenshots, 0, null);
                    reportSetupDone = true;
                }

                if (showExecutionUI)
                {
                    ProgressForm.Show();
                }
                else
                {
                    ProgressForm.Hide();
                }

                Dictionary <string, object> arguments = command.arguments;
                Hashtable props = (Hashtable)arguments["props"];

                if (sessionType == "Mobile")
                {
                    string target = (string)command.arguments["target"];
                    if (target.StartsWith("/mobileapp/"))
                    {
                        target.Replace("/mobileapp", "/mobileapp[@devicename'" + mobileDevice + "']");
                    }
                }

                foreach (DictionaryEntry entry in props)
                {
                    arguments.Add((string)entry.Key, entry.Value);
                }
                stepResponse = new RanorexHandlerFactory().GetHandler((string)command.arguments["itest-action"], repo).Execute(arguments);
                EXECUTION_INDEX++;
            }
            else if (command.command == "ping")
            {
                agentServer.Ping();
            }
            else if (command.command == "open")
            {
                try
                {
                    if ((bool)command.arguments["capture"] == true)
                    {
                        isInteractive = true;
                    }

                    OpenSession(command);

                    stepResponse         = new RanorexStepExecutionResponse();
                    stepResponse.success = true;
                }
                catch (Exception e)
                {
                    stepResponse         = new RanorexStepExecutionResponse();
                    stepResponse.success = false;
                    stepResponse.message = "Failed to open Ranorex session: " + e.Message;

                    agentServer.DropClient();
                }
            }
            else if (command.command == "close")
            {
                closeSession();
                agentServer.DropClient();
            }
            else if (command.command == "startcapture")
            {
            }
            else if (command.command == "stopcapture")
            {
                Thread startThread = new Thread(StopRecording);
                startThread.SetApartmentState(ApartmentState.STA);
                startThread.Start();
            }

            if (stepResponse != null)
            {
                AgentResponse agentResponse = new AgentResponse();
                agentResponse.messageType           = AgentResponse.MessageType.EXECUTION_STEP_RESPONSE;
                agentResponse.stepExecutionResponse = stepResponse;
                agentServer.SendMessage(agentResponse);
            }
        }
Esempio n. 8
0
        internal void ParameterPopulate()
        {
            // UPDATE AFTER COLUMNS ADJUSTMENT
            parameterMap     = Parameters.parameterMap(num);
            parameterTypeMap = Parameters.parameterTypeMap(num);

            Dictionary <string, string> type = new Dictionary <string, string>();

            int n = projectDataArray.Count;

            string s       = "{0} of " + n.ToString() + " elements processed...";
            string caption = "Import from Excel";


            using (Transaction t = new Transaction(doc, "Import parameters"))
            {
                t.Start();

                using (ProgressForm pf = new ProgressForm(caption, s, n))
                {
                    foreach (string[] arr in projectDataArray)
                    {
                        Element el = null;

                        if (pf.getAbortFlag())
                        {
                            t.RollBack();
                            return;
                        }
                        pf.Increment();
                        try
                        {
                            el = doc.GetElement(arr[0]);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        if (el == null)
                        {
                            continue;
                        }
                        try
                        {
                            for (int i = 1; i < parameterMap.Count - 2; i++)
                            {
                                string name = parameterMap[i];
                                if (Parameters.IsInsanceParameter(name, parameterTypeMap))
                                {
                                    Parameter p = el.LookupParameter(parameterMap[i]);
                                    if (p != null && !p.IsReadOnly)
                                    {
                                        p.Set(arr[i]);
                                    }
                                }
                                else
                                {
                                    type[String.Format("{0}:{1}", el.GetTypeId().IntegerValue.ToString(), parameterMap[i])] = arr[i];
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            TaskDialog.Show("Error", ex.Message);
                        }
                    }
                    t.Commit();
                }
            }
            using (Transaction t1 = new Transaction(doc, "Importe Type Parameters"))
            {
                t1.Start();

                n = type.Count;

                s = "{0} of " + n.ToString() + " type parameters processed...";

                using (ProgressForm pf = new ProgressForm(caption, s, n))
                {
                    foreach (var pair in type)
                    {
                        if (pf.getAbortFlag())
                        {
                            t1.RollBack();
                            return;
                        }
                        pf.Increment();

                        string[] sp = pair.Key.Split(':');
                        if (sp[0].Equals("-1"))
                        {
                            continue;
                        }
                        Element   el = doc.GetElement(new ElementId(Convert.ToInt32(sp[0])));
                        Parameter p  = el.LookupParameter(sp[1]);
                        if (p != null && !p.IsReadOnly)
                        {
                            p.Set(pair.Value);
                        }
                    }
                }
                t1.Commit();
            }
        }
Esempio n. 9
0
        /// <summary>Download and install the new version</summary>
        private void Install()
        {
            // Generate a temporary file for the installed
            var uri = new Uri(DownloadUrl);
            var installer_filepath = Path.Combine(Path.GetTempPath(), Path.GetFileName(DownloadUrl) ?? "RyLogViewerInstaller.exe");

            try
            {
                var dlg = new ProgressForm("Upgrading...", "Downloading latest version", Icon, ProgressBarStyle.Continuous, (form, args, cb) =>
                {
                    // Download the installer for the new version
                    using (var web = new WebClient {
                        Proxy = Proxy
                    })
                        using (var got = new ManualResetEvent(false))
                        {
                            Exception error            = null;
                            web.DownloadFileCompleted += (s, a) =>
                            {
                                try
                                {
                                    error = a.Error;
                                    if (a.Cancelled)
                                    {
                                        form.CancelSignal.Set();
                                    }
                                }
                                catch {}
                                finally { got.Set(); }
                            };

                            web.DownloadFileAsync(uri, installer_filepath);

                            // Wait for the download while polling the cancel pending flag
                            while (!got.WaitOne(100))
                            {
                                if (form.CancelPending)
                                {
                                    web.CancelAsync();
                                }
                            }

                            if (form.CancelPending)
                            {
                                throw new OperationCanceledException();
                            }
                            if (error != null)
                            {
                                throw new Exception("Failed to download installer for latest version", error);
                            }
                        }
                });
                using (dlg)
                    if (dlg.ShowDialog(this) != DialogResult.OK)
                    {
                        return;
                    }

                // Run the installer
                Process.Start(installer_filepath);

                // Shutdown this app
                Application.Exit(new CancelEventArgs());
            }
            catch (Exception ex)
            {
                Log.Write(ELogLevel.Error, ex, "Auto updated did not complete");
                MsgBox.Show(this, $"Automatic updated failed\r\nReason: {ex.MessageFull()}", "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="progressForm">Handle to the parent form</param>
 public ImportThread(ProgressForm progressForm, int testRailProjectId, string testLinkProjectName)
 {
     this.progressForm        = progressForm;
     this.testLinkProjectId   = testRailProjectId;
     this.testLinkProjectName = testLinkProjectName;
 }
Esempio n. 11
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            ProgressForm pForm = new ProgressForm();
            pForm.Show();
            dgvPluginData.Sort( dgvPluginData.Columns[0], ListSortDirection.Descending);
            int i = -1; int count = 0;
            while (++i < dgvPluginData.RowCount && (bool)dgvPluginData[0, i].Value == true)
            {
                PluginData pd = (PluginData)dgvPluginData.Rows[i].Tag;
                string localName = pd.tagType + ".ent";
                pForm.Text = "updating " + localName;
                pForm.Value = count++ * 100 / totalChecked;
                pForm.Refresh();

                WebClient wc = new WebClient();
                wc.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                try
                {
                    wc.DownloadFile(
                        pluginsFTPServer + pd.fileData.name,
                        Globals.Prefs.pathPluginsFolder + "\\" + localName
                        );
                }
                catch (Exception ex)
                {
                    Globals.Global.ShowErrorMsg("Error downloading plugin", ex);
                }
            }
            pForm.Dispose();

            HaloMap.Plugins.IFPHashMap.H1IFPHash.Clear();
            HaloMap.Plugins.IFPHashMap.H2IFPHash.Clear();
        }
Esempio n. 12
0
 private void ShowProgressForm(object sender, ISortParams e)
 {
     ProgressForm.Show();
 }
Esempio n. 13
0
        async static public void UploadToGallery(
            string filename,
            string modelname)
        {
            System.Windows.Forms.IWin32Window revit_window
                = new JtWindowHandle(
                      Autodesk.Windows.ComponentManager.ApplicationWindow);

            var syncContext = SynchronizationContext.Current;

            FileUploadForm fUp = new FileUploadForm();

            fUp.UserName = Util.GetUser();
            fUp.EMail    = Util.GetEmail();

            var dialogResult = fUp.ShowDialog(revit_window);

            if (dialogResult != System.Windows.Forms.DialogResult.OK)
            {
                Util.LogError("Upload cancelled.");

                return;
            }

            if (fUp.StoreDetails)
            {
                Util.StoreUserInfo(fUp.UserName, fUp.EMail);
            }

            SynchronizationContext.SetSynchronizationContext(
                syncContext);

            // The gallery bucket

            var bucketKey = "adn-viewer-gallery";

            string consumer_key, consumer_secret;

            if (!Util.GetConsumerCredentials(
                    "C:/credentials.txt",
                    out consumer_key,
                    out consumer_secret))
            {
                Util.LogError("Consumer credentials retrieval failed.");
                return;
            }

            AdnViewDataClient viewDataClient = new AdnViewDataClient(
                UserSettings.BASE_URL,
                consumer_key,
                consumer_secret);

            var tokenResult = await viewDataClient.AuthenticateAsync();

            if (!tokenResult.IsOk())
            {
                Util.LogError("Authentication failed: "
                              + tokenResult.Error.Reason);

                return;
            }

            // Generate unique file key

            string objectKey = Guid.NewGuid().ToString()
                               + ".rvt";

            var fi = FileUploadInfo.CreateFromFile(
                objectKey, filename);

            var bucketData = new BucketCreationData(
                bucketKey,
                BucketPolicyEnum.kPersistent);

            var response
                = await viewDataClient.UploadAndRegisterAsync(
                      bucketData, fi);

            if (!response.IsOk())
            {
                Util.LogError("Error: " + response.Error.Reason);

                return;
            }

            if (response is RegisterResponse)
            {
                RegisterResponse registerResponse = response as RegisterResponse;

                if (registerResponse.Result.ToLower() != "success")
                {
                    Util.LogError("Registration failed: " + registerResponse.Result);

                    return;
                }

                var fileId = viewDataClient.GetFileId(
                    bucketKey,
                    objectKey);

                var dbModel = new DBModel(
                    new Author(fUp.UserName, fUp.EMail),
                    modelname,
                    fileId,
                    fileId.ToBase64());

                string url = Util.GalleryUrl;

                AdnGalleryClient galleryClient = new AdnGalleryClient(
                    url);

                DBModelResponse modelResponse
                    = await Util.AddModelToGalleryAsync(
                          dbModel);

                if (!modelResponse.IsOk())
                {
                    Util.LogError(string.Format("Error: '{0}' {1}",
                                                modelResponse.Error.ToString(),
                                                null == modelResponse.Model ? "model is null" : ""));

                    return;
                }

                url = url + "/#/viewer?id=" + modelResponse.Model.Id;

                if (fUp.ShowProgress)
                {
                    var notifier = new TranslationNotifier(
                        viewDataClient,
                        fileId,
                        2000);

                    var fProgress = new ProgressForm(
                        modelname,
                        url,
                        notifier);

                    fProgress.Show(revit_window);

                    notifier.OnTranslationCompleted +=
                        OnTranslationCompleted;

                    notifier.Activate();
                }
                string msg = "You successfully "
                             + " uploaded a new model to the gallery.\r\n"
                             + "Your model is viewable at the following url:\r\n"
                             + url;

                Util.LogError(msg);

                TaskDialog dlg = new TaskDialog(
                    "Gallery Upload");

                dlg.MainInstruction = "Upload succeeded";
                dlg.MainContent     = msg;
                dlg.Show();
            }
        }
Esempio n. 14
0
        private void RetrieveDataFromFTPServer()
        {
            FtpWebRequest  ftpRequest;
            FtpWebResponse ftpResponse;

            xDoc = new XmlDocument();

            #region Attempt to download plugin database file
            try
            {
                // Create a request for the database file
                ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPdbFile);
                // Set default authentication for retrieving the file info
                ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);

                ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
                ftpResponse       = (FtpWebResponse)ftpRequest.GetResponse();
                // Ask the server for the file size and store it
                long fileSize = ftpResponse.ContentLength;
                ftpResponse.Close();

                WebClient wc = new WebClient();
                wc.Credentials = ftpRequest.Credentials;
                xDoc.LoadXml(wc.DownloadString(pluginsFTPdbFile));
            }
            catch
            {
                xDoc.AppendChild(xDoc.CreateElement("Plugins"));
            }
            #endregion

            #region Retrieve list of all files & directories from FTP server
            try
            {
                // Create a request to the directory we are working in
                ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPServer);
                // Set default authentication for retrieving the file info
                ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                ftpRequest.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;
                ftpResponse            = (FtpWebResponse)ftpRequest.GetResponse();
                StreamReader streamReader = new StreamReader(ftpResponse.GetResponseStream());
                string       line         = streamReader.ReadLine();
                while (!string.IsNullOrEmpty(line))
                {
                    listing.Add(new FileData(line));
                    line = streamReader.ReadLine();
                }
                ftpResponse.Close();
            }
            catch (Exception ex)
            {
            }
            #endregion

            ProgressForm formPB = new ProgressForm();
            formPB.Show();

            HashSet <string> hashTable  = new HashSet <string>();
            bool             xDocChange = false;
            foreach (FileData fd in listing)
            {
                // We only want files (non-directories)
                if ((fd.attrib | FileAttributes.Directory) != FileAttributes.Directory)
                {
                    string[] fName        = fd.name.ToLower().Split('.', '-');
                    string   modifiedName = fName[0].Replace('!', '_').Replace('+', '_');

                    #region Update information box
                    formPB.Text  = "Analyzing: \n" + fd.name;
                    formPB.Value = listing.IndexOf(fd) * 100 / listing.Count;
                    Application.DoEvents();
                    #endregion

                    if (fName[fName.Length - 1] != "ent")
                    {
                        continue;
                    }

                    /*
                     * if (fName.Length > 3)
                     * {
                     *  string ver = fName[1];
                     *  for (int i = 2; i < fName.Length - 1; i++)
                     *      ver += '.' + fName[i];
                     *  fVer = new Version(ver);
                     * }
                     */

                    // Check for the matching tag HASHCODE name
                    XmlNodeList xnl   = null;
                    XmlNode     xNode = null;

                    if (fName.Length > 2)
                    {
                        xnl = xDoc.GetElementsByTagName("_" + fName[1]);
                    }


                    // Search through each return value for the one in the desired parent TAG TYPE
                    if (xnl != null && xnl.Count > 0)
                    {
                        foreach (XmlNode xn in xnl)
                        {
                            if (xn.ParentNode.Name == modifiedName)
                            {
                                xNode = xn;
                                break;
                            }
                        }
                    }

@updatePlugin:
                    // If we do not get any results for the HASHCODE, check for parent TAG TYPE
                    if (xNode == null)
                    {
                        // Search for a matching TAG TYPE
                        XmlNodeList xml = xDoc.GetElementsByTagName(modifiedName);

                        // No matching TAG TYPE was found, so create a tag placeholder (eg. SCNR)
                        if (xml.Count == 0)
                        {
                            xNode = xDoc.CreateElement(modifiedName);
                            xDoc.FirstChild.AppendChild(xNode);
                        }
                        // We found a matching TAG TYPE, so select it
                        else
                        {
                            xNode = xml[0];
                        }

                        // Retrieve the plugin from the server & parse for needed info
                        WebClient wc = new WebClient();
                        wc.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                        try
                        {
                            string      tempPlugin = wc.DownloadString(pluginsFTPServer + fd.name);
                            XmlDocument xd         = new XmlDocument();
                            xd.LoadXml(tempPlugin);
                            XmlNodeList XList;
                            XmlNode     xnA; // Holds author attribute info
                            XmlNode     xnV; // Holds version attribute info
                            string      tag;

                            try
                            {
                                XList = xd.GetElementsByTagName("revision");
                                xnA   = XList[0].Attributes.GetNamedItem("author");
                                xnV   = XList[0].Attributes.GetNamedItem("version");
                                try
                                {
                                    tag = XList[0].Attributes.GetNamedItem("class").Value;
                                }
                                catch
                                {
                                    tag = fName[1].ToLower();
                                }
                            }
                            catch
                            {
                                try
                                {
                                    XList = xd.GetElementsByTagName("plugin");
                                    xnA   = XList[0].Attributes.GetNamedItem("author");
                                    xnV   = XList[0].Attributes.GetNamedItem("version");
                                    tag   = XList[0].Attributes.GetNamedItem("class").Value;
                                }
                                catch
                                {
                                    // Bad plugin?
                                    continue;
                                }
                            }

                            //
                            // Need to generate name first & will rename later
                            //
                            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                            string md5 = GetChecksum(encoding.GetBytes(tempPlugin));

                            if (fName.Length > 2)
                            {
                                xNode = xNode.AppendChild(xDoc.CreateElement("_" + fName[1]));
                            }
                            else
                            {
                                xNode = xNode.AppendChild(xDoc.CreateElement("_---"));
                            }

                            // Append author & version to xNode
                            // (This needs to be after the xNode is possibly set to xNode.Child)

                            // MD5 Hashcode
                            XmlAttribute xAttr = xDoc.CreateAttribute("md5");
                            xAttr.InnerText = md5;
                            xNode.Attributes.Append(xAttr);

                            // Author info
                            xAttr           = xDoc.CreateAttribute("tagtype");
                            xAttr.InnerText = tag;
                            xNode.Attributes.Append(xAttr);

                            // Author info
                            xAttr           = xDoc.CreateAttribute("author");
                            xAttr.InnerText = xnA.Value;
                            xNode.Attributes.Append(xAttr);

                            // Version info
                            xAttr           = xDoc.CreateAttribute("version");
                            xAttr.InnerText = xnV.Value;
                            xNode.Attributes.Append(xAttr);

                            // States that changes need to be made to database file
                            xDocChange = true;
                        }
                        catch (Exception ex)
                        {
                            Globals.Global.ShowErrorMsg("Error from plugin server: ", ex);
                        }
                    }
                    PluginData pd = new PluginData(fd, xNode);
                    if (pd.md5 == string.Empty)
                    {
                        xNode = null;
                        goto @updatePlugin;
                    }
                    if (hashTable.Contains(pd.md5))
                    {
                        // Duplicate file found, erase file & remove entry
                        try
                        {
                            ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPServer + fd.name);
                            // Set default authentication for retrieving the file info
                            ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);

                            ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                            ftpResponse       = (FtpWebResponse)ftpRequest.GetResponse();
                            // Ask the server for the file size and store it
                            ftpResponse.Close();
                            xDocChange = true;
                        }
                        catch
                        { }
                        continue;
                    }

                    hashTable.Add(pd.md5);

                    // 1827
                    // "_fx_-87943969.ent"
                    // {27/10/2012 1:49:00 AM}
                    // "Grimdoomer"
                    // "0.99"

                    // Create a unique short hash code for this plugin using author, version & file date/time stamp
                    string hashcode = pd.GetHashCode().ToString();
                    string fileName = fName[0] + '-' + hashcode + ".ent";
                    if (fd.name.ToLower() != fileName)
                    {
                        // Rename the node to reflect the [new] hashcode
                        if (xNode.Name != "_" + hashcode)
                        {
                            xNode = RenameNode(xNode, string.Empty, '_' + hashcode);
                        }
                        #region Rename file to naming sequence
                        // Create a request to the directory we are working in
                        ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPServer + fd.name);
                        // Set default authentication for retrieving the file info
                        ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                        ftpRequest.Method      = WebRequestMethods.Ftp.Rename;
                        ftpRequest.RenameTo    = fileName;
                        ftpResponse            = (FtpWebResponse)ftpRequest.GetResponse();
                        ftpResponse.Close();
                        #endregion
                        fd.name = fileName;
                    }

                    if (pd.version == "0.0")
                    {
                        int a = 0;
                    }
                    this.Add(fName[0], pd);
                }
            }
            // Clean up our loading form
            formPB.Dispose();

            if (xDocChange)
            {
                // WriteXDoc back out
                WebClient wc = new WebClient();
                wc.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                wc.UploadString(pluginsFTPdbFile, xDoc.InnerXml);
            }
        }
Esempio n. 15
0
        public static void Sync(FolderSyncInterface fsi)
        {
            if (!fsi.Setup())
            {
                goto error;
            }

            var dir = $"{Helper.directory}Revision/";
            var di  = new DirectoryInfo(dir);

            Queue <string> filePushQueue = null;
            Queue <string> filePullQueue = null;

            bool QueuePushes()
            {
                bool success = false;

                ProgressForm.BeginWait("Queueing file pushes...", progress =>
                {
                    success = (filePushQueue = fsi.FilesToPush(progress)) != null;
                });
                return(success);
            };

            bool QueuePulls()
            {
                bool success = false;

                ProgressForm.BeginWait("Queueing file pulls...", progress =>
                {
                    success = (filePullQueue = fsi.FilesToPull(progress)) != null;
                });
                return(success);
            }

            bool PushFiles()
            {
                bool success = true;

                ProgressForm.BeginWait("Pushing files...", progress =>
                {
                    int amount = filePushQueue.Count;
                    for (int i = 0; i < amount; i++)
                    {
                        if (fsi.PushFile(filePushQueue.Dequeue()))
                        {
                            progress.Report((float)i / amount);
                        }
                        else
                        {
                            success = false;
                            break;
                        }
                    }
                });
                return(success);
            }

            bool PullFiles()
            {
                bool success = true;

                ProgressForm.BeginWait("Pulling files...", progress =>
                {
                    int amount = filePullQueue.Count;
                    for (int i = 0; i < amount; i++)
                    {
                        if (fsi.PullFile(filePullQueue.Dequeue()))
                        {
                            progress.Report((float)i / amount);
                        }
                        else
                        {
                            success = false;
                            break;
                        }
                    }
                });
                return(success);
            };

            if (fsi.PushFirst)
            {
                if (!QueuePushes())
                {
                    goto error;
                }
                if (!QueuePulls())
                {
                    goto error;
                }
            }
            else
            {
                if (!QueuePulls())
                {
                    goto error;
                }
                if (!QueuePushes())
                {
                    goto error;
                }
            }

            if (fsi.PushFirst)
            {
                if (!PushFiles())
                {
                    goto error;
                }
                if (!PullFiles())
                {
                    goto error;
                }
            }
            else
            {
                if (!PullFiles())
                {
                    goto error;
                }
                if (!PushFiles())
                {
                    goto error;
                }
            }

            fsi.Finish();

            MsgBox.ShowWait("Successfully synchronized all files.", "Sync", null, MsgBox.MsgIcon.TICK);
            return;

error:
            fsi.Finish();

            MsgBox.ShowWait("File sync was not completed successfully.", "Sync", null, MsgBox.MsgIcon.EXCL);
            return;
        }
Esempio n. 16
0
        /// <summary>
        /// アプリケーションの起動 (進捗ダイアログを表示する場合があるため、UIスレッドで立ち上げる必要がある)
        /// </summary>
        /// <returns>正常に起動したかどうか。falseを返した場合はアプリケーションを終了</returns>
        public virtual bool Boot()
        {
            // ロガー初期化
            Logger = NLog.LogManager.GetLogger("Application");

            // ログ出力
            Logger.Info("アプリケーション起動中...");

            // ユーザー設定の読み込み
            UserSettings = UserSetting.Store.Setup(UserSettingPath);

            // Groongaの起動 (Groongaが存在しなければ終了)
            GM = new Groonga.Manager(DBDirPath, LogDirPath);
            if (!File.Exists(GM.GroongaExePath))
            {
                Util.ShowErrorMessage("groonga.exeが見つかりませんでした。");
                Quit();
                return(false);
            }
            GM.Boot();

            // プラグインの読み込み
            PluginManager = new Plugin.Manager();
            var loadedPluginVersionNumbers = PluginManager.LoadPlugins();

            // 対応フォーマット一覧の更新
            RefreshFormats();

            // クローラの初期化
            Crawler = new Crawler(this);

            // 現在DBのスキーマバージョンを取得 (DBが存在しない場合は0)
            var schemaVer = GM.GetSchemaVersion();

            // 現在DBのスキーマバージョンが、アプリケーションが要求するスキーマバージョンより高い場合はエラーとして終了
            if (schemaVer > Groonga.Manager.AppSchemaVersion)
            {
                Util.ShowErrorMessage(string.Format("このバージョンのInazuma Searchが最新バージョンではないため、データベースを読み込むことができません。\n最新バージョンのInazuma Searchを使用してください。"));
                Quit();
                return(false);
            }

            // 現在DBのスキーマバージョンが、アプリケーションが要求するスキーマバージョンより低い場合は
            // DBの新規作成orアップグレード処理を実行
            if (schemaVer < Groonga.Manager.AppSchemaVersion)
            {
                var reCrawlRequired = false;
                var t = Task.Run(() =>
                {
                    GM.SetupSchema(schemaVer, out reCrawlRequired);
                });
                var msg = (schemaVer == 0 ? "データベースを作成しています。しばらくお待ちください..." : "データベースを更新しています。しばらくお待ちください...");
                var f   = new ProgressForm(t, msg);
                f.ShowDialog();

                // 再度のクロールが必要ならメッセージを表示
                if (reCrawlRequired)
                {
                    MessageBox.Show(string.Format("Inazuma Searchのアップグレードにより、再度のクロール実行が必要となります。\nお手数をおかけしますが、起動後にクロールを実行してください。"), "確認");
                }

                // ユーザー設定を再読み込み (スキーマ更新で影響が及ぶ場合があるため)
                UserSettings.Load();
            }

            // プラグイン構成に変更があれば、確認ダイアログを削除してクロール結果を削除
            foreach (var pair in loadedPluginVersionNumbers)
            {
                var pluginFullName = pair.Key;
                var versionNumber  = pair.Value;

                if (!UserSettings.LastLoadedPluginVersionNumbers.ContainsKey(pluginFullName) ||
                    versionNumber != UserSettings.LastLoadedPluginVersionNumbers[pluginFullName])
                {
                    if (Util.Confirm("プラグインの構成が変更されています。\nこの変更により、クロール結果に差異が出る可能性があります。\n\nInazuma Searchが保持している、クロール済みの文書情報を削除してもよろしいですか?\n(文書ファイルは削除されません)"))
                    {
                        var t = Task.Run(() =>
                        {
                            GM.Truncate(Table.Documents);
                            GM.Truncate(Table.DocumentsIndex);
                            DeleteAllThumbnailFiles();
                        });
                        var f = new ProgressForm(t, "文書データをクリアしています...");
                        f.ShowDialog();
                    }
                    ;
                    break;
                }
            }

            // 前回の最終起動バージョンが0.17.0よりも前であれば、フォルダラベルの更新を実行
            if (UserSettings.LastBootVersion == null)
            {
                var t = Task.Run(() =>
                {
                    UpdateDocumentFolderLabels();
                });
                var f = new ProgressForm(t, "データベースを更新しています。しばらくお待ちください...");
                f.ShowDialog();
            }

            // 前回の最終起動バージョンが0.21.0よりも前であれば、再クロールを促す
            if (UserSettings.LastBootVersion != null && UserSettings.LastBootVersion <= "0.21.0")
            {
                if (Util.Confirm("【バージョンアップに伴うお知らせ】\nver 0.21.0以前のInazuma Searchをお使いいただいていた場合は、不具合により、Inazuma Searchが保持するクロール済み文書情報の一部が破損していた可能性があります。\nこれまでのバージョンで、クロール時や検索時にシステムエラーが多発していた方は、ご迷惑をおかけして申し訳ありませんが、クロール済み文書情報を一度削除していただいた上で、再度のクロール実行をお願いいたします。\n\nInazuma Searchが保持している、クロール済み文書情報を削除してもよろしいですか?\n(文書ファイルや設定情報は削除されません)"))
                {
                    var t = Task.Run(() =>
                    {
                        GM.Truncate(Table.Documents);
                        GM.Truncate(Table.DocumentsIndex);
                        DeleteAllThumbnailFiles();
                    });
                    var f = new ProgressForm(t, "クロール済み文書情報をクリアしています...");
                    f.ShowDialog();

                    Util.ShowInformationMessage("クロール済み文書情報を削除しました。\nお手数ですが、Inazuma Searchの起動後に、もう一度クロールを実行してください。");
                }
                ;
            }

            // サムネイルフォルダが存在しなければ作成
            Directory.CreateDirectory(ThumbnailDirPath);

            // 起動完了時の更新処理(最終起動バージョンの更新、プラグイン構成の保存)
            UserSettings.SaveOnAfterBoot(new Dictionary <string, int>(loadedPluginVersionNumbers));

            // ログ出力
            Logger.Info("アプリケーションを起動しました");

            // 常駐クロールモードがONであれば、クロールを開始する
            if (UserSettings.AlwaysCrawlMode)
            {
                Crawler.StartAlwaysCrawl();
            }

            // 正常起動
            return(true);
        }
Esempio n. 17
0
 private void OnBackgroundProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     ProgressForm.progressBar.Value = e.ProgressPercentage;
     ProgressForm.progressBar.Update();
     ProgressForm.UpdateReadyTotalField();
 }
Esempio n. 18
0
        private void openMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                ProgressForm progFrm = new ProgressForm("Opening");

                ClearState();

                dataGridView.DataSource = null;
                dataSet.Tables[0].BeginLoadData();

                clearMenuItem.PerformClick();

                Thread th = new Thread(new ParameterizedThreadStart(OpenFile));
                th.Start(progFrm);

                progFrm.ShowDialog(this);
            }
        }
Esempio n. 19
0
        private async void btnLoad_Click(object sender, EventArgs e)
        {
            if (btnStart.Enabled == false || btnStop.Enabled == true)
            {
                MessageBox.Show("请先停止抓取!");
                return;
            }


            #region 进度提示窗口设置
            ProgressForm progressForm = new ProgressForm();
            progressForm.Size             = new Size(600, 80);
            progressForm.StartPosition    = FormStartPosition.Manual;
            progressForm.Location         = new Point(this.DesktopLocation.X + this.Width / 2 - progressForm.Size.Width / 2, this.DesktopLocation.Y + this.Height / 2 - progressForm.Size.Height / 2);
            progressForm.FormBorderStyle  = FormBorderStyle.FixedToolWindow;
            progressForm.progress.Maximum = 100;
            progressForm.progress.Minimum = 0;
            progressForm.progress.Value   = 0;
            progressForm.Show(this);
            this.Enabled = false;
            #endregion

            //先清空原来的数据
            dataGridViewTitleURL.Rows.Clear();
            using (StreamReader reader = new StreamReader("TitleUrl.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string title = await reader.ReadLineAsync();

                    string url = await reader.ReadLineAsync();

                    dataGridViewTitleURL.Rows.Add(title, url);
                    dataGridViewTitleURL.Rows[dataGridViewTitleURL.Rows.Count - 2].HeaderCell.Value = (dataGridViewTitleURL.Rows.Count - 1).ToString();

                    //更新进度条
                    if (progressForm.progress.Value < 50)
                    {
                        progressForm.progress.Value++;
                        progressForm.Text = "任务进度:" + progressForm.progress.Value + "%";
                    }
                }
            }

            urls.Clear();
            urlsToBrowse.Clear();
            int numOfTitles = dataGridViewTitleURL.Rows.Count - 1;
            using (StreamReader reader = new StreamReader("Urls.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string url = await reader.ReadLineAsync();

                    urls.Add(url);
                    numOfTitles--;
                    if (numOfTitles < 0)
                    {
                        urlsToBrowse.Enqueue(url);
                    }

                    //更新进度条
                    if (progressForm.progress.Value < 90)
                    {
                        progressForm.progress.Value = progressForm.progress.Value + 1;
                        progressForm.Text           = "任务进度:" + progressForm.progress.Value + "%";
                    }
                }
            }

            if (dataGridViewTitleURL.Rows.Count > 1)
            {
                string temp = dataGridViewTitleURL.Rows[0].Cells[1].Value.ToString();
                txtWebSite.Text = "http://" + temp.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[1];
                websiteCopy     = txtWebSite.Text;
            }

            progressForm.Close();
            MessageBox.Show("载入数据完成!");
            this.Enabled = true;
        }
Esempio n. 20
0
        // filename: .rbproj file in temp
        // location: user selected target location of the project
        protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled)
        {
            string tempDir = Path.GetDirectoryName(fileName);

            // TODO: gem checks should not need a script
            string script      = Path.GetFullPath(Path.Combine(tempDir, "__Gems.rb"));
            bool   isGemLoader = File.Exists(script);

            if (!isGemLoader)
            {
                script = Path.GetFullPath(Path.Combine(tempDir, "__TemplateScript.rb"));
                if (!File.Exists(script))
                {
                    script = null;
                }
            }

            if (script != null)
            {
                IVsOutputWindowPane outputPane = RubyVsUtils.GetOrCreateOutputPane("Project", RubyConstants.ProjectOutputPaneGuid);
                if (outputPane != null)
                {
                    RubyVsUtils.ShowWindow(EnvDTE.Constants.vsWindowKindOutput);
                    outputPane.Activate();
                }

                if (!IronRubyToolsPackage.Instance.RequireIronRubyInstalled(allowCancel: true))
                {
                    canceled = 1;
                    project  = IntPtr.Zero;
                    return;
                }

                var dir       = Path.GetFullPath(Path.Combine(location, ".."));
                var cancelled = new ManualResetEvent(false);

                ProgressForm progressForm = new ProgressForm(10);
                progressForm.Text = isGemLoader ? "Checking required Gems" : "Creating Web Application";
                progressForm.CancellationEvent = cancelled;

                bool success = false;

                progressForm.BackgroundWorker.DoWork += new DoWorkEventHandler((s, e) => {
                    success = RubyStarter.ExecuteScriptFile(script, dir, outputPane, progressForm.BackgroundWorker, cancelled);
                });

                progressForm.BackgroundWorker.RunWorkerAsync();
                progressForm.ShowDialog();

                File.Delete(script);

                if (success)
                {
                    if (!isGemLoader)
                    {
                        try {
                            CopyFilesRecursive(tempDir, location);
                        } catch {
                            Rollback(location);
                            throw;
                        }
                    }
                }
                else
                {
                    Rollback(location);

                    if (progressForm.Cancelled)
                    {
                        outputPane.OutputStringThreadSafe("Cancelled.");
                    }
                    else
                    {
                        MessageBox.Show(
                            "An error occured while creating project. See output window for details.",
                            "Error",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error
                            );
                    }

                    canceled = 1;
                    project  = IntPtr.Zero;
                    return;
                }
            }

            base.CreateProject(fileName, location, name, flags, ref projectGuid, out project, out canceled);
        }
Esempio n. 21
0
        async static public void UploadToGallery()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // validates if file has name (ie saved at least once)
            FileInfo info = new FileInfo(db.Filename);

            if (info.Extension == ".dwt")
            {
                Util.LogError("Please save the drawing before uploading to the gallery, aborting...");
                return;
            }

            var syncContext = SynchronizationContext.Current;

            FileUploadForm fUp = new FileUploadForm();

            fUp.UserName = Util.GetUser();
            fUp.EMail    = Util.GetEmail();

            var dialogResult = Application.ShowModalDialog(fUp);

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

            if (fUp.StoreDetails)
            {
                Util.StoreUserInfo(fUp.UserName, fUp.EMail);
            }

            SynchronizationContext.SetSynchronizationContext(
                syncContext);

            // the gallery bucket
            var bucketKey = "adn-viewer-gallery";

            // Generates unique file key
            string objectKey = Guid.NewGuid().ToString() + ".dwg";

            // Generate temp filename
            string filename = Path.GetTempFileName() + ".dwg";

            db.SaveAs(filename, DwgVersion.Current);

            AdnViewDataClient viewDataClient = new AdnViewDataClient(
                UserSettings.BASE_URL,
                UserSettings.CONSUMER_KEY,
                UserSettings.CONSUMER_SECRET);

            var tokenResult = await viewDataClient.AuthenticateAsync();

            if (!tokenResult.IsOk())
            {
                Util.LogError("Authentication failed: " + tokenResult.Error.Reason);

                System.IO.File.Delete(filename);
                return;
            }

            var fi = FileUploadInfo.CreateFromFile(objectKey, filename);

            var bucketData = new BucketCreationData(
                bucketKey,
                BucketPolicyEnum.kPersistent);

            var response = await viewDataClient.UploadAndRegisterAsync(
                bucketData, fi);

            if (!response.IsOk())
            {
                Util.LogError("Error: " + response.Error.Reason);

                System.IO.File.Delete(filename);
                return;
            }

            if (response is RegisterResponse)
            {
                RegisterResponse registerResponse = response as RegisterResponse;

                if (registerResponse.Result.ToLower() != "success")
                {
                    Util.LogError("Registration failed: " + registerResponse.Result);

                    System.IO.File.Delete(filename);
                    return;
                }

                var modelName = info.Name.Substring(0, info.Name.Length - 4);

                var fileId = viewDataClient.GetFileId(
                    bucketKey,
                    objectKey);

                var dbModel = new DBModel(
                    new Author(fUp.UserName, fUp.EMail),
                    modelName,
                    fileId,
                    fileId.ToBase64());

                AdnGalleryClient galleryClient = new AdnGalleryClient(
                    Util.GetGalleryUrl());

                var modelResponse = await galleryClient.AddModelAsync(
                    dbModel);

                if (!modelResponse.IsOk())
                {
                    Util.LogError("Error: " + modelResponse.Error.ToString());

                    System.IO.File.Delete(filename);
                    return;
                }

                var url = Util.GetGalleryUrl() + "/#/viewer?id=" +
                          modelResponse.Model.Id;

                if (fUp.ShowProgress)
                {
                    var notifier = new TranslationNotifier(
                        viewDataClient,
                        fileId,
                        2000);

                    var fProgress = new ProgressForm(
                        modelName,
                        url,
                        notifier);

                    Application.ShowModelessDialog(fProgress);

                    notifier.OnTranslationCompleted +=
                        OnTranslationCompleted;

                    notifier.Activate();
                }

                ed.WriteMessage("\nYou successfully uploaded a new model to the gallery!");
                ed.WriteMessage("\nYour model is viewable at the following url:");

                ed.WriteMessage("\n" + url + "\n");

                System.IO.File.Delete(filename);
            }
        }
Esempio n. 22
0
        public bool OpenRepository(string path, IRepositoryProvider repositoryProvider)
        {
            if (_currentProvider != repositoryProvider)
            {
                CloseRepository();
                _currentProvider = repositoryProvider;
            }
            else
            {
                DetachRepository();
                foreach (var gui in _additionalGui)
                {
                    gui.DetachFromEnvironment(this);
                }
                _additionalGui.Clear();
                _activeIssueTrackerProviders.Clear();
            }

            try
            {
                _repository = null;
                _repository = ProgressForm.MonitorTaskAsModalWindow(
                    this,
                    Resources.StrLoadingRepository,
                    (p, c) => _currentProvider.OpenRepositoryAsync(path, p, c));
            }
            catch (OperationCanceledException)
            {
                return(false);
            }
            catch (Exception exc)
            {
                if (exc.IsCritical())
                {
                    throw;
                }
                GitterApplication.MessageBoxService.Show(
                    this,
                    exc.Message,
                    Resources.ErrFailedToOpenRepository,
                    MessageBoxButton.Close,
                    MessageBoxIcon.Error);
            }
            if (_repository == null)
            {
                return(false);
            }
            _repository.Deleted += OnRepositoryDeleted;
            if (_repositoryGui != null)
            {
                _repositoryGui.Repository = _repository;
            }
            else
            {
                _repositoryGui            = _currentProvider.GuiProvider;
                _repositoryGui.Repository = _repository;
                LoadGuiView(_repositoryGui);
                _repositoryGui.AttachToEnvironment(this);
            }
            _repositoryGui.ActivateDefaultView();

            Text = _repository.WorkingDirectory + " - " + Application.ProductName;

            repositoryProvider.OnRepositoryLoaded(_repository);

            OpenIssueTrackers();

            return(true);
        }
Esempio n. 23
0
		public void ConvertBitmapTo8Bpp(int correction)
		{
			//  this method is the only one that sometimes needs a long time;
			//  therefore Juergen Thomas added a progress form as standard,
			//  but shows it only for larger bitmaps
			using(ProgressForm progress = new ProgressForm(ctrl)) {
				if (bmp.Width * bmp.Height >= 40000)
					progress.Show();
				//  variables used instead of timer
				DateTime now;
				TimeSpan diff;

				Bitmap Result = new Bitmap( bmp.Width, bmp.Height,
					PixelFormat.Format8bppIndexed );

				BitmapData ResultData
					= Result.LockBits(
						new Rectangle(0, 0, bmp.Width, bmp.Height),
						ImageLockMode.ReadWrite,
						PixelFormat.Format8bppIndexed);

				int tmpStride = ResultData.Stride;
				IntPtr ptr = ResultData.Scan0;

				Hashtable ColorReduction = new Hashtable();
				byte offset = 39;
				for (int r = 0; r < 256; r += 51)
					for (int g = 0; g < 256; g += 51)
						for (int b = 0; b < 256; b += 51)
						{
							ColorReduction[Color.FromArgb(r, b, g)] = ++offset;
						}

				int tmpBytes = bmp.Height * tmpStride;
				byte[] tmpBitmapData = new byte[tmpBytes];

				now = DateTime.Now;
				for (int x = 0; x < bmp.Width; x++)
				{
					//  check if progress should be actualized (after 600 msec)
					diff = DateTime.Now - now;
					if (progress.Visible && (diff.Ticks > 6000000)) {
						progress.Progressing(x);
						now = DateTime.Now;
					}

					for (int y = 0; y < bmp.Height; y++)
					{
						int offset2 = (y * tmpStride) + x;
						//  get a suitable 8 bit color to the current 24 bit pixel
						Color col = ConvertColorTo8Bpp(bmp.GetPixel(x,y), correction);
						//  set this color as color resp. grayscale
						if (format8bitPixel == ColorDepthReduction.Colored8bpp)
							tmpBitmapData[offset2]
								= (byte)( col.R*0.3 + col.G*0.59 + col.B*0.11 );
						else
							tmpBitmapData[offset2]
								= (byte)ColorReduction[col];
					}
				}

				System.Runtime.InteropServices.Marshal.Copy(tmpBitmapData, 0, ptr, tmpBytes);

				Result.UnlockBits(ResultData);

				progress.Hide();

				//  change the formprint bitmap
				bmp.Dispose();
				bmp = Result;
			}
		}
Esempio n. 24
0
	//
	// invokeFileSyncHandlerDirectlyButton_Click
	//
	// Perform a file synchronization directly.
	//
	// Parameters:
	//  sender - The source Button object for this event.
	//  e - The EventArgs object that contains the event data.
	//
	private void invokeFileSyncHandlerDirectlyButton_Click(object sender, System.EventArgs e)
	{
		hresultLabel.Text = "";
		try
		{
			SynrcSync fileSync = new SynrcSync();
			//fileSync.InvokeDirectly = true;
			fileSync.syncStatus += new SynrcSync.SyncStatusDelegate(OnFileSyncStatus);
			fileSync.syncError += new SynrcSync.SyncErrorDelegate(OnSyncError);
			progressForm = new ProgressForm();
			progressForm.Show();
			int retval = 0;// fileSync.Sync();
			hresultLabel.Text = "HRESULT is 0x" + retval.ToString("x");
		}
		catch (Exception ex)
		{
			MessageBox.Show("Exception from invocation: " + ex.Message);
			if (progressForm != null)
			{
				progressForm.Close();
			}
		}
	}
Esempio n. 25
0
 public ProjectRunner(string taskName)
 {
     this.TaskName      = taskName;
     _progressForm      = new ProgressForm();
     _progressForm.Text = taskName;
 }
Esempio n. 26
0
        // Cite the selected items
        private void btnCite_Click(object sender, EventArgs e)
        {
            try
            {
                ParameterizedThreadStart threadStart = new ParameterizedThreadStart(formatter.InsertCitationsInThread);
                masterThread = new Thread(threadStart);
                masterThread.Name = "insertingcitations";
                List<ItemMasterRow> listSelectedItems = new List<ItemMasterRow>();
                foreach (ItemMasterRow item in listItems.SelectedObjects)
                {
                    listSelectedItems.Add(item);
                }
                Dictionary<string, object> data = new Dictionary<string, object>();
                data["Control"] = this;
                data["ListItems"] = listSelectedItems;
                if (currentSearchOption != SearchOptions.Filter)
                    data["FromSearch"] = 1;

                masterThread.Start(data);
                progress = new ProgressForm(Lang.en_US.Progress_InsertCitation_Title, Lang.en_US.Progress_InsertCitation_Msg, true);
                progress.FormClosed += new FormClosedEventHandler(this.progress_FormClosed);
                progress.ShowDialog();
            }
            catch (Exception ex)
            {
                this.log.WriteLine(LogType.Error, "MasterControl::btnCite_Click", ex.ToString());
            }
        }
Esempio n. 27
0
        internal void ParameterDispatcher()
        {
            CategorySet catSet = Utils.AssignableCategories(uiapp, doc);

            if (num > 0)
            {
                projectParameters = Parameters.ProjectData(num);
            }
            else
            {
                projectParameters = Parameters.ProjectData();
            }
            int catCounter = 0;

            // For each Category
            foreach (Category cat in catSet)
            {
                catCounter++;
                IList <Element> isntanceCollector = new FilteredElementCollector(doc).OfCategoryId(cat.Id).WhereElementIsNotElementType().ToElements();
                if (isntanceCollector.Count < 1)
                {
                    continue;
                }

                HashSet <string> unique = new HashSet <string>();

                string catName = cat.Name;

                int    n       = isntanceCollector.Count;
                string s       = "{0} of " + n.ToString() + String.Format(" elements of {0} category processed... .{1}/{2} cat.", catName, catCounter.ToString(), catSet.Size.ToString());
                string caption = "Exporting..";

                using (ProgressForm pf = new ProgressForm(caption, s, n))
                {
                    // For each element
                    foreach (Element el in isntanceCollector)
                    {
                        try
                        {
                            if (pf.getAbortFlag())
                            {
                                return;
                            }
                            pf.Increment();
                            List <string> elParameters = new List <string>();
                            Element       type         = doc.GetElement(el.GetTypeId());

                            if (num > 0)
                            {
                                elParameters.Add(el.UniqueId.ToString());
                            }

                            foreach (Tuple <string, string> tuple in projectParameters)
                            {
                                if (tuple.Item2.Equals("Instance"))
                                {
                                    Parameter p           = el.LookupParameter(tuple.Item1);
                                    string    emptyString = "  ";
                                    if (p != null && p.HasValue && !String.IsNullOrEmpty(p.AsString()))
                                    {
                                        emptyString = p.AsString();
                                    }
                                    elParameters.Add(emptyString);
                                }
                                else
                                {
                                    if (type == null)
                                    {
                                        elParameters.Add("No Type");
                                        continue;
                                    }
                                    Parameter p           = type.LookupParameter(tuple.Item1);
                                    string    emptyString = "  ";
                                    if (p != null && p.HasValue)
                                    {
                                        emptyString = p.AsString();
                                    }
                                    elParameters.Add(emptyString);
                                }
                            }
                            if (type == null)
                            {
                                elParameters.Add("No Type");
                            }
                            else
                            {
                                elParameters.Add(type.Name);
                            }
                            if (num > 0)
                            {
                                elParameters.Add(catName);
                                projectData.Add(elParameters);
                            }
                            if (num == 0)
                            {
                                if (unique.Add(elParameters.Aggregate((i, j) => i + "," + j)))
                                {
                                    projectData.Add(elParameters);
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }
Esempio n. 28
0
 // Refresh the references in the current document
 private void btnRefresh_Click(object sender, EventArgs e)
 {
     try
     {
         ParameterizedThreadStart threadStart = new ParameterizedThreadStart(formatter.RefreshCitationsInThread);
         masterThread = new Thread(threadStart);
         masterThread.Name = "refreshingcitations";
         masterThread.Start(this);
         progress = new ProgressForm(Lang.en_US.Progress_RefreshCitation_Title, Lang.en_US.Progress_RefreshCitation_Msg, true);
         progress.FormClosed += new FormClosedEventHandler(progress_FormClosed);
         progress.ShowDialog();
     }
     catch(Exception ex)
     {
         log.WriteLine(LogType.Error, "MasterControl::btnRefList_Click", ex.ToString());
     }
 }
Esempio n. 29
0
        /// <summary>
        /// Updates the list view.
        /// </summary>
        private void UpdateListView()
        {
            ProgressForm prForm = new ProgressForm();

            ThreadPool.QueueUserWorkItem(new WaitCallback(DoUpdateListView), prForm);

            prForm.ShowDialog(this);
        }
Esempio n. 30
0
 void Show()
 {
    m_SplashForm = new ProgressForm(m_SplashImage);
    m_SplashForm.Location = m_Location;
    m_FromCreated.Set();
    m_SplashForm.ShowDialog();
 }
Esempio n. 31
0
 private void ShowProgressForm()
 {
     ProgressForm.Show();
 }
Esempio n. 32
0
        private void btn网上导入_Click(object sender, EventArgs e)
        {
            string tdh = (string)(pnl提单号.Controls[0] as IWindowDataControl).SelectedDataValue;
            string hc  = (string)(pnl船名.Controls[0] as IWindowDataControl).SelectedDataValue;

            if (string.IsNullOrEmpty(tdh))
            {
                MessageForm.ShowWarning("请填写提单号!");
                return;
            }

            if (!string.IsNullOrEmpty(hc) && hc.Contains('/'))
            {
                hc = hc.Substring(hc.LastIndexOf('/') + 1).Trim();
            }

            IList <Hd.NetRead.集装箱数据> boxList = null;
            int piao_successCount            = 0; //成功导入的票数量
            int rw_successCount = 0;              //成功导入的任务数量

            ProgressForm progressForm = new ProgressForm();

            progressForm.Start(this, "网上导入");

            Feng.Async.AsyncHelper asyncHelper = new Feng.Async.AsyncHelper(
                new Feng.Async.AsyncHelper.DoWork(delegate()
            {
                nbeportRead m_nbeportGrab = new nbeportRead();
                m_nbeportGrab.SetLoginInfo(Feng.DBDef.Instance.TryGetValue("NetReadUserName"),
                                           Feng.DBDef.Instance.TryGetValue("NetReadPassword"));

                if (string.IsNullOrEmpty(hc))
                {
                    boxList = m_nbeportGrab.查询集装箱数据(ImportExportType.进口集装箱, tdh);
                }
                else
                {
                    boxList = m_nbeportGrab.查询集装箱数据(ImportExportType.进口集装箱, tdh, hc);
                }

                if (boxList != null && boxList.Count > 0)
                {
                    AskToReplace(m_cm, "任务性质", 任务性质.进口拆箱);
                    AskToReplace(m_cm, "提单号", boxList[0].提单号);
                    AskToReplace(m_cm, "船名航次", boxList[0].船名 + "/" + boxList[0].航次);
                    piao_successCount++;

                    foreach (集装箱数据 jzx in boxList)
                    {
                        bool have = false;
                        foreach (Xceed.Grid.DataRow row in m_显示区Grid.DataRows)
                        {
                            if (row.Cells["箱号"].Value != null && row.Cells["箱号"].Value.ToString().Trim() == jzx.集装箱号.Trim())
                            {
                                have = true;
                                break;
                            }
                        }
                        if (!have)
                        {
                            任务 rw    = new 任务();
                            rw.任务来源  = 任务来源.网上;
                            rw.任务性质  = 任务性质.进口拆箱;
                            rw.提箱点编号 = NameValueMappingCollection.Instance.FindIdFromName("人员单位_全部", jzx.堆场区).ToString();
                            rw.箱号    = jzx.集装箱号;
                            rw.船名    = jzx.船名;
                            rw.航次    = jzx.航次;
                            m_cm2.AddNew();
                            m_cm2.DisplayManager.Items[m_cm2.DisplayManager.Position] = rw;
                            m_cm2.EndEdit();
                            rw_successCount++;
                        }
                    }
                }
                return(null);
            }),
                new Feng.Async.AsyncHelper.WorkDone(delegate(object result)
            {
                MessageForm.ShowInfo("成功导入 " + piao_successCount + " 票," + rw_successCount + " 条任务。");
                progressForm.Stop();
            }));
        }
Esempio n. 33
0
        private void newCaptureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Capture.ChooseForm frm = new Capture.ChooseForm();

            Process[] processes = frm.GetSelectedProcesses();
            if (processes.Length == 0)
                return;

            ProgressForm progFrm = new ProgressForm("Starting capture");

            captureMgr.StartCapture(processes, progFrm);

            if (progFrm.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show(String.Format("Failed to start capture: {0}", progFrm.GetOperationErrorMessage()),
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Capture.ProgressForm capProgFrm = new Capture.ProgressForm(captureMgr);
            capProgFrm.ShowDialog();

            progFrm = new ProgressForm("Stopping capture");

            captureMgr.StopCapture(progFrm);

            if (progFrm.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show(String.Format("Failed to stop capture: {0}", progFrm.GetOperationErrorMessage()),
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                captureMgr.SaveCapture(saveFileDialog.FileName);
            }
            else
            {
                captureMgr.DiscardCapture();
            }

            #if false
            tmpEventList.Clear();
            tmpPacketList.Clear();

            captureStartMenuItem.Enabled = false;

            object source = dataGridView.DataSource;
            dataGridView.DataSource = null;

            CaptureForm frm = new CaptureForm(listener, swForm.GetRules());
            frm.ShowDialog(this);

            dataGridView.DataSource = null;

            ProgressForm progFrm = new ProgressForm("Analyzing data");

            Thread th = new Thread(new ParameterizedThreadStart(DoPostAnalysis));
            th.Start(progFrm);

            progFrm.ShowDialog(this);
            #endif
        }
 private void Form_Loaded(object sender, EventArgs e)
 {
     staticRef = this;
 }
Esempio n. 35
0
 private void tryggveToolStripMenuItem_Click(object sender, EventArgs e)
 {
     oSpy.Capture.Converter conv = new oSpy.Capture.Converter();
     ProgressForm prog = new ProgressForm("Woot");
     conv.ConvertAll("C:\\Users\\Ole André\\AppData\\Local\\Temp\\gatqxqhw.wvc", 206, prog);
     prog.ShowDialog();
 }
Esempio n. 36
0
        /// <summary>
        /// Save Files attached to query
        /// </summary>
        /// <param name="doc">Document object </param>
        private void Savefile(Document doc)
        {
            saveFileDialog.FileName = Path.GetFileName(doc.Filename);

            if (doc.Filename.EndsWith("xml", StringComparison.OrdinalIgnoreCase))
            {
                saveFileDialog.FilterIndex = 2;
            }
            else if (!doc.Filename.EndsWith("txt", StringComparison.OrdinalIgnoreCase))
            {
                string fileExtension = Path.GetExtension(doc.Filename);
                if (fileExtension.NullOrEmpty())
                {
                    if (!doc.MimeType.NullOrEmpty() && doc.MimeType.IndexOf("/") >= 0)
                    {
                        fileExtension         = "." + doc.MimeType.Substring(doc.MimeType.IndexOf('/') + 1);
                        saveFileDialog.Filter = string.Format("{1} files (*{0})|*{0}|{2}", fileExtension, fileExtension.Substring(1, 1).ToUpper() + fileExtension.Substring(2), saveFileDialog.Filter);
                    }
                }
                else
                {
                    saveFileDialog.Filter = string.Format("{1} files (*{0})|*{0}|{2}", fileExtension, fileExtension.Substring(1, 1).ToUpper() + fileExtension.Substring(2), saveFileDialog.Filter);
                }
            }

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var sSaveLocation = saveFileDialog.FileName;

            var progress = new ProgressForm("Saving File", "Transferring the File from the Portal...")
            {
                Indeteminate = doc.Size <= 0
            };

            byte[] buffer = new byte[0x100000];
            Observable.Using(() => File.Create(sSaveLocation),
                             outStream =>
                             Observable.Using(() =>
            {
                Stream dcStream;
                if (isRequestView == true)
                {
                    if (doc.MimeType != "application/vnd.pmn.lnk")
                    {
                        dcStream = new DocumentChunkStream(Guid.Parse(doc.DocumentID), networkSetting);
                    }
                    else
                    {
                        string lnk = string.Empty;
                        using (var docStream = new DocumentChunkStream(Guid.Parse(doc.DocumentID), networkSetting))
                        {
                            lnk = new StreamReader(docStream).ReadToEnd();
                            docStream.Close();
                        }
                        if (networkSetting.SftpClient == null)
                        {
                            networkSetting.SftpClient = new SFTPClient(networkSetting.Host, networkSetting.Port, networkSetting.Username, networkSetting.DecryptedPassword);
                        }
                        dcStream = networkSetting.SftpClient.FileStream(lnk);
                    }
                }
                else
                {
                    if (_cache != null && _cache.Enabled)
                    {
                        dcStream = _cache.GetDocumentStream(Guid.Parse(doc.DocumentID));
                    }
                    else
                    {
                        processor.ResponseDocument(requestId, doc.DocumentID, out dcStream, 60000);
                    }
                }
                return(dcStream);
            },
                                              inStream =>
                                              Observable.Return(0, Scheduler.Default).Repeat()
                                              .Select(_ => inStream.Read(buffer, 0, buffer.Length))
                                              .TakeWhile(bytesRead => bytesRead > 0)
                                              .Do(bytesRead => outStream.Write(buffer, 0, bytesRead))
                                              .Scan(0, (totalTransferred, bytesRead) => totalTransferred + bytesRead)
                                              .ObserveOn(this)
                                              //.Do(totalTransferred => progress.Progress = totalTransferred * 100 / Math.Max(doc.Size, 1))
                                              .Do(totalTransferred => progress.Progress = totalTransferred * 100 / Math.Max((inStream.CanSeek ? (int)inStream.Length : doc.Size), 1))
                                              )
                             )
            .SubscribeOn(Scheduler.Default)
            .TakeUntil(progress.ShowAndWaitForCancel(this))
            .ObserveOn(this)
            .Finally(progress.Dispose)
            .LogExceptions(log.Error)
            .Do(_ => {},
                ex => { MessageBox.Show(this, "There was an error saving the file: \r\n\r\n" + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); },
                () => { MessageBox.Show(this, "File downloaded successfully", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); })
            .Catch()
            .Subscribe();
        }
Esempio n. 37
0
 private void bExtract_Click(object sender, EventArgs e)
 {
   if (lvFiles.SelectedItems.Count == 0)
   {
     return;
   }
   if (lvFiles.SelectedItems.Count == 1)
   {
     var fe = (BSAFileEntry) lvFiles.SelectedItems[0].Tag;
     SaveSingleDialog.FileName = fe.FileName;
     if (SaveSingleDialog.ShowDialog() == DialogResult.OK)
     {
       fe.Extract(SaveSingleDialog.FileName, false, br, ContainsFileNameBlobs);
       SaveSingleDialog.InitialDirectory = Path.GetDirectoryName(SaveSingleDialog.FileName);
     }
   }
   else
   {
     if (SaveAllDialog.ShowDialog() == DialogResult.OK)
     {
       var pf = new ProgressForm(false);
       pf.Text = "Unpacking archive";
       pf.EnableCancel();
       pf.SetProgressRange(lvFiles.SelectedItems.Count);
       pf.Show();
       var count = 0;
       try
       {
         foreach (ListViewItem lvi in lvFiles.SelectedItems)
         {
           var fe = (BSAFileEntry) lvi.Tag;
           fe.Extract(SaveAllDialog.SelectedPath, true, br, ContainsFileNameBlobs);
           pf.UpdateProgress(count++);
           Application.DoEvents();
         }
       }
       catch (fommException)
       {
         MessageBox.Show("Operation cancelled", "Message");
       }
       catch (Exception ex)
       {
         MessageBox.Show(ex.Message, "Error");
       }
       pf.Unblock();
       pf.Close();
     }
   }
 }
Esempio n. 38
0
 private void UpdateProgressForm(object sender, ISortParams e)
 {
     ProgressForm.progressBar.Maximum = Service.Tasks.Count;
     ProgressForm.progressBar.Update();
     ProgressForm.UpdateReadyTotalField();
 }
Esempio n. 39
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            //需要替换的申报包列表
            List <string> importList         = new List <string>();
            List <string> importFileNameList = new List <string>();

            #region 查的需要导入的路径
            foreach (TreeNode tn in tlTestA.Nodes)
            {
                //判断是否被选中
                if (tn.Checked)
                {
                    //读取目录名称中的项目编号
                    string projectNumber = tn.Text + "-00";

                    //判断是否需要替换
                    if (replaceDict.ContainsKey(projectNumber))
                    {
                        //需要替换

                        //判断是否替换这个项目
                        if (replaceDict[projectNumber])
                        {
                            //需要替换,添加到ImportList列表中
                            importList.Add(Path.Combine(tn.Name, ""));
                            importFileNameList.Add(tn.Text);
                        }
                        else
                        {
                            //不需要替换
                            continue;
                        }
                    }
                    else
                    {
                        //不需要替换
                        importList.Add(Path.Combine(tn.Name, ""));
                        importFileNameList.Add(tn.Text);
                    }
                }
            }
            #endregion

            //开始导入
            ProgressForm pf = new ProgressForm();
            pf.Show();
            pf.run(importList.Count, 0, new EventHandler(delegate(object senders, EventArgs ee)
            {
                //进度数值
                int progressVal = 0;
                int index       = -1;
                //导入
                foreach (string pDir in importList)
                {
                    try
                    {
                        progressVal++;
                        index++;
                        //申报文件名
                        string createFileName     = importFileNameList[index].ToString();
                        string tempname           = createFileName.Substring(0, createFileName.IndexOf("-", 5));
                        List <string> messageList = null;
                        pf.reportProgress(progressVal, createFileName + "_开始解压");
                        bool returnContent = unZipFile(pDir, createFileName, out messageList);
                        if (returnContent)
                        {
                            //报告进度
                            pf.reportProgress(progressVal, createFileName + "_开始导入");
                            MainForm.writeLog("开始导入__" + createFileName);

                            //导入数据库
                            new DBImporter().addOrReplaceProject(createFileName + "-00", Path.Combine(Path.Combine(decompressDir, createFileName), "static.db"));

                            //报告进度
                            pf.reportProgress(progressVal, createFileName + "_结束导入");
                            MainForm.writeLog("结束导入__" + createFileName);
                        }
                        pf.reportProgress(progressVal, createFileName + "_结束解压");
                    }
                    catch (Exception ex)
                    {
                        MainForm.writeLog(ex.ToString());
                    }
                }

                //检查是否已创建句柄,并调用委托执行UI方法
                if (pf.IsHandleCreated)
                {
                    pf.Invoke(new MethodInvoker(delegate()
                    {
                        try
                        {
                            //刷新综合查询
                            if (MainForm.ModuleDict.ContainsKey(MainForm.allCheckKey))
                            {
                                ((PublicManager.Modules.DataCheck.AllCheck.ModuleController2)MainForm.ModuleDict[MainForm.allCheckKey]).reloadData();
                            }

                            //刷新Catalog列表
                            mainView.updateCatalogs();

                            //关闭进度窗口
                            pf.Close();

                            //关闭窗口
                            Close();
                        }
                        catch (Exception ex)
                        {
                            MainForm.writeLog(ex.ToString());
                        }
                    }));
                }
                else
                {
                    //关闭窗口
                    Close();
                }
            }));
        }
Esempio n. 40
0
        public void Run(List <Manifest.Entry> Entries, string DestinationFolder)
        {
            // Setup progress UI...
            Progress      = new ProgressForm();
            Progress.Text = "Extracting archived files";
            Progress.OverallProgressBar.Maximum = 10000;
            Progress.OverallProgressBar.Minimum = 0;
            Progress.OverallProgressBar.Value   = 0;
            Progress.CancelPrompt = "Are you sure you wish to cancel this extraction operation?";
            Progress.Show();

            try
            {
                System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.BelowNormal;

                ZippyForm.LogWriteLine(LogLevel.Information, "Starting extraction from project " + Project.Name + " of " + Entries.Count + " files and folders to destination folder '" + DestinationFolder + "'.");

                /** Operate on a single zip file at a time.  This requires planning which files are
                 *  coming from where.  Also, we count how many total bytes we'll be extracting.  **/
                Progress.label1.Text = "Identifying required archive files...";
                List <ArchiveFilename> ArchivesRequired = new List <ArchiveFilename>();
                foreach (Manifest.Entry Entry in Entries)
                {
                    IdentifyRequiredArchives(ArchivesRequired, Entry);
                }

                // Then, begin actual extraction...
                foreach (ArchiveFilename Archive in ArchivesRequired)
                {
                    ZippyForm.LogWriteLine(LogLevel.LightDebug, "Starting extractions from archive '" + Archive.ToString() + "'.");
                    Progress.label1.Text = "Extracting from archive:  " + Archive.ToString();
                    for (; ;)
                    {
                        try
                        {
                            using (ZipFile zip = ZipFile.Read(Project.CompleteBackupFolder + "\\" + Archive.ToString()))
                            {
                                zip.ZipError        += new EventHandler <ZipErrorEventArgs>(OnZipError);
                                zip.ExtractProgress += new EventHandler <ExtractProgressEventArgs>(OnZipExtractProgress);
                                foreach (Manifest.Entry Entry in Entries)
                                {
                                    ZippyForm.LogWriteLine(LogLevel.HeavyDebug, "Extracting '" + Entry.RelativePath + "'.");
                                    RunEntry(zip, Archive, Entry, Utility.StripTrailingSlash(DestinationFolder));
                                }
                            }
                            break;
                        }
                        catch (Ionic.Zip.ZipException ze)
                        {
                            ZippyForm.LogWriteLine(LogLevel.Information, "Zip error during extraction from archive '" + Archive.ToString() + "': " + ze.Message);
                            ZippyForm.LogWriteLine(LogLevel.LightDebug, "Detailed error: " + ze.ToString());

                            StringBuilder Msg = new StringBuilder();
                            Msg.Append("Error extracting from archive '" + Archive.ToString() + "': " + ze.Message);
                            if (Entries.Count < 15)
                            {
                                Msg.AppendLine();
                                Msg.AppendLine("The following entries to be restored are affected:");
                                foreach (Manifest.Entry Entry in Entries)
                                {
                                    if (Entry is Manifest.File)
                                    {
                                        Msg.AppendLine(Entry.Name);
                                    }
                                    if (Entry is Manifest.Folder)
                                    {
                                        Msg.AppendLine(Entry.Name + " folder");
                                    }
                                }
                            }
                            else
                            {
                                Msg.Append("  More than 15 files to be restored are affected.");
                            }
                            switch (MessageBox.Show(Msg.ToString(), "Error", MessageBoxButtons.AbortRetryIgnore))
                            {
                            case DialogResult.Abort: throw new CancelException();

                            case DialogResult.Retry: continue;

                            case DialogResult.Ignore: break;

                            default: throw new NotSupportedException();
                            }
                        }
                    }
                }

                ZippyForm.LogWriteLine(LogLevel.Information, "Extraction operation completed.");
            }
            catch (CancelException ex)
            {
                ZippyForm.LogWriteLine(LogLevel.Information, "Extraction operation canceled.");
                throw ex;
            }
            finally
            {
                Progress.Dispose();
                Progress = null;

                System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.Normal;
            }
        }
Esempio n. 41
0
        private void _miWiaAcquire_Click(object sender, System.EventArgs e)
        {
            WiaAcquireFlags flags        = WiaAcquireFlags.None;
            bool            showProgress = true;

            _progressDlg = new ProgressForm(DemosGlobalization.GetResxString(GetType(), "Resx_Transferring"), "", 100);

            _wiaAcquiring = true;

            if (_showUserInterface)
            {
                flags = WiaAcquireFlags.UseCommonUI | WiaAcquireFlags.ShowUserInterface;
            }
            else
            {
                // Check if the selected device is scanner and that it has multiple sources (Feeder & Flatbed)
                // then show the select source dialog box.
                if (SelectAcquireSource() != DialogResult.OK)
                {
                    _wiaAcquiring = false;
                    return;
                }
            }

            if (_showUserInterface)
            {
                if (_wiaVersion == WiaVersion.Version2)
                {
                    showProgress = false;
                }
            }

            if (showProgress)
            {
                // Show the progress dialog.
                _progressDlg.Show(this);
            }

            try
            {
                _wiaSession.AcquireOptions = _wiaAcquireOptions;

                if (_wiaProperties.DataTransfer.TransferMode == WiaTransferMode.None) // GetProperties() method not called yet.
                {
                    _transferMode = WiaTransferMode.Memory;
                }
                else
                {
                    _transferMode = _wiaProperties.DataTransfer.TransferMode;
                }

                // Disable the minimize and maximize buttons.
                this.MinimizeBox = false;
                this.MaximizeBox = false;

#if !LEADTOOLS_V19_OR_LATER
                DialogResult dialogResult = _wiaSession.Acquire(this, _sourceItem, flags);
#else
                DialogResult dialogResult = _wiaSession.Acquire(this.Handle, _sourceItem, flags);
#endif // #if !LEADTOOLS_V19_OR_LATER
                if (dialogResult != DialogResult.OK)
                {
                    return;
                }

                // Enable back the minimize and maximize buttons.
                this.MinimizeBox = true;
                this.MaximizeBox = true;

                if (_progressDlg.Visible)
                {
                    if (!_progressDlg.Abort)
                    {
                        _progressDlg.Dispose();
                    }
                }

                if (_sourceItem != null)
                {
                    _sourceItem = null;
                }

                if (_wiaSession.FilesCount > 0) // This property indicates how many files where saved when the transfer mode is File mode.
                {
                    string strMsg = DemosGlobalization.GetResxString(GetType(), "Resx_PagesSavedTo") + "\n\n";
                    if (_wiaSession.FilesPaths.Count > 0)
                    {
                        for (int i = 0; i < _wiaSession.FilesPaths.Count; i++)
                        {
                            string strTemp = string.Format("{0}\n", _wiaSession.FilesPaths[i]);
                            strMsg += strTemp;
                        }
                        MessageBox.Show(this, strMsg, DemosGlobalization.GetResxString(GetType(), "Resx_FileTransfer"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    // WIA 2.0 sometimes doesn't return the acquired files count and paths, so this message will show
                    // the directory where the saved files were saved.
                    if (_wiaVersion == WiaVersion.Version2)
                    {
                        int    len = _wiaAcquireOptions.FileName.LastIndexOf('\\');
                        string strFilesDirectory = _wiaAcquireOptions.FileName.Substring(0, len);
                        string strMsg            = string.Format(DemosGlobalization.GetResxString(GetType(), "Resx_PagesSavedTo") + "\n\n{0}", strFilesDirectory);
                        MessageBox.Show(this, strMsg, DemosGlobalization.GetResxString(GetType(), "Resx_FileTransfer"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                _wiaAcquiring = false;
            }
            catch (Exception ex)
            {
                // Enable back the minimize and maximize buttons.
                this.MinimizeBox = true;
                this.MaximizeBox = true;

                _wiaAcquiring = false;
                if (_progressDlg.Visible)
                {
                    if (!_progressDlg.Abort)
                    {
                        _progressDlg.Dispose();
                    }
                }

                Messager.ShowError(this, ex);
            }
            finally
            {
                // Enable back the minimize and maximize buttons.
                this.MinimizeBox = true;
                this.MaximizeBox = true;

                _wiaAcquiring = false;
            }
        }
 private void CloseProgressBar()
 {
     _progress?.Close();
     _progress?.Dispose();
     _progress = null;
 }
Esempio n. 43
0
        public static GuiCommandStatus FormatPatch(IWin32Window parent, IRevisionPointer revision)
        {
            Verify.Argument.IsNotNull(revision, nameof(revision));

            const string patchExt   = ".patch";
            string       outputPath = null;

            using (var dlg = new SaveFileDialog()
            {
                FileName = revision.Pointer + patchExt,
                Filter = Resources.StrPatches + "|" + patchExt,
                DefaultExt = patchExt,
                OverwritePrompt = true,
                Title = Resources.StrSavePatch,
            })
            {
                if (dlg.ShowDialog(parent) == DialogResult.OK)
                {
                    outputPath = dlg.FileName;
                }
                else
                {
                    return(GuiCommandStatus.Canceled);
                }
            }
            if (string.IsNullOrWhiteSpace(outputPath))
            {
                return(GuiCommandStatus.Canceled);
            }
            byte[] patch;
            try
            {
                patch = ProgressForm.MonitorTaskAsModalWindow(parent,
                                                              Resources.StrSavePatch, revision.FormatPatchAsync);
            }
            catch (OperationCanceledException)
            {
                return(GuiCommandStatus.Canceled);
            }
            catch (GitException exc)
            {
                GitterApplication.MessageBoxService.Show(
                    parent,
                    exc.Message,
                    Resources.ErrFailedToFormatPatch,
                    MessageBoxButton.Close,
                    MessageBoxIcon.Error);
                return(GuiCommandStatus.Faulted);
            }
            if (patch != null)
            {
                try
                {
                    File.WriteAllBytes(outputPath, patch);
                    return(GuiCommandStatus.Completed);
                }
                catch (Exception exc) when(!exc.IsCritical())
                {
                    GitterApplication.MessageBoxService.Show(
                        parent,
                        exc.Message,
                        Resources.ErrFailedToSavePatch,
                        MessageBoxButton.Close,
                        MessageBoxIcon.Error);
                    return(GuiCommandStatus.Faulted);
                }
            }
            return(GuiCommandStatus.Faulted);
        }
Esempio n. 44
0
        //##################    Scaning gog.com for games owned    ##################

        private async void GetGames()
        {
            platforms = new Dictionary <int, string>();

            int i = 0;

            foreach (IPlatform platform in PluginHelper.DataManager.GetAllPlatforms())
            {
                platforms.Add(i, platform.Name);
                i++;
            }

            // if platforms changed reset
            if (platform == null || !platforms[platformNo].Equals(platform))
            {
                platformNo = 0;
                platform   = platforms[platformNo];
            }

            ImportOptions options = new ImportOptions(this);

            options.Show();
            await options.ok.Task;

            options.Close();
            this.skipByTitle  = options.skipByTitle;
            this.skipImported = options.skipImported;
            this.mode         = options.mode;
            this.galaxyPath   = options.galaxyPath;
            this.platformNo   = options.platformNo;
            this.platform     = platforms[platformNo];
            options.Dispose();

            await Scan_Library();

            ProgressForm progressForm = new ProgressForm("Collecting Game Information");

            progressForm.Show();
            await progressForm.ShowProgress(GetGames_doWork);

            progressForm.Close();
            progressForm.Dispose();

            if (errorForm != null)
            {
                errorForm.Show();
                await errorForm.ok.Task;
                errorForm.Dispose();
            }

            if (gamesFound != null || gamesFound.Count > 0)
            {
                gamesFound.Sort((x1, x2) => x1.title.CompareTo(x2.title));

                if (mode.Equals(Mode.startWithGalaxy))
                {
                    GameImportForm importForm = new GameImportForm(this);
                    importForm.Show();
                }
                else if (mode.Equals(Mode.linkToDownload))
                {
                    GameImportForm2 importForm = new GameImportForm2(this);
                    importForm.Show();
                }
            }

            webClient.Dispose();
        }
Esempio n. 45
0
        private void RetrieveDataFromFTPServer()
        {
            FtpWebRequest ftpRequest;
            FtpWebResponse ftpResponse;

            xDoc = new XmlDocument();

            ProgressForm formPB = new ProgressForm();
            formPB.Show();

            try
            {
                formPB.Text = "Downloading Database";
                formPB.Value = 0;
                formPB.Refresh();

                #region Attempt to download plugin database file
                try
                {
                    // Create a request for the database file
                    ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPdbFile);
                    // Set default authentication for retrieving the file info
                    ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);

                    ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
                    ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                    // Ask the server for the file size and store it
                    long fileSize = ftpResponse.ContentLength;
                    ftpResponse.Close();

                    WebClient wc = new WebClient();
                    wc.Credentials = ftpRequest.Credentials;
                    xDoc.LoadXml(wc.DownloadString(pluginsFTPdbFile));
                }
                catch
                {
                    xDoc.AppendChild(xDoc.CreateElement("Plugins"));
                }
                #endregion

                formPB.Text = "Check File Dates/Times";
                #region Retrieve list of all files & directories from FTP server
                try
                {
                    // Create a request to the directory we are working in
                    ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPServer);
                    // Set default authentication for retrieving the file info
                    ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                    ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                    StreamReader streamReader = new StreamReader(ftpResponse.GetResponseStream());

                    List<string> files = new List<string>();
                    string line = streamReader.ReadLine();
                    while (!string.IsNullOrEmpty(line))
                    {
                        files.Add(line);
                        line = streamReader.ReadLine();
                    }

                    foreach (string s in files)
                    {
                        formPB.Value = files.IndexOf(s) * 100 / files.Count;
                        formPB.Refresh();
                        if (s[0].ToString().ToLower() == "d")
                            continue;

                        // Create a request to the directory we are working in
                        ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPServer + s.Substring(62));
                        ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                        ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                        DateTime dt = ftpResponse.LastModified;
                        listing.Add(new FileData(s, dt));
                        ftpResponse.Close();
                    }

                }
                catch (Exception ex)
                {
                }
                #endregion

                HashSet<string> hashTable = new HashSet<string>();
                bool xDocChange = false;
                foreach (FileData fd in listing)
                {
                    // We only want files (non-directories)
                    if ((fd.attrib | FileAttributes.Directory) != FileAttributes.Directory)
                    {
                        string[] fName = fd.name.ToLower().Split('.', '-');
                        string modifiedName = fName[0].Replace('!', '_').Replace('+', '_');

                        #region Update information box
                        formPB.Text = "Analyzing: \n" + fd.name;
                        formPB.Value = listing.IndexOf(fd) * 100 / listing.Count;
                        formPB.Refresh();
                        #endregion

                        if (fName[fName.Length - 1] != "ent")
                            continue;

                        /*
                        if (fName.Length > 3)
                        {
                            string ver = fName[1];
                            for (int i = 2; i < fName.Length - 1; i++)
                                ver += '.' + fName[i];
                            fVer = new Version(ver);
                        }
                        */

                        // Check for the matching tag HASHCODE name
                        XmlNodeList xnl = null;
                        XmlNode xNode = null;

                        if (fName.Length > 2)
                            xnl = xDoc.GetElementsByTagName("_" + fName[1]);

                        // Search through each return value for the one in the desired parent TAG TYPE
                        if (xnl != null && xnl.Count > 0)
                            foreach (XmlNode xn in xnl)
                            {
                                if (xn.ParentNode.Name == modifiedName)
                                {
                                    xNode = xn;
                                    break;
                                }
                            }

                    @updatePlugin:
                        // If we do not get any results for the HASHCODE, check for parent TAG TYPE
                        if (xNode == null)
                        {
                            // Search for a matching TAG TYPE
                            XmlNodeList xml = xDoc.GetElementsByTagName(modifiedName);

                            // No matching TAG TYPE was found, so create a tag placeholder (eg. SCNR)
                            if (xml.Count == 0)
                            {
                                xNode = xDoc.CreateElement(modifiedName);
                                xDoc.FirstChild.AppendChild(xNode);
                            }
                            // We found a matching TAG TYPE, so select it
                            else
                            {
                                xNode = xml[0];
                            }

                            // Retrieve the plugin from the server & parse for needed info
                            WebClient wc = new WebClient();
                            wc.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                            try
                            {
                                string tempPlugin = wc.DownloadString(pluginsFTPServer + fd.name);
                                XmlDocument xd = new XmlDocument();
                                xd.LoadXml(tempPlugin);
                                XmlNodeList XList;
                                XmlNode xnA;    // Holds author attribute info
                                XmlNode xnV;    // Holds version attribute info
                                string tag;

                                try
                                {
                                    XList = xd.GetElementsByTagName("revision");
                                    xnA = XList[0].Attributes.GetNamedItem("author");
                                    xnV = XList[0].Attributes.GetNamedItem("version");
                                    try
                                    {
                                        XList = xd.GetElementsByTagName("plugin");
                                        tag = XList[0].Attributes.GetNamedItem("class").Value;
                                    }
                                    catch
                                    {
                                        tag = fName[0].ToLower();
                                    }
                                }
                                catch
                                {
                                    try
                                    {
                                        XList = xd.GetElementsByTagName("plugin");
                                        xnA = XList[0].Attributes.GetNamedItem("author");
                                        xnV = XList[0].Attributes.GetNamedItem("version");
                                        tag = XList[0].Attributes.GetNamedItem("class").Value;
                                    }
                                    catch
                                    {
                                        // Bad plugin?
                                        continue;
                                    }
                                }

                                //
                                // Need to generate name first & will rename later
                                //
                                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                                string md5 = GetChecksum(encoding.GetBytes(tempPlugin));

                                if (fName.Length > 2)
                                    xNode = xNode.AppendChild(xDoc.CreateElement("_" + fName[1]));
                                else
                                    xNode = xNode.AppendChild(xDoc.CreateElement("_---"));

                                // Append author & version to xNode
                                // (This needs to be after the xNode is possibly set to xNode.Child)

                                // MD5 Hashcode
                                XmlAttribute xAttr = xDoc.CreateAttribute("md5");
                                xAttr.InnerText = md5;
                                xNode.Attributes.Append(xAttr);

                                // Author info
                                xAttr = xDoc.CreateAttribute("tagtype");
                                xAttr.InnerText = tag;
                                xNode.Attributes.Append(xAttr);

                                // Author info
                                xAttr = xDoc.CreateAttribute("author");
                                xAttr.InnerText = xnA.Value;
                                xNode.Attributes.Append(xAttr);

                                // Version info
                                xAttr = xDoc.CreateAttribute("version");
                                xAttr.InnerText = xnV.Value;
                                xNode.Attributes.Append(xAttr);

                                // States that changes need to be made to database file
                                xDocChange = true;
                            }
                            catch (Exception ex)
                            {
                                Globals.Global.ShowErrorMsg("Error from plugin server: ", ex);
                            }
                        }
                        PluginData pd = new PluginData(fd, xNode);
                        if (pd.md5 == string.Empty)
                        {
                            xNode = null;
                            goto @updatePlugin;
                        }
                        if (hashTable.Contains(pd.md5))
                        {
                            // Duplicate file found, erase file & remove entry
                            try
                            {
                                ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPServer + fd.name);
                                // Set default authentication for retrieving the file info
                                ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);

                                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                                // Ask the server for the file size and store it
                                ftpResponse.Close();
                                xDocChange = true;
                            }
                            catch
                            { }
                            continue;
                        }

                        hashTable.Add(pd.md5);

                        // 1827
                        // "_fx_-87943969.ent"
                        // {27/10/2012 1:49:00 AM}
                        // "Grimdoomer"
                        // "0.99"

                        // Create a unique short hash code for this plugin using author, version & file date/time stamp
                        string hashcode = pd.GetHashCode().ToString();
                        string fileName = fName[0] + '-' + hashcode + ".ent";
                        if (fd.name.ToLower() != fileName)
                        {
                            // Rename the node to reflect the [new] hashcode
                            if (xNode.Name != "_" + hashcode)
                                xNode = RenameNode(xNode, string.Empty, '_' + hashcode);
                            #region Rename file to naming sequence
                            // Create a request to the directory we are working in
                            ftpRequest = (FtpWebRequest)WebRequest.Create(pluginsFTPServer + fd.name);
                            // Set default authentication for retrieving the file info
                            ftpRequest.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                            ftpRequest.Method = WebRequestMethods.Ftp.Rename;
                            ftpRequest.RenameTo = fileName;
                            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                            ftpResponse.Close();
                            #endregion
                            fd.name = fileName;
                        }

                        if (pd.version == "0.0")
                        {
                            int a = 0;
                        }
                        this.Add(fName[0], pd);
                    }

                }
                if (xDocChange)
                {
                    // WriteXDoc back out
                    WebClient wc = new WebClient();
                    wc.Credentials = new NetworkCredential(updateFTPName, updateFTPPass);
                    wc.UploadString(pluginsFTPdbFile, xDoc.InnerXml);
                }
            }
            finally
            {
                // Clean up our loading form
                formPB.Dispose();
            }
        }
Esempio n. 46
0
 /// <summary>Find the duplicates</summary>
 public void FindDuplicates()
 {
     using (var dlg = new ProgressForm("Finding Duplicates...", string.Empty, SystemIcons.Information, ProgressBarStyle.Marquee, FindDuplicates))
         dlg.ShowDialog(m_parent);
 }
Esempio n. 47
0
 /// <summary>
 /// Оригинальный конструктор
 /// </summary>
 public GCompTools()
 {
     Params = GCompWrapper.SetDefaults();
     frm    = new ProgressForm(this);
     loadDefaultParams();
 }
Esempio n. 48
0
 private void btnHighlight_Click(object sender, EventArgs e)
 {
     ProgressForm progressForm = new ProgressForm();
     progressForm.Shown += new EventHandler(progressForm_Shown);
     progressForm.ShowDialog(new WindowHandle(ParentHandle));
     Button btn = sender as Button;
     if (btn != null)
     {
         if (CurrentModule.IsHighlighted)
         {
             btn.Text = "Clear";
             this.btnSettings.Enabled = false;
         }
         else
         {
             btn.Text = "Highlight";
             this.btnSettings.Enabled = true;
         }
     }
 }