public void TestInitialize()
 {
     var fixture = new Fixture();
     factories = Substitute.For<Factories>();
     navigator = Substitute.For<Navigator>();
     stateProvider = Substitute.For<StateProvider>();
     facade = Substitute.For<ReplacementBuilderAndSugarEstimatorFacade>();
     clipboard = Substitute.For<Clipboard>();
     messageDialog = Substitute.For<MessageDialog>();
     navigation = new InsulinEditingViewModel.Navigation();
     CreateSut();
     insulin = fixture.Create<Insulin>();
     insulin.InitializeCircumstances(new List<Guid>());
     insulin.SetOwner(factories);
     sugar = new Sugar();
     sugar.SetOwner(factories);
     factories.InsulinCircumstances.Returns(fixture.CreateMany<InsulinCircumstance>().ToList());
     factories.CreateSugar().Returns(sugar);
     settings = new Settings { MaxBolus = 5 };
     factories.Settings.Returns(settings);
     meal = fixture.Create<Meal>();
     factories.Finder.FindMealByInsulin(insulin).Returns(meal);
     factories.Finder.FindInsulinById(insulin.Id).Returns(insulin);
     var replacementAndEstimatedSugars = new ReplacementAndEstimatedSugars();
     replacementAndEstimatedSugars.EstimatedSugars = new List<Sugar>();
     replacementAndEstimatedSugars.Replacement
         = new Replacement { InsulinTotal = new Insulin(), Items = new List<ReplacementItem>() };
     facade.GetReplacementAndEstimatedSugars(Arg.Any<Meal>(), Arg.Any<Insulin>(), Arg.Any<Sugar>())
             .Returns(replacementAndEstimatedSugars);
     factories.MealNames.Returns(new List<MealName>());
     stateProvider.State.Returns(new Dictionary<string, object>());
 }
        public static void ReadClipboard()
        {
            ClipboardData data = new ClipboardData();

            data.Id         = Guid.NewGuid();
            data.CreateTime = DateTime.Now;

            //读取纯文本
            try
            {
                if (Clipboard.ContainsText())
                {
                    data.Text = Clipboard.GetText();
                }
                if (data.Text != null)
                {
                    data.Text = data.Text.Trim();
                }
            }
            catch { }

            //读取富文本(实在是解决不了内存的占用问题,所以暂时不读取富文本内容了)
            //try
            //{
            //    RichTextBox _rt = new RichTextBox();
            //    _rt.Paste();
            //    using (Stream s = new MemoryStream())
            //    {
            //        _rt.SaveFile(s, RichTextBoxStreamType.RichText);
            //        data.RichText = new byte[(int)s.Length];
            //        s.Position = 0;
            //        s.Read(data.RichText, 0, data.RichText.Length);
            //    }
            //}
            //catch { }

            //读取图片
            try { if (Clipboard.ContainsImage())
                  {
                      data.Image = Clipboard.GetImage();
                  }
            } catch { }

            //计算综合MD5值
            string md5_text = MD5Tool.Encrypt(SerializeTool.Serialize(data.Text));
            //string md5_rich = MD5Tool.Encrypt(data.RichText);
            string md5_image = MD5Tool.Encrypt(SerializeTool.Serialize(data.Image));

            data.MD5 = $"{md5_text}{md5_image}";

            byte[] _data = SerializeTool.Serialize(data);
            if (_data != null)
            {
                data.Size = _data.Length;
            }

            if (Str.Ok(data.MD5) && (Str.Ok(data.Text) || data.Image != null))
            {
                Add(data);
            }
        }
示例#3
0
        private void CsharpOrm_Click(object sender, EventArgs e)
        {
            var connectionString = DatabaseNode.Databases.Server.ConnectionString;
            GetTableSchemaResult getTableSchemaResult;

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                var tableName = $"{DatabaseNode.Name}.{_owner}.{_name}";
                getTableSchemaResult = TableSchema.GetTableSchema(connection, tableName);
            }

            var dataTransferObjectFields = getTableSchemaResult.Columns
                                           .Select(column =>
            {
                var name           = column.ColumnName;
                var typeName       = column.TypeName;
                var isNullable     = column.IsNullable;
                var csharpTypeName = SqlDataTypeArray.SqlDataTypes.First(i => i.SqlDataTypeName == typeName).CSharpTypeName;
                var csharpType     = CSharpTypeArray.CSharpTypes.First(i => i.Name == csharpTypeName);
                if (isNullable == true && csharpType.Type.IsValueType)
                {
                    csharpTypeName += "?";
                }

                return(new DataTransferObjectField(name, csharpTypeName));
            })
                                           .ToReadOnlyCollection();
            var dataTransferObject = DataTransferObjectFactory.CreateDataTransferObject(_name, dataTransferObjectFields).ToIndentedString("    ");

            var columns = getTableSchemaResult.Columns
                          .Select(i => new Foundation.Data.DbQueryBuilding.Column(i.ColumnName, i.TypeName, i.IsNullable == true))
                          .ToReadOnlyCollection();
            var createInsertSqlSqlStatementMethod = CreateInsertSqlStatementMethodFactory.Create(_owner, _name, columns);

            var identifierColumn = getTableSchemaResult.UniqueIndexColumns
                                   .Select(i => getTableSchemaResult.Columns.First(j => j.ColumnId == i.ColumnId))
                                   .Select(i => new Foundation.Data.DbQueryBuilding.Column(i.ColumnName, i.TypeName, i.IsNullable == true))
                                   .First();
            var versionColumn = columns.FirstOrDefault(i => i.ColumnName == "Version");

            columns = columns.Where(i => i.ColumnName != identifierColumn.ColumnName).ToReadOnlyCollection();
            var createUpdateSqlStatementMethod = CreateUpdateSqlStatementMethodFactory.Create(_owner, _name, identifierColumn, versionColumn, columns);
            var createDeleteSqlStatementMethod = CreateDeleteSqlStatementMethodFactory.Create(_owner, _name, identifierColumn, versionColumn);

            var textBuilder = new TextBuilder();

            textBuilder.Add(dataTransferObject);
            textBuilder.Add(Line.Empty);
            textBuilder.Add($"public static class {_name}SqlStatementFactory");
            using (textBuilder.AddCSharpBlock())
            {
                textBuilder.Add(createInsertSqlSqlStatementMethod);
                textBuilder.Add(Line.Empty);
                textBuilder.Add(createUpdateSqlStatementMethod);
                textBuilder.Add(Line.Empty);
                textBuilder.Add(createDeleteSqlStatementMethod);
            }

            Clipboard.SetText(textBuilder.ToLines().ToIndentedString("    "));
            var queryForm = (QueryForm)DataCommanderApplication.Instance.MainForm.ActiveMdiChild;

            queryForm.SetStatusbarPanelText("Copying script to clipboard finished.",
                                            queryForm.ColorTheme != null ? queryForm.ColorTheme.ForeColor : SystemColors.ControlText);
        }
示例#4
0
        private void ScriptTable_Click(object sender, EventArgs e)
        {
            using (new CursorManager(Cursors.WaitCursor))
            {
                var queryForm = (QueryForm)DataCommanderApplication.Instance.MainForm.ActiveMdiChild;
                queryForm.SetStatusbarPanelText("Copying table script to clipboard...",
                                                queryForm.ColorTheme != null ? queryForm.ColorTheme.ForeColor : SystemColors.ControlText);
                var stopwatch = Stopwatch.StartNew();

                var connectionString = DatabaseNode.Databases.Server.ConnectionString;
                var csb = new SqlConnectionStringBuilder(connectionString);

                var connectionInfo = new SqlConnectionInfo();
                connectionInfo.ApplicationName       = csb.ApplicationName;
                connectionInfo.ConnectionTimeout     = csb.ConnectTimeout;
                connectionInfo.DatabaseName          = csb.InitialCatalog;
                connectionInfo.EncryptConnection     = csb.Encrypt;
                connectionInfo.MaxPoolSize           = csb.MaxPoolSize;
                connectionInfo.MinPoolSize           = csb.MinPoolSize;
                connectionInfo.PacketSize            = csb.PacketSize;
                connectionInfo.Pooled                = csb.Pooling;
                connectionInfo.ServerName            = csb.DataSource;
                connectionInfo.UseIntegratedSecurity = csb.IntegratedSecurity;
                connectionInfo.WorkstationId         = csb.WorkstationID;
                if (!csb.IntegratedSecurity)
                {
                    connectionInfo.UserName = csb.UserID;
                    connectionInfo.Password = csb.Password;
                }

                var connection = new ServerConnection(connectionInfo);
                connection.Connect();
                var server   = new Server(connection);
                var database = server.Databases[DatabaseNode.Name];
                var table    = database.Tables[_name, _owner];

                var options = new ScriptingOptions();
                options.Indexes                = true;
                options.Permissions            = true;
                options.IncludeDatabaseContext = false;
                options.Default                = true;
                options.AnsiPadding            = true;
                options.DriAll                = true;
                options.ExtendedProperties    = true;
                options.ScriptBatchTerminator = true;
                options.SchemaQualify         = true;
                options.SchemaQualifyForeignKeysReferences = true;

                var stringCollection = table.Script(options);
                var sb = new StringBuilder();
                foreach (var s in stringCollection)
                {
                    sb.AppendLine(s);
                    sb.AppendLine("GO");
                }

                Clipboard.SetText(sb.ToString());
                stopwatch.Stop();
                queryForm.SetStatusbarPanelText(
                    $"Copying table script to clipboard finished in {StopwatchTimeSpan.ToString(stopwatch.ElapsedTicks, 3)} seconds.",
                    queryForm.ColorTheme != null ? queryForm.ColorTheme.ForeColor : SystemColors.ControlText);
            }
        }
 private void CopyButton_Click(object sender, RoutedEventArgs e)
 {
     Clipboard.SetDataObject(DSSQLTB.Text);
 }
示例#6
0
 private void log_SelectedIndexChanged(object sender, EventArgs e)
 {
     Clipboard.SetText(log.SelectedItem.ToString());
 }
示例#7
0
文件: filezoo.cs 项目: kig/filezoo
    /** BLOCKING - startup dir latency */
    public Filezoo(string dirname)
    {
        Selection = new Dictionary<string, bool> ();
        Renderer = new FSDraw ();

        clipboard = Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", true));

        SortField = SortFields[0];
        SizeField = SizeFields[0];
        Zoomer = new FlatZoomer ();

        Gdk.Colormap cm = Screen.RgbaColormap;
        if (cm != null && Screen.IsComposited) {
          Widget.DefaultColormap = cm;
          Colormap = cm;
          UseRgbaVisuals = true;
        }

        SetCurrentDir (dirname);

        Helpers.StartupProfiler.Time ("SetCurrentDir");

        CanFocus = true;
        KeyPressEvent += delegate (object o, KeyPressEventArgs args) {
          Cancelled = true;
          Gdk.ModifierType state = args.Event.State;
          switch (args.Event.Key) {
        case Gdk.Key.Control_L:
        case Gdk.Key.Control_R:
          state |= Gdk.ModifierType.ControlMask;
          break;
        case Gdk.Key.Shift_L:
        case Gdk.Key.Shift_R:
          state |= Gdk.ModifierType.ShiftMask;
          break;
        case Gdk.Key.Alt_L:
        case Gdk.Key.Alt_R:
          state |= Gdk.ModifierType.Mod1Mask;
          break;
          }
          SetCursor (state);
        };

        KeyReleaseEvent += delegate (object o, KeyReleaseEventArgs args) {
          Cancelled = true;
          if (args.Event.Key == Gdk.Key.Escape && Selection.Count > 0) {
        ClearSelection ();
        args.RetVal = true;
          } else if ((args.Event.State & Gdk.ModifierType.ControlMask) == Gdk.ModifierType.ControlMask) {
        switch (args.Event.Key) {
          case Gdk.Key.x:
            CutSelection(CurrentDirPath);
            break;
          case Gdk.Key.c:
            CopySelection(CurrentDirPath);
            break;
          case Gdk.Key.v:
            PasteSelection(CurrentDirPath);
            break;
        }
          } else {
        switch (args.Event.Key) {
          case Gdk.Key.Delete:
            TrashSelection ();
            break;
          case Gdk.Key.BackSpace:
            GoToParent ();
            break;
          case Gdk.Key.Home:
            SetCurrentDir (Helpers.HomeDir);
            break;
        }
          }
          Gdk.ModifierType state = args.Event.State;
          switch (args.Event.Key) {
        case Gdk.Key.Control_L:
        case Gdk.Key.Control_R:
          state &= ~Gdk.ModifierType.ControlMask;
          break;
        case Gdk.Key.Shift_L:
        case Gdk.Key.Shift_R:
          state &= ~Gdk.ModifierType.ShiftMask;
          break;
        case Gdk.Key.Alt_L:
        case Gdk.Key.Alt_R:
          state &= ~Gdk.ModifierType.Mod1Mask;
          break;
          }
          SetCursor (state);
        };

        DragDataGet += delegate (object o, DragDataGetArgs args) {
          string items = "file://" + DragSourcePath;
          if (Selection.Count > 0 && Selection.ContainsKey(DragSourcePath))
        items = GetSelectionData ();
          args.SelectionData.Set(args.SelectionData.Target, 8, System.Text.Encoding.UTF8.GetBytes(items));
          args.SelectionData.Text = items;
        };

        DragEnd += delegate {
          GetSelectionData ();
          Cancelled = true;
          dragInProgress = false;
          DragSourceEntry = null;
          DragSourcePath = null;
        };

        /** DESCTRUCTIVE */
        DragDataReceived += delegate (object sender, DragDataReceivedArgs e) {
          Cancelled = true;
          string targetPath = FindHit (Width, Height, e.X, e.Y, 8).Target.FullName;
          HandleSelectionData (e.SelectionData, e.Context.SuggestedAction, targetPath);
        };

        Gtk.Drag.DestSet (this, DestDefaults.All, target_table,
        Gdk.DragAction.Move
          | Gdk.DragAction.Copy
          | Gdk.DragAction.Ask
        );

        AddEvents((int)(
        Gdk.EventMask.ButtonPressMask
          | Gdk.EventMask.ButtonReleaseMask
          | Gdk.EventMask.ScrollMask
          | Gdk.EventMask.PointerMotionMask
          | Gdk.EventMask.EnterNotifyMask
          | Gdk.EventMask.KeyPressMask
          | Gdk.EventMask.KeyReleaseMask
          | Gdk.EventMask.LeaveNotifyMask
        ));

        ThreadStart ts = new ThreadStart (PreDrawCallback);
        Thread t = new Thread(ts);
        t.IsBackground = true;
        t.Start ();

        System.Timers.Timer t1 = new System.Timers.Timer(50);
        t1.Elapsed += new ElapsedEventHandler (CheckUpdates);
        System.Timers.Timer t2 = new System.Timers.Timer(1000);
        t2.Elapsed += new ElapsedEventHandler (LongMonitor);
        t1.Enabled = true;
        t2.Enabled = true;
        GLib.Timeout.Add (10, new GLib.TimeoutHandler(CheckRedraw));
        Helpers.StartupProfiler.Total ("Pre-drawing startup");
    }
示例#8
0
    /// <summary>
    /// This constructor is called from the other constructor.
    /// </summary>
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        Build();
          PipeEng = new Engine(AppName);
          this.Title = AppName;
          AssyFolder = System.IO.Path.GetDirectoryName(typeof(MainWindow).Assembly.Location);
          homeFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
          applDataFolder = homeFolder + System.IO.Path.DirectorySeparatorChar + "." + AppName.ToLower();
          ConfigFile = applDataFolder + System.IO.Path.DirectorySeparatorChar + AppName + "Conf.xml";

          LoadConfiguration();

          ErrorsTextView.WrapMode = WrapMode.Word;
          TheClipboard = Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false));

          PipeTextView.Buffer.Changed += PipeTextBuffer_OnChanged;
          InputTextView.Buffer.Changed += IOTextBuffer_OnChanged;
          OutputTextView.Buffer.Changed += IOTextBuffer_OnChanged;

          TextNotebook.SetTabLabelText(TextNotebook.Children[0],"Input");
          TextNotebook.SetTabLabelText(TextNotebook.Children[1],"Output");
          TextNotebook.SetTabLabelText(TextNotebook.Children[2],"Errors");

          PopulateFilterToolbar();

          this.Title = "new pipe - " + AppName;
          UpdateControls();
    }
示例#9
0
        public string AdvencedSearchGetQuery(TextBox CodeProjet, TextBox NomProjet, TextBox CodeProgramme, TextBox NomProgramme, ComboBox Daira, ComboBox Commune, ComboBox NatureProgramme, ComboBox TypeProgramme)
        {
            int i;
            int j;
            int k;


            string query  = "select NomProjet,RefProgramme,programme.RefProjet,NomProgramme,programme.Site,programme.Daira,programme.Commune,NatureProgramme,TypeProgramme,NombreBiens,programme.Superficie,TypeVente,CoutFoncier,TVA,CoutFoncierTTC,PrixM2 from programme,projet where ";
            string query2 = "programme.RefProjet = projet.RefProjet";

            string[] AttributTextBox = new string[2];
            AttributTextBox[0] = "programme.RefProjet";
            AttributTextBox[1] = "RefProgramme";


            TextBox[] prg = new TextBox[2];
            prg[0] = CodeProjet;
            prg[1] = CodeProgramme;


            for (i = 0; i < AttributTextBox.Length; i++)
            {
                if (prg[i].Text != "")
                {
                    query = query + "" + AttributTextBox[i] + "=" + "'" + prg[i].Text + "'" + " And ";
                }
            }

            string[] AttributTextBox2 = new string[2];
            AttributTextBox2[0] = "NomProjet";
            AttributTextBox2[1] = "NomProgramme";


            TextBox[] prg3 = new TextBox[2];
            prg3[0] = NomProjet;
            prg3[1] = NomProgramme;


            for (k = 0; k < AttributTextBox2.Length; k++)
            {
                if (prg3[k].Text != "")
                {
                    query = query + "" + AttributTextBox2[k] + " LIKE " + "'" + prg3[k].Text + "%" + "'" + " And ";
                }
            }

            string[] AttributComboBox = new string[4];

            AttributComboBox[0] = "programme.Daira";
            AttributComboBox[1] = "programme.Commune";
            AttributComboBox[2] = "NatureProgramme";
            AttributComboBox[3] = "TypeProgramme";

            ComboBox[] prg2 = new ComboBox[4];
            prg2[0] = Daira;
            prg2[1] = Commune;
            prg2[2] = NatureProgramme;
            prg2[3] = TypeProgramme;


            for (j = 0; j < AttributComboBox.Length; j++)
            {
                if (prg2[j].Text != "")
                {
                    query = query + "" + AttributComboBox[j] + "=" + "'" + prg2[j].Text + "'" + " And ";
                }
            }

            query = query + query2;
            Clipboard.SetText(query);
            return(query);
        }
示例#10
0
        public static void ClipboardUpload(TaskSettings taskSettings = null)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            if (Clipboard.ContainsImage())
            {
                Image img = Clipboard.GetImage();

                if (img != null)
                {
                    if (!taskSettings.AdvancedSettings.ProcessImagesDuringClipboardUpload)
                    {
                        taskSettings.AfterCaptureJob = AfterCaptureTasks.UploadImageToHost;
                    }

                    RunImageTask(img, taskSettings);
                }
            }
            else if (Clipboard.ContainsFileDropList())
            {
                string[] files = Clipboard.GetFileDropList().Cast <string>().ToArray();
                UploadFile(files, taskSettings);
            }
            else if (Clipboard.ContainsText())
            {
                string text = Clipboard.GetText();

                if (!string.IsNullOrEmpty(text))
                {
                    string url = text.Trim();

                    if (Helpers.IsValidURLRegex(url))
                    {
                        if (taskSettings.UploadSettings.ClipboardUploadURLContents)
                        {
                            string filename = Helpers.GetURLFilename(url);

                            if (!string.IsNullOrEmpty(filename))
                            {
                                DownloadAndUploadFile(url, filename, taskSettings);
                                return;
                            }
                        }

                        if (taskSettings.UploadSettings.ClipboardUploadShortenURL)
                        {
                            ShortenURL(url, taskSettings);
                            return;
                        }
                    }

                    if (taskSettings.UploadSettings.ClipboardUploadAutoIndexFolder && text.Length <= 260 && Directory.Exists(text))
                    {
                        IndexFolder(text, taskSettings);
                    }
                    else
                    {
                        UploadText(text, taskSettings);
                    }
                }
            }
        }
示例#11
0
        /// <summary>
        /// Performs the CopyDisplayName command.
        /// </summary>
        /// <param name="parameter">The CopyDisplayName command parameter.</param>
        private void DoCopyDisplayNameCommand(object parameter)
        {
            var assembly = (GACAssemblyViewModel)parameter;

            Clipboard.SetText(assembly.InternalAssemblyDescription.DisplayName);
        }
示例#12
0
 internal static void SetExcelData(params object[] data)
 {
     Clipboard.SetText("\"" + string.Join("\";\"", data) + "\"", TextDataFormat.CommaSeparatedValue);
 }
 private void PasteCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
 {
     e.CanExecute = Clipboard.ContainsText();
 }
示例#14
0
 private void OnApply(object Obj, EventArgs EA)
 {
     Clipboard.SetText(Edit.Text);
 }
示例#15
0
        private async void startDownloadButton_Click(object sender, EventArgs e)
        {
            SavePrefs();
            startDownloadButton.Enabled = false;

            cancelDownload = false;

            if (!Directory.Exists(downloadDestBox.Text))
            {
                MessageBox.Show("The download destination does not exist!", "Problem!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string tags = searchTagsBox.Text.Trim();
            string[] tagsArray = string.IsNullOrEmpty(tags) ? new string[0] : tags.Split(' ');
            if (tagsArray.Length > 4)
            {
                MessageBox.Show("You can only search with a maximum of 4 tags!", "Ops!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }

            try
            {
                using (var http = new HttpClient())
                {
                    http.DefaultRequestHeaders.Clear();
                    http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1");
                    http.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

                    StringBuilder linkBuilder = new StringBuilder();
                    linkBuilder.Append("https://e621.net/post/index.xml?tags=rating%3Ae%20");
                    if (!animatedCheckBox.Checked)
                        linkBuilder.Append("type%3Apng%20");
                    else
                        linkBuilder.Append("type%3Agif%20");

                    tags = tags.Replace(" ", "%20");

                    linkBuilder.Append(tags).Append($"%20order:random&limit={downloadAmountBar.Value}");
                    //string json = await GetJson(linkBuilder.ToString());
                    //JArray array = JArray.Parse(json);
                    Clipboard.SetText(linkBuilder.ToString());
                    var data = await http.GetStreamAsync(linkBuilder.ToString());
                    var doc = XDocument.Load(data);
                    int amount = doc.Descendants("posts").Nodes().ToArray().Length;
                    //MessageBox.Show(doc.Descendants("posts").ElementAt(0).Descendants("file_url").FirstOrDefault().Value.ToString());
                    if (amount > 0)
                    {
                        using (WebClient client = new WebClient())
                        {
                            downloading = true;
                            client.DownloadProgressChanged += Client_DownloadProgressChanged;
                            cancelDownloadButton.Enabled = true;
                            //await client.DownloadFileTaskAsync(array[0]["file_url"].ToString(), downloadDestBox.Text + "\\" + array[0]["id"].ToString() + "." + array[0]["file_ext"].ToString());
                            //for (int i = 0; i < amount; i++)
                            //{
                            //    downloadingLabel.Text = "Downloading " + (i + 1).ToString() + "/" + amount.ToString();
                            //    string url = doc.Descendants("posts").ElementAt(i).Descendants("file_url").FirstOrDefault().Value.ToString();
                            //    string downloadDest = downloadDestBox.Text + "\\" + doc.Descendants("posts").ElementAt(i).Descendants("id").FirstOrDefault().Value.ToString() + "." + doc.Descendants("posts").ElementAt(i).Descendants("file_ext").FirstOrDefault().Value.ToString();
                            //    //await client.DownloadFileTaskAsync(array[i]["file_url"].ToString(), downloadDestBox.Text + "\\" + array[i]["id"].ToString() + "." + array[i]["file_ext"].ToString());
                            //    await client.DownloadFileTaskAsync(url, downloadDest);
                            //}
                            //MessageBox.Show(doc.Descendants("posts").ToArray().Length.ToString());
                            int dlIndex = 0;
                            foreach (XElement element in doc.Descendants("posts").Nodes())
                            {
                                if (cancelDownload)
                                {
                                    client.DownloadProgressChanged -= Client_DownloadProgressChanged;
                                    downloading = false;
                                    startDownloadButton.Enabled = true;
                                    downloadProgressBar.Value = 0;
                                    downloadingLabel.Text = NOT_DOWNLOADING_TEXT;
                                    return;
                                }
                                //MessageBox.Show(element.Descendants("id").FirstOrDefault().Value.ToString());
                                downloadingLabel.Text = "Downloading " + (dlIndex + 1).ToString() + "/" + amount.ToString();
                                string url = element.Descendants("file_url").FirstOrDefault().Value.ToString();
                                string downloadDest = downloadDestBox.Text + "\\" + element.Descendants("id").FirstOrDefault().Value.ToString() + "." + element.Descendants("file_ext").FirstOrDefault().Value.ToString();
                                await client.DownloadFileTaskAsync(url, downloadDest);
                                dlIndex++;
                            }
                            client.DownloadProgressChanged -= Client_DownloadProgressChanged;
                            downloadingLabel.Text = NOT_DOWNLOADING_TEXT;
                            MessageBox.Show("Downloads done", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            startDownloadButton.Enabled = true;
                            cancelDownloadButton.Enabled = false;
                            downloading = false;
                            downloadProgressBar.Value = 0;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Couldn't find any results with those search tags.", "Ops!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        startDownloadButton.Enabled = true;
                        downloading = false;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Something went wrong.\n\n" + ex.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                startDownloadButton.Enabled = true;
                downloading = false;
            }
        }
示例#16
0
        public Scintilla()
        {
            if (IntPtr.Size == 4)
                _sciLexerDllName = "DbDiff.SciLexer32.dll";
            else
                _sciLexerDllName = "DbDiff.SciLexer64.dll";
            _ns = (INativeScintilla)this;

            // Set up default encoding
            _encoding = Encoding.GetEncoding(NativeInterface.GetCodePage());

            //	Ensure all style values have at least defaults
            _ns.StyleClearAll();

            _caret					= new CaretInfo(this);
            _lines					= new LinesCollection(this);
            _selection				= new Selection(this);
            _indicators				= new IndicatorCollection(this);
            _margins				= new MarginCollection(this);
            _scrolling				= new Scrolling(this);
            _whiteSpace				= new WhiteSpace(this);
            _endOfLine				= new EndOfLine(this);
            _clipboard				= new Clipboard(this);
            _undoRedo				= new UndoRedo(this);
            _dropMarkers			= new DropMarkers(this);
            _hotspotStyle			= new HotspotStyle(this);
            _callTip				= new CallTip(this);
            _styles					= new StyleCollection(this);
            _indentation			= new Indentation(this);
            _documentHandler		= new DocumentHandler(this);
            _lineWrap				= new LineWrap(this);
            _lexing					= new Lexing(this);
            _longLines				= new LongLines(this);
            _commands				= new Commands(this);
            _configurationManager	= new ConfigurationManager(this);
            _printing				= new Printing(this);
            _documentNavigation		= new DocumentNavigation(this);
            _goto					= new GoTo(this);

            _helpers.AddRange(new ScintillaHelperBase[]
            {
                _caret,
                _lines,
                _selection,
                _indicators,
                _margins,
                _scrolling,
                _whiteSpace,
                _endOfLine,
                _clipboard,
                _undoRedo,
                _dropMarkers,
                _hotspotStyle,
                _styles,
                _indentation,
                _documentHandler,
                _lineWrap,
                _lexing,
                _longLines,
                _commands,
                _configurationManager,
                _printing,
                _documentNavigation,
                _goto
            });

            //	Changing the Default values from Scintilla's default Black on White
            //	to platform defaults for Edits
            BackColor = SystemColors.Window;
            ForeColor = SystemColors.WindowText;
        }
示例#17
0
        private void BuildContextMenu()
        {
            CmdArgsCtxMenu_Cut.IsEnabled   = true;
            CmdArgsCtxMenu_Copy.IsEnabled  = true;
            CmdArgsCtxMenu_Paste.IsEnabled = true;

            CmdArgsCtxMenu_SavedMenu.IsEnabled   = false;
            CmdArgsCtxMenu_SavedMenu.Header      = "Saved";
            CmdArgsCtxMenu_HistoryMenu.IsEnabled = false;
            CmdArgsCtxMenu_HistoryMenu.Header    = "History";

            if (String.IsNullOrEmpty(CmdArgs.SelectedText))
            {
                CmdArgsCtxMenu_Cut.IsEnabled  = false;
                CmdArgsCtxMenu_Copy.IsEnabled = false;
            }
            if (!Clipboard.ContainsText())
            {
                CmdArgsCtxMenu_Paste.IsEnabled = false;
            }

            if (savedArgs.Count > 0)
            {
                CmdArgsCtxMenu_SavedMenu.IsEnabled = true;

                CmdArgsCtxMenu_SavedMenu.Items.Clear();
                foreach (KeyValuePair <string, string> kvp in savedArgs)
                {
                    MenuItem savedMI = new MenuItem();

                    DockPanel savedMIPanel = new DockPanel();
                    savedMIPanel.LastChildFill       = false;
                    savedMIPanel.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

                    TextBlock textBlock = new TextBlock();
                    textBlock.Text = kvp.Key;
                    savedMIPanel.Children.Add(textBlock);

                    Button deleteButton = new Button();
                    deleteButton.Content = new System.Windows.Controls.Image
                    {
                        Source = new BitmapImage(new Uri("Resources/Delete.png", UriKind.Relative))
                    };
                    deleteButton.Margin = new Thickness(20, 0, 0, 0);
                    deleteButton.Click += deleteButton_OnClick;
                    savedMIPanel.Children.Add(deleteButton);

                    savedMI.Header      = savedMIPanel;
                    savedMI.Name        = "SavedEntry";
                    savedMI.IsCheckable = true;
                    if (kvp.Value == IDEUtils.GetCommandArgs())
                    {
                        savedMI.IsChecked = true;
                    }
                    savedMI.Click += savedMI_OnClick;

                    TextBlock toolTipTextBlock = new TextBlock();
                    toolTipTextBlock.Text         = kvp.Value;
                    toolTipTextBlock.TextWrapping = TextWrapping.Wrap;
                    savedMI.ToolTip = toolTipTextBlock;
                    ToolTipService.SetShowDuration(savedMI, 3600000);

                    CmdArgsCtxMenu_SavedMenu.Items.Add(savedMI);
                }

                CmdArgsCtxMenu_SavedMenu.Header = string.Format(CultureInfo.CurrentCulture, "Saved ({0})", CmdArgsCtxMenu_SavedMenu.Items.Count);

                CmdArgsCtxMenu_SavedMenu.UpdateLayout();
            }

            if (History.GetHistory.Count > 0)
            {
                CmdArgsCtxMenu_HistoryMenu.IsEnabled = true;

                CmdArgsCtxMenu_HistoryMenu.Items.Clear();
                foreach (string historyEntry in History.GetHistory)
                {
                    MenuItem  historyMI = new MenuItem();
                    TextBlock textBlock = new TextBlock();
                    textBlock.Text        = historyEntry;
                    historyMI.Header      = textBlock;
                    historyMI.Name        = "HistoryEntry";
                    historyMI.IsCheckable = true;
                    if (historyEntry == IDEUtils.GetCommandArgs())
                    {
                        historyMI.IsChecked = true;
                    }
                    historyMI.Click += historyMI_OnClick;

                    TextBlock toolTipTextBlock = new TextBlock();
                    toolTipTextBlock.Text         = historyEntry;
                    toolTipTextBlock.TextWrapping = TextWrapping.Wrap;
                    historyMI.ToolTip             = toolTipTextBlock;
                    ToolTipService.SetShowDuration(historyMI, 3600000);

                    CmdArgsCtxMenu_HistoryMenu.Items.Add(historyMI);
                }

                CmdArgsCtxMenu_HistoryMenu.Header = string.Format(CultureInfo.CurrentCulture, "History ({0}/{1})", CmdArgsCtxMenu_HistoryMenu.Items.Count, History.GetHistory.Size);

                CmdArgsCtxMenu_HistoryMenu.UpdateLayout();
            }
        }
示例#18
0
        public Scintilla()
        {
            // We don't want .NET to use GetWindowText because we manage ('cache') our own text
            SetStyle(ControlStyles.CacheText, true);

            // Necessary control styles (see TextBoxBase)
            SetStyle(ControlStyles.StandardClick
                   | ControlStyles.StandardDoubleClick
                   | ControlStyles.UseTextForAccessibility
                   | ControlStyles.UserPaint,
                   false);

            // It's critical that we initialize helpers that listen for notifications early and
            // in the correct order. They have to be the first to know when notifications occur.
            _lineStorage = new LineStorage(this);
            _stringAdapter = new StringAdapter(this, _lineStorage);

            _state = new BitVector32(0);
            _state[_acceptsReturnState] = true;
            _state[_acceptsTabState] = true;

            _ns = (INativeScintilla)this;

            _caption = GetType().FullName;

            // Most Windows Forms controls delay-load everything until a handle is created.
            // That's a major pain so we just explicity create a handle right away.
            CreateControl();

            // Set up default encoding to UTF-8 which is the Scintilla's best supported.
            // .NET strings are UTF-16 but should be able to convert without any problems
            this.Encoding = Encoding.UTF8;

            // Ensure all style values have at least defaults
            _ns.StyleClearAll();

            _caret = new CaretInfo(this);
            _lines = new LineCollection(this);
            _selection = new Selection(this);
            _snippets = new SnippetManager(this);
            _margins = new MarginCollection(this);
            _whitespace = new Whitespace(this);
            _endOfLine = new EndOfLine(this);
            _clipboard = new Clipboard(this);
            _undoRedo = new UndoRedo(this);
            _dropMarkers = new DropMarkers(this);
            _hotspotStyle = new HotspotStyle(this);
            _callTip = new CallTip(this);
            _styles = new StyleCollection(this);
            _indentation = new Indentation(this);
            _markers = new MarkerCollection(this);
            _autoComplete = new AutoComplete(this);
            _documentHandler = new DocumentHandler(this);
            _lexing = new Lexing(this);
            _longLines = new LongLines(this);
            _commands = new Commands(this);
            _folding = new Folding(this);
            _configurationManager = new ConfigurationManager(this);
            _printing = new Printing(this);
            _findReplace = CreateFindReplaceInstance();
            _documentNavigation = new DocumentNavigation(this);
            _goto = new GoTo(this);


            _helpers.AddRange(new TopLevelHelper[]
            {
                _caret,
                _lines,
                _selection,
                _snippets,
                _margins,
                _whitespace,
                _endOfLine,
                _clipboard,
                _undoRedo,
                _dropMarkers,
                _hotspotStyle,
                _styles,
                _indentation,
                _markers,
                _autoComplete,
                _documentHandler,
                _lexing,
                _longLines,
                _commands,
                _folding,
                _configurationManager,
                _printing,
                _findReplace,
                _documentNavigation,
                _goto
            });


            // Change from Scintilla's default black on white to
            // platform defaults for edit controls.
            base.BackColor = SystemColors.Window;
            base.ForeColor = SystemColors.WindowText;

            Styles[0].Font = Font;
            Styles[0].ForeColor = ForeColor;
            Styles[0].BackColor = BackColor;
            Styles.Default.BackColor = BackColor;

            // Change scrolling defaults
            DirectMessage(NativeMethods.SCI_SETSCROLLWIDTH, new IntPtr(1), IntPtr.Zero);
            DirectMessage(NativeMethods.SCI_SETSCROLLWIDTHTRACKING, new IntPtr(1), IntPtr.Zero);
        }
示例#19
0
        //艦隊編成のコピー
        private void ContextMenuFleet_CopyFleet_Click(object sender, EventArgs e)
        {
            StringBuilder sb    = new StringBuilder();
            KCDatabase    db    = KCDatabase.Instance;
            FleetData     fleet = db.Fleet[FleetID];

            if (fleet == null)
            {
                return;
            }

            sb.AppendFormat("{0}\t" + GeneralRes.AirPower + " {1}/ " + GeneralRes.TotalLoS + "{2}\r\n", fleet.Name, fleet.GetAirSuperiority(), fleet.GetSearchingAbilityString());
            for (int i = 0; i < fleet.Members.Count; i++)
            {
                if (fleet[i] == -1)
                {
                    continue;
                }

                ShipData ship = db.Ships[fleet[i]];

                sb.AppendFormat("{0}/{1}\t", ship.MasterShip.Name, ship.Level);

                var eq = ship.AllSlotInstance;


                if (eq != null)
                {
                    for (int j = 0; j < eq.Count; j++)
                    {
                        if (eq[j] == null)
                        {
                            continue;
                        }

                        int count = 1;
                        for (int k = j + 1; k < eq.Count; k++)
                        {
                            if (eq[k] != null && eq[k].EquipmentID == eq[j].EquipmentID && eq[k].Level == eq[j].Level && eq[k].AircraftLevel == eq[j].AircraftLevel)
                            {
                                count++;
                            }
                            else
                            {
                                break;
                            }
                        }

                        if (count == 1)
                        {
                            sb.AppendFormat("{0}{1}", j == 0 ? "" : "/", eq[j].NameWithLevel);
                        }
                        else
                        {
                            sb.AppendFormat("{0}{1}x{2}", j == 0 ? "" : "/", eq[j].NameWithLevel, count);
                        }

                        j += count - 1;
                    }
                }

                sb.AppendLine();
            }


            Clipboard.SetData(DataFormats.StringFormat, sb.ToString());
        }
示例#20
0
 private void copyToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Clipboard.SetData("Text", lstStrings.SelectedItems[0].SubItems[1].Text);
 }
示例#21
0
        /// <summary>
        /// 「艦隊デッキビルダー」用編成コピー
        /// <see cref="http://www.kancolle-calc.net/deckbuilder.html"/>
        /// </summary>
        private void ContextMenuFleet_CopyFleetDeckBuilder_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            KCDatabase    db = KCDatabase.Instance;

            // 手書き json の悲しみ

            sb.Append(@"{""version"":3,");

            foreach (var fleet in db.Fleet.Fleets.Values)
            {
                if (fleet == null)
                {
                    continue;
                }

                sb.AppendFormat(@"""f{0}"":{{", fleet.FleetID);

                int shipcount = 1;
                foreach (var ship in fleet.MembersInstance)
                {
                    if (ship == null)
                    {
                        break;
                    }

                    sb.AppendFormat(@"""s{0}"":{{""id"":{1},""lv"":{2},""luck"":{3},""items"":{{",
                                    shipcount,
                                    ship.ShipID,
                                    ship.Level,
                                    ship.LuckBase);

                    if (ship.ExpansionSlot <= 0)
                    {
                        sb.Append(@"""ix"":{},");
                    }
                    else
                    {
                        sb.AppendFormat(@"""ix"":{{""id"":{0}}},", ship.ExpansionSlotMaster);
                    }

                    int eqcount = 1;
                    foreach (var eq in ship.SlotInstance)
                    {
                        if (eq == null)
                        {
                            break;
                        }

                        // 水偵は改修レベル優先(熟練度にすると改修レベルに誤解されて 33式 の結果がずれるため)
                        sb.AppendFormat(@"""i{0}"":{{""id"":{1},""rf"":{2}}},", eqcount, eq.EquipmentID, eq.MasterEquipment.CategoryType == 10 ? eq.Level : Math.Max(eq.Level, eq.AircraftLevel));

                        eqcount++;
                    }

                    if (eqcount > 0)
                    {
                        sb.Remove(sb.Length - 1, 1);                                    // remove ","
                    }
                    sb.Append(@"}},");

                    shipcount++;
                }

                if (shipcount > 0)
                {
                    sb.Remove(sb.Length - 1, 1);                                // remove ","
                }
                sb.Append(@"},");
            }

            sb.Remove(sb.Length - 1, 1);                        // remove ","
            sb.Append(@"}");

            Clipboard.SetData(DataFormats.StringFormat, sb.ToString());
        }
示例#22
0
 /// <summary>Execute the command.</summary>
 public override void Execute()
 {
     Clipboard.SetText(HostWindow.DatabaseInspector.RightClickedTableName);
 }
示例#23
0
        private void SSH_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Control && e.KeyCode == Keys.V)
                {
                    foreach (char Char in Clipboard.GetText(TextDataFormat.Text))
                    {
                        shellStream.Write(Char.ToString());
                        localcommand += Char.ToString();
                    }

                    return;
                }
                //remaining is key tab, and nano
                //if (e.KeyCode == Keys.Tab)
                //{
                //    shellStream.DataReceived -= ShellStream_DataReceived;
                //    shellStream.WriteLine("ls");
                //    Thread.Sleep(500);
                //    string s = reader.ReadToEnd();
                //    this.AppendText(s);
                //    //to do tab work
                //}

                //if (e.KeyCode == Keys.Up)
                //{
                //    //shellStream.Write("\x24");
                //    //return;
                //}

                if (e.Control && e.KeyCode == Keys.C)
                {
                    shellStream.Write("\x03");
                    return;
                }
                if (e.Control && e.KeyCode == Keys.X)
                {
                    shellStream.Write("\x18");
                    return;
                }

                if (e.KeyCode == Keys.Back)
                {
                    //local command handled in data received method
                    shellStream.Write("\x08");
                    return;
                }

                if (e.KeyCode == Keys.Return)
                {
                    TraverseCommand_forLocal(localcommand);
                    localcommand = "";
                    shellStream.WriteLine("");
                    return;
                }



                if (e.KeyCode == Keys.Space)
                {
                    shellStream.Write(" ");
                    localcommand += " ";
                    return;
                }

                if (e.KeyCode == Keys.OemPeriod)
                {
                    shellStream.Write(".");
                    localcommand += ".";
                    return;
                }

                if (e.KeyCode == Keys.OemMinus)
                {
                    if (e.Shift)
                    {
                        shellStream.Write("_");
                        localcommand += "_";
                        return;
                    }

                    shellStream.Write("-");
                    localcommand += "-";
                    return;
                }


                if (e.KeyCode == Keys.OemQuestion)
                {
                    shellStream.Write("/");
                    localcommand += "/";
                    return;
                }

                if (e.KeyCode == Keys.Oem5)
                {
                    shellStream.Write("\\");
                    localcommand += "\\";
                    return;
                }



                if (e.Shift && ((e.KeyValue >= 0x30 && e.KeyValue <= 0x39) || // numbers
                                (e.KeyValue >= 0x41 && e.KeyValue <= 0x5A) // letters
                                                                           //|| (e.KeyValue >= 0x60 && e.KeyValue <= 0x69) // numpad
                                ))
                {
                    shellStream.Write(char.ConvertFromUtf32(e.KeyValue));
                    localcommand += char.ConvertFromUtf32(e.KeyValue);
                    //shellStream.Write(e.KeyCode.ToString());
                    //localcommand += e.KeyCode.ToString();
                    return;
                }

                //MessageBox.Show(e.KeyValue.ToString());
                //write alpha numberic values in small
                if ((e.KeyValue >= 0x30 && e.KeyValue <= 0x39) || // numbers
                    (e.KeyValue >= 0x41 && e.KeyValue <= 0x5A)     // letters
                                                                   //|| (e.KeyValue >= 0x60 && e.KeyValue <= 0x69)// numpad
                    )
                {
                    shellStream.Write(char.ConvertFromUtf32(e.KeyValue).ToLower());
                    localcommand += char.ConvertFromUtf32(e.KeyValue).ToLower();
                    //shellStream.Write(e.KeyCode.ToString().ToLower());
                    //localcommand += e.KeyCode.ToString().ToLower();
                    return;
                }
            }
            catch (ObjectDisposedException ex)
            {
                MessageBox.Show("Connection failed");
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#24
0
 private void OnCopy(object target, ExecutedRoutedEventArgs e)
 {
     // copies the string representation of the current content to the clipboard
     Clipboard.SetText(this.Content.ToString());
 }
示例#25
0
        private void CTC_Click(object sender, EventArgs e)
        {
            try
            {
                ManagementObjectSearcher mosProcessor = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM CIM_Processor");
                ManagementObjectSearcher mosGPU       = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM CIM_VideoController");

                String cpubit          = "??";
                Int32  cpuclock        = 0;
                String cpumanufacturer = "Unknown";
                String cpuname         = "Unknown";
                String gpuname         = "Unknown";
                String gpuver          = "N/A";
                UInt32 gpuvram         = 0;
                String Frequency       = "0";
                String coreCount       = "1";

                // Get CPU info
                foreach (ManagementObject moProcessor in mosProcessor.Get())
                {
                    cpuclock        = int.Parse(moProcessor["maxclockspeed"].ToString());
                    cpubit          = CPUArch(int.Parse(moProcessor["Architecture"].ToString()));
                    cpuname         = moProcessor["name"].ToString();
                    cpumanufacturer = moProcessor["manufacturer"].ToString();
                    coreCount       = moProcessor["NumberOfCores"].ToString();
                }

                // Get GPU info
                foreach (ManagementObject moGPU in mosGPU.Get())
                {
                    gpuname = moGPU["Name"].ToString();
                    gpuvram = Convert.ToUInt32(moGPU["AdapterRAM"]);
                    gpuver  = moGPU["DriverVersion"].ToString();
                }

                if (cpuclock < 1000)
                {
                    Frequency = String.Format("{0}MHz", cpuclock);
                }
                else
                {
                    Frequency = String.Format("{0}GHz", ((float)cpuclock / 1000).ToString("0.00"));
                }

                // Ok, print everything to the string builder
                StringBuilder sb = new StringBuilder();
                sb.Append(String.Format("Keppy's MIDI Converter Information Dialog\n\n", ConverterVer.Text));
                sb.Append("== Driver info =================================================\n");
                sb.Append(String.Format("Driver version: {0}\n", ConverterVer.Text));
                sb.Append(String.Format("BASS version: {0}\n", BASSVer.Text));
                sb.Append(String.Format("BASSMIDI version: {0}\n", BASSMIDIVer.Text));
                sb.Append(String.Format("Compiled on: {0}\n\n", CompilerDate.Text));
                sb.Append("== Windows installation info ===================================\n");
                sb.Append(String.Format("Name: {0}\n", WindowsName.Text));
                sb.Append(String.Format("Version: {0}\n\n", WindowsBuild.Text));
                sb.Append("== Computer info ===============================================\n");
                sb.Append(String.Format("Processor: {0} ({1})\n", cpuname, cpubit));
                sb.Append(String.Format("Processor info: {1} cores and {2} threads, running at {3}\n", cpumanufacturer, coreCount, Environment.ProcessorCount, Frequency));
                sb.Append(String.Format("Graphics card: {0}\n", gpuname));
                sb.Append(String.Format("Graphics card info: {0}MB VRAM, driver version {1}\n\n", (gpuvram / 1048576), gpuver));
                sb.Append("================================================================\n");
                sb.Append(String.Format("End of info. Got them on {0}.", DateTime.Now.ToString()));

                // Copy to clipboard
                Clipboard.SetText(sb.ToString());
                sb = null;

                MessageBox.Show("Copied to clipboard.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                string       message      = String.Format("Exception type: {0}\nException message: {1}\nStack trace: {2}", ex.GetType(), ex.Message, ex.StackTrace);
                String       Error        = String.Format("An error has occured while copying the info to the clipboard.\n\nError:\n{0}\n\nDo you want to try again?", message);
                DialogResult dialogResult = MessageBox.Show(Error, "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dialogResult == DialogResult.Yes)
                {
                    CTC.PerformClick();
                }
            }
        }
示例#26
0
        private void InsertScript_Click(object sender, EventArgs e)
        {
            var commandText = string.Format(@"select
    c.name,
    t.name as TypeName,
    c.max_length,
    c.precision,
    c.scale,
    c.is_nullable
from [{0}].sys.schemas s (nolock)
join [{0}].sys.objects o (nolock)
	on s.schema_id = o.schema_id
join [{0}].sys.columns c (nolock)
	on o.object_id = c.object_id
join [{0}].sys.types t (nolock)
	on c.user_type_id = t.user_type_id
where
	s.name = '{1}'
	and o.name = '{2}'
order by c.column_id", DatabaseNode.Name, _owner, _name);

            Log.Write(LogLevel.Trace, commandText);
            var connectionString = DatabaseNode.Databases.Server.ConnectionString;
            var columns          = SqlClientFactory.Instance.ExecuteReader(connectionString, new ExecuteReaderRequest(commandText), 128, ReadColumn);

            var stringBuilder = new StringBuilder();
            var first         = true;

            foreach (var column in columns)
            {
                if (first)
                {
                    first = false;
                    stringBuilder.Append("declare\r\n");
                }
                else
                {
                    stringBuilder.Append(",\r\n");
                }

                var variableName = column.ColumnName;
                variableName = char.ToLower(variableName[0]) + variableName.Substring(1);
                var typeName = column.TypeName;

                switch (typeName)
                {
                case SqlDataTypeName.Char:
                case SqlDataTypeName.NChar:
                case SqlDataTypeName.NVarChar:
                case SqlDataTypeName.VarChar:
                    var maxLength       = column.MaxLength;
                    var precisionString = maxLength >= 0 ? maxLength.ToString() : "max";
                    typeName += "(" + precisionString + ")";
                    break;

                case SqlDataTypeName.Decimal:
                    var precision = column.Precision;
                    var scale     = column.Scale;
                    if (scale == 0)
                    {
                        typeName += "(" + precision + ")";
                    }
                    else
                    {
                        typeName += "(" + precision + ',' + scale + ")";
                    }
                    break;
                }

                stringBuilder.Append($"    @{variableName} {typeName}");
            }

            stringBuilder.AppendFormat("\r\n\r\ninsert into {0}.{1}\r\n(\r\n    ", _owner, _name);
            first = true;

            foreach (var column in columns)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    stringBuilder.Append(',');
                }

                stringBuilder.Append(column.ColumnName);
            }

            stringBuilder.Append("\r\n)\r\nselect\r\n");
            first = true;

            var stringTable = new StringTable(3);
            var sequence    = new Sequence();

            foreach (var column in columns)
            {
                var stringTableRow = stringTable.NewRow();
                var variableName   = column.ColumnName;
                variableName      = char.ToLower(variableName[0]) + variableName.Substring(1);
                stringTableRow[1] = $"@{variableName}";

                var text = $"as {column.ColumnName}";
                if (sequence.Next() < columns.Count - 1)
                {
                    text += ',';
                }

                stringTableRow[2] = text;
                stringTable.Rows.Add(stringTableRow);
            }

            stringBuilder.Append(stringTable.ToString(4));

            Clipboard.SetText(stringBuilder.ToString());
            var queryForm = (QueryForm)DataCommanderApplication.Instance.MainForm.ActiveMdiChild;

            queryForm.SetStatusbarPanelText("Copying script to clipboard finished.",
                                            queryForm.ColorTheme != null ? queryForm.ColorTheme.ForeColor : SystemColors.ControlText);
        }
示例#27
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_PASTE)
            {
                if (Clipboard.ContainsText() == true)
                {
                    string sign = Clipboard.GetText();

                    string signLower = sign.ToLower();

                    int pos = signLower.IndexOf("proc");

                    if (pos == -1)
                    {
                        return;
                    }

                    bool   PosInSpaceBefProcName = false;
                    bool   PosProcName           = false;
                    string spname = string.Empty;
                    for (int i = pos; i < sign.Length; ++i)
                    {
                        char c = sign[i];

                        if (PosInSpaceBefProcName == false)
                        {
                            if (SPSignature.IsWhitespace(c) == false)
                            {
                                continue;
                            }
                            else
                            {
                                PosInSpaceBefProcName = true;
                            }
                        }
                        else if (PosInSpaceBefProcName && PosProcName == false)
                        {
                            if (SPSignature.IsWhitespace(c))
                            {
                                continue;
                            }
                            else
                            {
                                spname     += c;
                                PosProcName = true;
                            }
                        }
                        else if (PosProcName)
                        {
                            if (SPSignature.IsWhitespace(c) == false && c != '(')
                            {
                                spname += c;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    PastedEvent(spname.Trim());
                }
            }
            base.WndProc(ref m);
        }
示例#28
0
        /// <summary>
        /// Exports the pipe text to the clipboard as a command-line style pipe.
        /// </summary>
        private void ExportAction(object sender, EventArgs e)
        {
            string text = PipeTextBox.Text;

            Clipboard.SetDataObject(Engine.GuiPipeToCli(text));
        }
示例#29
0
 public static void TextToClipboard(string text)
 {
     Clipboard.SetText(text);
     Clipboard.Flush();
 }
示例#30
0
 private void 获取不到网卡信息ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Clipboard.SetText("LODCTR /R");
     MessageBox.Show("管理员运行 cmd 执行命令【LODCTR /R】(已自动复制到剪切板),并重启程序!");
 }
示例#31
0
        private void HeaderKeysListBox_KeyDown(System.Object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (IMAGESET != null && IMAGESET.Count > 1)
                {
                    DialogResult res = MessageBox.Show("Delete selected key(s) from all headers (YES), or only current header (NO)?", "Warning", MessageBoxButtons.YesNoCancel);
                    if (res == DialogResult.Cancel)
                    {
                        return;
                    }
                    else if (res == DialogResult.Yes)
                    {
                        HeaderContextApplyAll.Checked = true;
                    }
                    else
                    {
                        HeaderContextApplyAll.Checked = false;
                    }
                }

                HeaderContextRemoveKeys.PerformClick();
                return;
            }

            if (e.Control && e.KeyCode == Keys.C)            //copy
            {
                String copy = "";
                for (int i = 0; i < HeaderKeysListBox.SelectedIndices.Count; i++)
                {
                    copy += HEADER[(int)HeaderKeysListBox.SelectedIndices[i]].GetFullyFomattedFITSLine() + Environment.NewLine;
                }

                if (copy.Length > 0)
                {
                    Clipboard.SetText(copy);
                }

                return;
            }

            if (e.Control && e.KeyCode == Keys.V)            //paste
            {
                if (HeaderKeysListBox.SelectedIndices.Count == 0)
                {
                    return;
                }

                String paste = Clipboard.GetText();
                if (paste == null || paste.Length == 0)
                {
                    return;
                }

                if (!JPMath.IsInteger((double)(paste.Length) / 80))
                {
                    return;
                }

                int           index = HeaderKeysListBox.SelectedIndices[HeaderKeysListBox.SelectedIndices.Count - 1];
                FITSHeaderKey key;
                int           nlines = paste.Length / 80;
                for (int i = 0; i < nlines; i++)
                {
                    key = new FITSHeaderKey(paste.Substring(i * 80, 80));
                    HEADER.AddKey(key, index + 1 + i);
                }
            }
        }
 private void btnPaste_Click(object sender, EventArgs e)
 {
     txtHostCode.BackColor = Color.LemonChiffon;
     txtHostCode.Text      = Clipboard.GetText();
 }
        public bool ExecuteCommand(CopyCommandArgs args, CommandExecutionContext executionContext)
        {
            ITextSelection selection = args.TextView.Selection;

            if (selection.SelectedSpans.Count != 1 || // Only handle single selections
                selection.Start.Position == selection.End.Position || // Don't handle zero-width selections
                !Options.Instance.CopyWithoutIndentation)
            {
                return(false);
            }


            // Only handle selections that starts with indented
            if (args.TextView.TryGetTextViewLineContainingBufferPosition(selection.Start.Position, out ITextViewLine viewLine))
            {
                if (viewLine.Start.Position == selection.Start.Position)
                {
                    return(false);
                }
            }

            ITextSnapshot snapshot = args.TextView.TextBuffer.CurrentSnapshot;

            IEnumerable <ITextSnapshotLine> lines = from line in snapshot.Lines
                                                    where line.Extent.IntersectsWith(selection.SelectedSpans[0])
                                                    select line;

            // Only handle when multiple lines are selected
            if (lines.Count() == 1)
            {
                return(false);
            }

            var indentation = selection.Start.Position.Position - viewLine.Start.Position;
            var spans       = new List <SnapshotSpan>();
            var sb          = new StringBuilder();

            var text = args.TextView.TextBuffer.CurrentSnapshot.GetText(viewLine.Start.Position, indentation);

            // Only handle cases when selection starts is on an empty indentation
            if (!string.IsNullOrWhiteSpace(text))
            {
                return(false);
            }

            foreach (ITextSnapshotLine line in lines)
            {
                if (line.Extent.IsEmpty)
                {
                    spans.Add(line.Extent);
                    sb.AppendLine();
                }
                else
                {
                    var end = line.Length - indentation;
                    if (selection.End.Position.Position < line.End.Position)
                    {
                        end -= (line.End.Position - selection.End.Position.Position);
                    }

                    if (!line.Extent.IsEmpty)
                    {
                        spans.Add(line.Extent);
                        sb.AppendLine(line.Extent.GetText());
                    }
                }
            }

            var rtf = _rtfService.GenerateRtf(new NormalizedSnapshotSpanCollection(spans), args.TextView);

            var data = new DataObject();

            data.SetText(rtf.TrimEnd(), TextDataFormat.Rtf);
            data.SetText(sb.ToString().TrimEnd(), TextDataFormat.UnicodeText);
            Clipboard.SetDataObject(data, false);

            return(true);
        }
示例#34
0
 protected void CopyClipboardToPipe(Clipboard CB, string text)
 {
     PipeTextView.Buffer.Text = Engine.CliPipeToGui(text);
 }
示例#35
0
        /// <summary>
        ///     Clears clipboard and copy a HTML fragment to the clipboard, providing additional meta-information.
        /// </summary>
        /// <param name="htmlFragment">a html fragment</param>
        /// <param name="title">optional title of the HTML document (can be null)</param>
        /// <param name="sourceUrl">optional Source URL of the HTML document, for resolving relative links (can be null)</param>
        public static void CopyToClipboard(string htmlFragment, string title, Uri sourceUrl)
        {
            if (title == null)
            {
                title = "From Clipboard";
            }

            StringBuilder sb = new StringBuilder();

            // Builds the CF_HTML header. See format specification here:
            // http://msdn.microsoft.com/library/default.asp?url=/workshop/networking/clipboard/htmlclipboard.asp

            // The string contains index references to other spots in the string, so we need placeholders so we can compute the offsets.
            // The <<<<<<<_ strings are just placeholders. We'll backpatch them actual values afterwards.
            // The string layout (<<<) also ensures that it can't appear in the body of the html because the <
            // character must be escaped.
            string header =
                @"Format:HTML Format
Version:1.0
StartHTML:<<<<<<<1
EndHTML:<<<<<<<2
StartFragment:<<<<<<<3
EndFragment:<<<<<<<4
StartSelection:<<<<<<<3
EndSelection:<<<<<<<3
";

            string pre =
                @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">
<HTML><HEAD><TITLE>" + title + @"</TITLE></HEAD><BODY><!--StartFragment-->";

            string post = @"<!--EndFragment--></BODY></HTML>";

            sb.Append(header);
            if (sourceUrl != null)
            {
                sb.AppendFormat("SourceURL:{0}", sourceUrl);
            }
            int startHtml = sb.Length;

            sb.Append(pre);
            int fragmentStart = sb.Length;

            sb.Append(htmlFragment);
            int fragmentEnd = sb.Length;

            sb.Append(post);
            int endHtml = sb.Length;

            // Backpatch offsets
            sb.Replace("<<<<<<<1", To8DigitString(startHtml));
            sb.Replace("<<<<<<<2", To8DigitString(endHtml));
            sb.Replace("<<<<<<<3", To8DigitString(fragmentStart));
            sb.Replace("<<<<<<<4", To8DigitString(fragmentEnd));


            // Finally copy to clipboard.
            string data = sb.ToString();

            Clipboard.Clear();
            Clipboard.SetText(data, TextDataFormat.Html);
        }
示例#36
0
 public void Register_Clipboard(Clipboard _myClipboard)
 {
     currentClipboard = _myClipboard;
 }
示例#37
0
        private LanguageServerOptions AddRequests(LanguageServerOptions options)
        {
            // Pathmap creation is seperated into 2 requests, 'pathmapFromClipboard' and 'pathmapApply'.
            // Pathmap generation request.
            options.OnRequest <object, string>("pathmapFromClipboard", _ => Task <string> .Run(() => {
                // Create the error handler for pathmap parser.
                ServerPathmapHandler error = new ServerPathmapHandler();

                // Get the pathmap. 'map' will be null if there is an error.
                try
                {
                    Pathmap map = Pathmap.ImportFromCSV(Clipboard.GetText(), error);

                    if (map == null)
                    {
                        return(error.Message);
                    }
                    else
                    {
                        lastMap = map;
                        return("success");
                    }
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
            }));

            // Pathmap save request.
            options.OnRequest <Newtonsoft.Json.Linq.JToken>("pathmapApply", uriToken => Task.Run(() => {
                // Save 'lastMap' to a file.
                string result = lastMap.ExportAsJSON();
                string output = uriToken["path"].ToObject <string>().Trim('/');
                using (var stream = new StreamWriter(output))
                    stream.Write(result);
            }));

            // Pathmap editor request.
            options.OnRequest <PathmapDocument, bool>("pathmapEditor", (editFileToken) => Task <bool> .Run(() => {
                DeltinScript compile;
                if (editFileToken.Text == null)
                {
                    string editor = Extras.CombinePathWithDotNotation(null, "!PathfindEditor.del");
                    compile       = new DeltinScript(new TranslateSettings(editor)
                    {
                        OutputLanguage = ConfigurationHandler.OutputLanguage
                    });
                }
                else
                {
                    compile = Editor.Generate(editFileToken.File, Pathmap.ImportFromText(editFileToken.Text), ConfigurationHandler.OutputLanguage);
                }

                Clipboard.SetText(compile.WorkshopCode);

                return(true);
            }));

            // semantic tokens
            options.OnRequest <Newtonsoft.Json.Linq.JToken, SemanticToken[]>("semanticTokens", (uriToken) => Task <SemanticToken[]> .Run(async() =>
            {
                await DocumentHandler.WaitForParse();
                SemanticToken[] tokens = LastParse.ScriptFromUri(new Uri(uriToken["fsPath"].ToObject <string>()))?.GetSemanticTokens();
                return(tokens ?? new SemanticToken[0]);
            }));

            // debugger start
            options.OnRequest <object>("debugger.start", args => Task.Run(() => {
                _debugger.Start();
                return(new object());
            }));

            // debugger stop
            options.OnRequest <object>("debugger.stop", args => Task.Run(() => {
                _debugger.Stop();
                return(new object());
            }));

            // debugger scopes
            options.OnRequest <ScopesArgs, DBPScope[]>("debugger.scopes", args => Task <DBPScope[]> .Run(() => {
                try
                {
                    if (_debugger.VariableCollection != null)
                    {
                        return(_debugger.VariableCollection.GetScopes(args));
                    }
                }
                catch (Exception ex)
                {
                    DebuggerException(ex);
                }
                return(new DBPScope[0]);
            }));

            // debugger variables
            options.OnRequest <VariablesArgs, DBPVariable[]>("debugger.variables", args => Task <DBPVariable[]> .Run(() => {
                try
                {
                    if (_debugger.VariableCollection != null)
                    {
                        return(_debugger.VariableCollection.GetVariables(args));
                    }
                }
                catch (Exception ex)
                {
                    DebuggerException(ex);
                }
                return(new DBPVariable[0]);
            }));

            // debugger evaluate
            options.OnRequest <EvaluateArgs, EvaluateResponse>("debugger.evaluate", args => Task <EvaluateResponse> .Run(() => {
                try
                {
                    return(_debugger.VariableCollection?.Evaluate(args));
                }
                catch (Exception ex)
                {
                    DebuggerException(ex);
                    return(EvaluateResponse.Empty);
                }
            }));

            // Decompile insert
            options.OnRequest <object>("decompile.insert", () => Task.Run(() =>
            {
                try
                {
                    var workshop  = new ConvertTextToElement(Clipboard.GetText()).Get();
                    var code      = new WorkshopDecompiler(workshop, new OmitLobbySettingsResolver(), new CodeFormattingOptions()).Decompile();
                    object result = new { success = true, code = code };
                    return(result);
                }
                catch (Exception ex)
                {
                    object result = new { success = false, code = ex.ToString() };
                    return(result);
                }
            }));

            return(options);
        }
示例#38
0
        public Scintilla()
        {
            this._state = new BitVector32(0);
            this._state[_acceptsReturnState] = true;
            this._state[_acceptsTabState] = true;

            _ns = (INativeScintilla)this;

            _caption = GetType().FullName;

            // Set up default encoding to UTF-8 which is the Scintilla's best supported.
            // .NET strings are UTF-16 but should be able to convert without any problems
            this.Encoding = Encoding.UTF8;

            // Ensure all style values have at least defaults
            _ns.StyleClearAll();

            _caret = new CaretInfo(this);
            _lines = new LineCollection(this);
            _selection = new Selection(this);
            _indicators = new IndicatorCollection(this);
            _snippets = new SnippetManager(this);
            _margins = new MarginCollection(this);
            _scrolling = new Scrolling(this);
            _whitespace = new Whitespace(this);
            _endOfLine = new EndOfLine(this);
            _clipboard = new Clipboard(this);
            _undoRedo = new UndoRedo(this);
            _dropMarkers = new DropMarkers(this);
            _hotspotStyle = new HotspotStyle(this);
            _callTip = new CallTip(this);
            _styles = new StyleCollection(this);
            _indentation = new Indentation(this);
            _markers = new MarkerCollection(this);
            _autoComplete = new AutoComplete(this);
            _documentHandler = new DocumentHandler(this);
            _lexing = new Lexing(this);
            _longLines = new LongLines(this);
            _commands = new Commands(this);
            _folding = new Folding(this);
            _configurationManager = new ConfigurationManager(this);
            _printing = new Printing(this);
            _findReplace = new FindReplace(this);
            _documentNavigation = new DocumentNavigation(this);
            _goto = new GoTo(this);

            _helpers.AddRange(new TopLevelHelper[]
            {
                _caret,
                _lines,
                _selection,
                _indicators,
                _snippets,
                _margins,
                _scrolling,
                _whitespace,
                _endOfLine,
                _clipboard,
                _undoRedo,
                _dropMarkers,
                _hotspotStyle,
                _styles,
                _indentation,
                _markers,
                _autoComplete,
                _documentHandler,
                _lexing,
                _longLines,
                _commands,
                _folding,
                _configurationManager,
                _printing,
                _findReplace,
                _documentNavigation,
                _goto
            });

            // Change from Scintilla's default black on white to
            // platform defaults for edit controls.
            base.BackColor = SystemColors.Window;
            base.ForeColor = SystemColors.WindowText;

            Styles[0].Font = Font;
            Styles[0].ForeColor = ForeColor;
            Styles[0].BackColor = BackColor;
            Styles.Default.BackColor = BackColor;
        }
示例#39
0
        public PathInfo(ImageResource imgRes)
            : base(imgRes)
        {
            BinaryPSDReader reader = imgRes.GetDataReader();

            this.PathNum = this.ID - 2000;
            this.ID = 2000;

            ushort numKnots = 0;
            int cnt = 0;
            this.Commands = new List<object>();
            while (reader.BytesToEnd > 0)
            {
                RecordType rtype = (RecordType)(int)reader.ReadUInt16();
                //Should always start with PathFill (0)
                if (cnt == 0 && rtype != RecordType.PathFill)
                    throw new Exception("PathInfo start error!");

                switch (rtype)
                {
                    case RecordType.InitialFill:
                        reader.BaseStream.Position += 1;
                        bool allPixelStart = reader.ReadBoolean();
                        reader.BaseStream.Position += 22;
                        break;

                    case RecordType.PathFill:
                        if (cnt != 0)
                            throw new Exception("Path fill?!?");
                        reader.BaseStream.Position += 24;
                        break;

                    case RecordType.Clipboard:
                        ERectangleF rct = new ERectangleF();
                        rct.Top = reader.ReadPSDSingle();
                        rct.Left = reader.ReadPSDSingle();
                        rct.Bottom = reader.ReadPSDSingle();
                        rct.Right = reader.ReadPSDSingle();
                        Clipboard clp = new Clipboard();
                        clp.Rectangle = rct;
                        clp.Scale = reader.ReadPSDSingle();
                        reader.BaseStream.Position += 4;
                        this.Commands.Add(clp);
                        break;

                    case RecordType.ClosedPathLength:
                    case RecordType.OpenPathLength:
                        numKnots = reader.ReadUInt16();
                        reader.BaseStream.Position += 22;
                        NewPath np = new NewPath();
                        np.Open = (rtype == RecordType.OpenPathLength);
                        this.Commands.Add(np);
                        break;

                    case RecordType.ClosedPathBezierKnotLinked:
                    case RecordType.ClosedPathBezierKnotUnlinked:
                    case RecordType.OpenPathBezierKnotLinked:
                    case RecordType.OpenPathBezierKnotUnlinked:
                        BezierKnot bz = new BezierKnot();

                        EPointF[] pts = new EPointF[3];
                        for (int i = 0; i < 3; i++)
                        {
                            float y = reader.ReadPSDFixedSingle(); //y comes first...
                            pts[i] = new EPointF(reader.ReadPSDFixedSingle(), y) / 256;
                        }
                        bz.Control1 = pts[0];
                        bz.Anchor = pts[1];
                        bz.Control2 = pts[2];
                        bz.Linked = (rtype == RecordType.ClosedPathBezierKnotLinked || rtype == RecordType.OpenPathBezierKnotLinked);
                        //bz.Open = (rtype == RecordType.OpenPathBezierKnotLinked || rtype == RecordType.OpenPathBezierKnotUnlinked);

                        this.Commands.Add(bz);
                        numKnots--;
                        break;
                }
                cnt++;
            }

            reader.Close();
        }