Ejemplo n.º 1
0
        public void FeelLucky()
        {
            if (string.IsNullOrEmpty(this.URLHTML))
            {
                this.VisitUrlAsync();
            }
            isBusy = true;
            var crawTargets = new List <XPathAnalyzer.CrawTarget>();
            ICollection <CrawlItem> existItems = CrawlItems;

            if (IsMultiData == ScriptWorkMode.One)
            {
                existItems = new List <CrawlItem> {
                    new CrawlItem {
                        Name = "temp", XPath = SelectXPath
                    }
                }
            }
            ;
            var task = TemporaryTask <XPathAnalyzer.CrawTarget> .AddTempTaskSimple(GlobalHelper.Get("key_659"),
                                                                                   HtmlDoc.DocumentNode.SearchPropertiesSmart(IsMultiData, existItems, RootXPath, RootFormat, IsAttribute),
                                                                                   crawTarget =>
            {
                crawTargets.Add(crawTarget);
                //var datas =
                //    HtmlDoc.DocumentNode.GetDataFromXPath(crawTarget.CrawItems, IsMultiData, crawTarget.RootXPath,
                //        RootFormat).ToList();
                //crawTarget.Datas = datas;
            }, d =>
            {
                isBusy = false;
                if (crawTargets.Count == 0)
                {
                    XLogSys.Print.Warn(GlobalHelper.Get("key_660"));
                    return;
                }

                var luckModel    = new FeelLuckyModel(crawTargets, HtmlDoc, IsMultiData);
                var view         = PluginProvider.GetObjectInstance <ICustomView>(GlobalHelper.Get("key_657")) as UserControl;
                view.DataContext = luckModel;

                var name   = GlobalHelper.Get("feellucky");
                var window = new Window {
                    Title = name
                };
                window.WindowState = WindowState.Maximized;
                window.Content     = view;
                luckModel.SetView(view, window);
                window.Activate();
                window.ShowDialog();
                if (window.DialogResult == true)

                {
                    var crawTarget = luckModel.CurrentTarget;
                    if (string.IsNullOrEmpty(RootXPath))
                    {
                        RootFormat = SelectorFormat.XPath;
                    }
                    RootXPath = crawTarget.RootXPath;


                    CrawlItems.AddRange(crawTarget.CrawItems.Where(r => r.IsEnabled && CrawlItems.FirstOrDefault(d2 => d2.XPath == r.XPath) == null));
                }
            });

            SysProcessManager.CurrentProcessTasks.Add(task);
        }
Ejemplo n.º 2
0
        public SmartCrawler()
        {
            Http                 = new HttpItem();
            CrawlItems           = new ObservableCollection <CrawlItem>();
            helper               = new HttpHelper();
            URL                  = "";
            HtmlDoc              = new HtmlDocument();
            SelectText           = "";
            IsMultiData          = ScriptWorkMode.List;
            IsAttribute          = true;
            URL                  = "www.cnblogs.com";
            ShareCookie          = new TextEditSelector();
            ShareCookie.GetItems = AppHelper.GetAllCrawlerNames(null);
            Commands2            = CommandBuilder.GetCommands(
                this,
                new[]
            {
                new Command(GlobalHelper.Get("key_302"), obj => AddNewItem(),
                            obj =>
                            string.IsNullOrEmpty(SelectName) == false && string.IsNullOrEmpty(SelectXPath) == false,
                            "add"),
                new Command(GlobalHelper.Get("search"), obj => GetXPathAsync(),
                            obj =>
                            currentXPaths != null, "magnify"),
                new Command(GlobalHelper.Get("feellucky"),
                            obj => FeelLucky(),
                            obj => IsMultiData != ScriptWorkMode.NoTransform && isBusy == false, "smiley_happy"
                            ),
                new Command(GlobalHelper.Get("key_624"), obj =>
                {
                    if (!(CrawlItems.Count > 0).SafeCheck(GlobalHelper.Get("key_625")))
                    {
                        return;
                    }

                    if (IsMultiData == ScriptWorkMode.List && CrawlItems.Count < 2)
                    {
                        MessageBox.Show(GlobalHelper.Get("key_626"), GlobalHelper.Get("key_99"));
                        return;
                    }
                    if (string.IsNullOrEmpty(this.URLHTML))
                    {
                        this.VisitUrlAsync();
                    }

                    var datas =
                        HtmlDoc.DocumentNode.GetDataFromXPath(CrawlItems, IsMultiData, RootXPath, RootFormat).Take(20)
                        .ToList();
                    var view = PluginProvider.GetObjectInstance <IDataViewer>(GlobalHelper.Get("key_230"));

                    var r = view.SetCurrentView(datas);
                    ControlExtended.DockableManager.AddDockAbleContent(
                        FrmState.Custom, r, GlobalHelper.Get("key_627"));

                    var rootPath =
                        XPath.GetMaxCompareXPath(CrawlItems.Select(d => d.XPath));
                    if (datas.Count > 1 && string.IsNullOrEmpty(RootXPath) && rootPath.Length > 0 &&
                        IsMultiData == ScriptWorkMode.List &&
                        MessageBox.Show(string.Format(GlobalHelper.Get("key_628"), rootPath), GlobalHelper.Get("key_99"),
                                        MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        RootXPath  = rootPath;
                        RootFormat = SelectorFormat.XPath;
                        HtmlDoc.CompileCrawItems(CrawlItems);
                        OnPropertyChanged("RootXPath");
                    }
                }, icon: "page_search")
            });
        }
Ejemplo n.º 3
0
 public Session(Guid id, PluginProvider pluginProvider, SocketSender socketSender)
 {
     this.Id             = id;
     this.pluginProvider = pluginProvider;
     this.socketSender   = socketSender;
 }
Ejemplo n.º 4
0
        private bool DropAction(string sender, object attr)
        {
            if (sender == "Drop")
            {
                var objs = attr as object[];
                if (objs.Count() == 2)
                {
                    var p = objs[0] as SmartGroup;
                    var t = objs[1] as XFrmWorkAttribute;

                    var item = PluginProvider.GetObjectInstance(t.MyType) as IColumnProcess;

                    if (string.IsNullOrEmpty(p.Name) == false)
                    {
                        item.Column = p.Name;
                    }
                    item.Father       = this;
                    this.shouldUpdate = false;
                    InsertModule(item);
                    this.shouldUpdate = true;
                    if (NeedConfig(item))
                    {
                        var window = PropertyGridFactory.GetPropertyWindow(item);

                        window.ShowDialog();
                    }
                    ETLMount++;
                }
            }
            if (sender == "Click")
            {
                var smart = attr as SmartGroup;
                if (smart != null)
                {
                    attr = smart.ColumnInfo;
                }
                var window  = PropertyGridFactory.GetPropertyWindow(attr);
                var oldProp = attr.UnsafeDictSerializePlus();

                window.Closed += (s, e) =>
                {
                    if (oldProp.IsEqual(attr.UnsafeDictSerializePlus()) == false)
                    {
                        RefreshSamples();
                    }
                };
                window.ShowDialog();
            }
            if (sender != "Delete")
            {
                return(true);
            }
            var a = attr as IColumnProcess;

            if (MessageBox.Show("确实要删除" + a.TypeName + "吗?", "提示信息", MessageBoxButton.OKCancel) !=
                MessageBoxResult.OK)
            {
                return(true);
            }
            CurrentETLTools.Remove(a);
            RefreshSamples();
            return(true);
        }
Ejemplo n.º 5
0
        public static IEnumerable <CustomPropertyInfo> GetToolProperty(Type tool, Object instance = null, bool mustBrowsable = true)
        {
            Object newinstance;

            if (instance == null)
            {
                instance    = PluginProvider.GetObjectInstance(tool);
                newinstance = instance;
            }
            else
            {
                newinstance = PluginProvider.GetObjectInstance(tool);
            }
            var propertys =
                tool.GetProperties().Where(
                    d => d.CanRead && d.CanWrite && AttributeHelper.IsEditableType(d.PropertyType)).ToArray();

            foreach (var propertyInfo in propertys.OrderBy(GetOrder))
            {
                var name = propertyInfo.Name;
                if (name == "ObjectID" || name == "Enabled" || name == "ColumnSelector")
                {
                    continue;
                }

                var property = new CustomPropertyInfo();

                string typeName     = null;
                var    defaultValue = GetDefaultValue(propertyInfo, newinstance, out typeName);
                var    currentValue = GetDefaultValue(propertyInfo, instance, out typeName);
                property.CurrentValue = currentValue;
                property.DefaultValue = defaultValue;
                var desc = GlobalHelper.Get("no_desc");
                // var fi =type.GetField(propertyInfo.Name);
                var browseable =
                    (BrowsableAttribute[])propertyInfo.GetCustomAttributes(typeof(BrowsableAttribute), false);
                if (browseable.Length > 0 && browseable[0].Browsable == false && mustBrowsable)
                {
                    continue;
                }
                var descriptionAttributes =
                    (LocalizedDescriptionAttribute[])propertyInfo.GetCustomAttributes(
                        typeof(LocalizedDescriptionAttribute), false);
                var nameAttributes =
                    (LocalizedDisplayNameAttribute[])propertyInfo.GetCustomAttributes(
                        typeof(LocalizedDisplayNameAttribute), false);
                if (nameAttributes.Length > 0)
                {
                    name = GlobalHelper.Get(nameAttributes[0].DisplayName);
                }
                if (descriptionAttributes.Length > 0)
                {
                    desc = GlobalHelper.Get(descriptionAttributes[0].Description);
                }
                desc                  = string.Join("\n", desc.Split('\n').Select(d => d.Trim('\t', ' ')));
                property.Desc         = desc;
                property.Name         = name;
                property.DefaultValue = defaultValue;
                property.OriginName   = propertyInfo.Name;
                property.TypeName     = typeName;
                yield return(property);
            }
        }
Ejemplo n.º 6
0
        public override bool Init()
        {
            base.Init();
            GitHubApi       = new GitHubAPI();
            MarketProjects  = new ObservableCollection <ProjectItem>();
            dockableManager = MainFrmUI as IDockableManager;
            dataManager     = MainFrmUI.PluginDictionary["DataManager"] as IDataManager;

            var aboutAuthor = new BindingAction(GlobalHelper.Get("key_262"), d =>
            {
                var view       = PluginProvider.GetObjectInstance <ICustomView>(GlobalHelper.Get("key_263"));
                var window     = new Window();
                window.Title   = GlobalHelper.Get("key_263");
                window.Content = view;
                window.ShowDialog();
            })
            {
                Description = GlobalHelper.Get("key_264"), Icon = "information"
            };
            var mainlink = new BindingAction(GlobalHelper.Get("key_265"), d =>
            {
                var url = "https://github.com/ferventdesert/Hawk";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = GlobalHelper.Get("key_266"), Icon = "home"
            };
            var helplink = new BindingAction(GlobalHelper.Get("key_267"), d =>
            {
                var url = "https://ferventdesert.github.io/Hawk/";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = GlobalHelper.Get("key_268"), Icon = "question"
            };

            var feedback = new BindingAction(GlobalHelper.Get("key_269"), d =>
            {
                var url = "https://github.com/ferventdesert/Hawk/issues";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = GlobalHelper.Get("key_270"), Icon = "reply_people"
            };


            var giveme = new BindingAction(GlobalHelper.Get("key_271"), d =>
            {
                var url =
                    "https://github.com/ferventdesert/Hawk/wiki/8-%E5%85%B3%E4%BA%8E%E4%BD%9C%E8%80%85%E5%92%8C%E6%8D%90%E8%B5%A0";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = GlobalHelper.Get("key_272"), Icon = "smiley_happy"
            };
            var blog = new BindingAction(GlobalHelper.Get("key_273"), d =>
            {
                var url = "http://www.cnblogs.com/buptzym/";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = GlobalHelper.Get("key_274"), Icon = "tower"
            };

            var update = new BindingAction(GlobalHelper.Get("checkupgrade"),
                                           d =>
            {
                AutoUpdater.Start("https://raw.githubusercontent.com/ferventdesert/Hawk/global/Hawk/autoupdate.xml");
            })
            {
                Description = GlobalHelper.Get("checkupgrade"), Icon = "arrow_up"
            };
            var helpCommands = new BindingAction(GlobalHelper.Get("key_275"))
            {
                Icon = "magnify"
            };

            helpCommands.ChildActions.Add(mainlink);
            helpCommands.ChildActions.Add(helplink);

            helpCommands.ChildActions.Add(feedback);
            helpCommands.ChildActions.Add(giveme);
            helpCommands.ChildActions.Add(blog);
            helpCommands.ChildActions.Add(aboutAuthor);
            helpCommands.ChildActions.Add(update);
            MainFrmUI.CommandCollection.Add(helpCommands);

            var hierarchy    = (Hierarchy)LogManager.GetRepository();
            var debugCommand = new BindingAction(GlobalHelper.Get("debug"))
            {
                ChildActions = new ObservableCollection <ICommand>
                {
                    new BindingAction(GlobalHelper.Get("key_277"))
                    {
                        ChildActions =
                            new ObservableCollection <ICommand>
                        {
                            new BindingAction("Debug", obj => hierarchy.Root.Level = Level.Debug),
                            new BindingAction("Info", obj => hierarchy.Root.Level  = Level.Info),
                            new BindingAction("Warn", obj => hierarchy.Root.Level  = Level.Warn),
                            new BindingAction("Error", obj => hierarchy.Root.Level = Level.Error),
                            new BindingAction("Fatal", obj => hierarchy.Root.Level = Level.Fatal)
                        }
                    }
                },
                Icon = ""
            };

            MainFrmUI.CommandCollection.Add(debugCommand);
            ProcessCollection = new ObservableCollection <IDataProcess>();


            CurrentProcessTasks = new ObservableCollection <TaskBase>();
            BindingCommands     = new BindingAction(GlobalHelper.Get("key_279"));
            var sysCommand = new BindingAction();

            sysCommand.ChildActions.Add(
                new Command(
                    GlobalHelper.Get("key_280"),
                    obj =>
            {
                if (
                    MessageBox.Show(GlobalHelper.Get("key_281"), GlobalHelper.Get("key_99"),
                                    MessageBoxButton.OKCancel) ==
                    MessageBoxResult.OK)
                {
                    ProcessCollection.RemoveElementsNoReturn(d => true, RemoveOperation);
                }
            }, obj => true,
                    "clear"));

            sysCommand.ChildActions.Add(
                new Command(
                    GlobalHelper.Get("key_282"),
                    obj =>
            {
                if (
                    MessageBox.Show(GlobalHelper.Get("key_283"), GlobalHelper.Get("key_99"),
                                    MessageBoxButton.OKCancel) ==
                    MessageBoxResult.OK)
                {
                    SaveCurrentTasks();
                }
            }, obj => true,
                    "save"));

            BindingCommands.ChildActions.Add(sysCommand);

            var taskAction1 = new BindingAction();


            taskAction1.ChildActions.Add(new Command(GlobalHelper.Get("key_284"),
                                                     async obj =>
            {
                var project = await GetRemoteProjectContent();
                if (project != null)
                {
                    foreach (var param in project.Parameters)
                    {
                        //TODO: how check if it is same? name?
                        if (CurrentProject.Parameters.FirstOrDefault(d => d.Name == param.Name) == null)
                        {
                            CurrentProject.Parameters.Add(param);
                        }
                    }
                    CurrentProject.ConfigSelector.SelectItem = project.ConfigSelector.SelectItem;
                }

                (obj as ProcessTask).Load(true);
            },
                                                     obj => obj is ProcessTask, "inbox_out"));



            BindingCommands.ChildActions.Add(taskAction1);
            var taskAction2 = new BindingAction(GlobalHelper.Get("key_287"));

            taskAction2.ChildActions.Add(new Command(GlobalHelper.Get("key_288"),
                                                     obj =>
            {
                var task = obj as TaskBase;
                task.Start();
            },
                                                     obj =>
            {
                var task = obj as TaskBase;
                return(task != null && task.IsStart == false);
            }, "play"));

            taskAction2.ChildActions.Add(new Command(GlobalHelper.Get("cancel_task"),
                                                     obj =>
            {
                var task = obj as TaskBase;
                if (task.IsStart)
                {
                    task.Remove();
                }

                task.Remove();
            },
                                                     obj =>
            {
                var task = obj as TaskBase;
                return(task != null);
            }, "cancel"));


            var runningTaskActions = new BindingAction(GlobalHelper.Get("key_290"));


            runningTaskActions.ChildActions.Add(new Command(GlobalHelper.Get("key_291"),
                                                            d => GetSelectedTask(d).Execute(d2 => d2.IsPause = true), d => ProcessTaskCanExecute(d, true), "pause"));
            runningTaskActions.ChildActions.Add(new Command(GlobalHelper.Get("key_292"),
                                                            d => GetSelectedTask(d).Execute(d2 => d2.IsPause = false), d => ProcessTaskCanExecute(d, false), "play"));

            runningTaskActions.ChildActions.Add(new Command(GlobalHelper.Get("key_293"),
                                                            d =>
            {
                var selectedTasks = GetSelectedTask(d).ToList();
                CurrentProcessTasks.RemoveElementsNoReturn(d2 => selectedTasks.Contains(d2), d2 => d2.Remove());
            }, d => ProcessTaskCanExecute(d, null), "delete"));


            runningTaskActions.ChildActions.Add(new Command(GlobalHelper.Get("property"),
                                                            d =>
            {
                var selectedTasks = GetSelectedTask(d).FirstOrDefault();
                PropertyGridFactory.GetPropertyWindow(selectedTasks).ShowDialog();
            }, d => ProcessTaskCanExecute(d, null), "settings"));



            BindingCommands.ChildActions.Add(runningTaskActions);
            BindingCommands.ChildActions.Add(runningTaskActions);


            var processAction = new BindingAction();

            dynamic processview =
                (MainFrmUI as IDockableManager).ViewDictionary.FirstOrDefault(d => d.Name == GlobalHelper.Get("key_794"))
                .View;

            processView = processview.processListBox as ListBox;


            var dataTimer    = new DispatcherTimer();
            var tickInterval = ConfigFile.GetConfig().Get <int>("AutoSaveTime");

            if (tickInterval > 0)
            {
                dataTimer.Tick    += timeCycle;
                dataTimer.Interval = new TimeSpan(0, 0, 0, tickInterval);
                dataTimer.Start();
            }


            processAction.ChildActions.Add(new Command(GlobalHelper.Get("key_294"), obj =>
            {
                if (obj != null)
                {
                    foreach (var process in GetSelectedProcess(obj))
                    {
                        if (process == null)
                        {
                            return;
                        }
                        var old = obj as IDataProcess;
                        if (old == null)
                        {
                            return;
                        }

                        var name = process.GetType().ToString().Split('.').Last();
                        var item = GetOneInstance(name, true, true);
                        (process as IDictionarySerializable).DictCopyTo(item as IDictionarySerializable);
                        item.Init();
                        item.Name = process.Name + "_copy";
                    }
                }
                else
                {
                    var plugin = GetOneInstance("SmartETLTool", true, true, true) as SmartETLTool;
                    plugin.Init();
                    ControlExtended.DockableManager.ActiveModelContent(plugin);
                }
            }, obj => true, "add"));

            processAction.ChildActions.Add(new Command(GlobalHelper.Get("key_295"), obj =>
            {
                if (obj == null)
                {
                    var plugin = GetOneInstance("SmartCrawler", true, true, true) as SmartCrawler;
                    plugin.Init();
                    ControlExtended.DockableManager.ActiveModelContent(plugin);
                }
                else
                {
                    foreach (var process in GetSelectedProcess(obj))
                    {
                        if (process == null)
                        {
                            return;
                        }
                        var name = process.GetType().ToString().Split('.').Last();
                        var item = GetOneInstance(name, true, true);

                        (process as IDictionarySerializable).DictCopyTo(item as IDictionarySerializable);
                        item.Init();
                        item.Name = process.Name + "_copy";
                    }
                }
            }, obj => true, "cloud_add"));


            processAction.ChildActions.Add(new Command(GlobalHelper.Get("key_296"), obj =>
            {
                if (obj == null)
                {
                    SaveCurrentTasks();
                }
                else
                {
                    foreach (var process in GetSelectedProcess(obj))
                    {
                        SaveTask(process, false);
                    }
                }
            }, obj => true, "save"));
            processAction.ChildActions.Add(new Command(GlobalHelper.Get("key_297"), obj =>
            {
                var process = GetSelectedProcess(obj).FirstOrDefault();
                if (process == null)
                {
                    return;
                }
                var view = (MainFrmUI as IDockableManager).ViewDictionary.FirstOrDefault(d => d.Model == process);
                if (view == null)
                {
                    LoadProcessView(process);
                }
                (MainFrmUI as IDockableManager).ActiveModelContent(process);

                process.Init();
            }, obj => true, "tv"));
            processAction.ChildActions.Add(new Command(GlobalHelper.Get("key_298"), obj =>
            {
                if (MessageBox.Show(GlobalHelper.Get("delete_confirm"), GlobalHelper.Get("key_99"), MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    return;
                }
                foreach (var process in GetSelectedProcess(obj))
                {
                    if (process == null)
                    {
                        return;
                    }

                    RemoveOperation(process);
                    ProcessCollection.Remove(process);
                    var tasks = CurrentProcessTasks.Where(d => d.Publisher == process).ToList();
                    if (tasks.Any())
                    {
                        foreach (var item in tasks)
                        {
                            item.Remove();
                            XLogSys.Print.Warn(string.Format(GlobalHelper.Get("key_299"), process.Name, item.Name));
                        }
                    }
                }
            }, obj => true, "delete"));
            processAction.ChildActions.Add(new Command(GlobalHelper.Get("key_300"),
                                                       obj => { ControlExtended.DockableManager.ActiveThisContent(GlobalHelper.Get("ModuleMgmt")); },
                                                       obj => true, "home"));
            processAction.ChildActions.Add(new Command(GlobalHelper.Get("find_ref"),
                                                       obj =>
            {
                PrintReferenced(obj as IDataProcess);
            }, obj => true, "diagram"));
            processAction.ChildActions.Add(new Command(GlobalHelper.Get("property"),
                                                       obj =>
            {
                PropertyGridFactory.GetPropertyWindow(obj).ShowDialog();
            }, obj => true, "settings"));

            BindingCommands.ChildActions.Add(processAction);
            BindingCommands.ChildActions.Add(taskAction2);


            var attributeactions = new BindingAction(GlobalHelper.Get("key_301"));

            attributeactions.ChildActions.Add(new Command(GlobalHelper.Get("key_302"), obj =>
            {
                var attr = obj as XFrmWorkAttribute;
                if (attr == null)
                {
                    return;
                }

                var process = GetOneInstance(attr.MyType.Name, newOne: true, isAddUI: true);
                process.Init();
            }, icon: "add"));
            BindingCommands.ChildActions.Add(attributeactions);


            var marketAction = new BindingAction();

            marketAction.ChildActions.Add(new Command(GlobalHelper.Get("connect_market"), async obj =>
            {
                GitHubApi.Connect();
                MarketProjects.Clear();
                ControlExtended.SetBusy(ProgressBarState.Indeterminate, message: GlobalHelper.Get("get_remote_projects"));
                MarketProjects.AddRange(await GitHubApi.GetProjects());
                ControlExtended.SetBusy(ProgressBarState.NoProgress);
            }, icon: "refresh"));
            marketAction.ChildActions.Add(new Command(GlobalHelper.Get("key_240"), obj =>
            {
                var window = PropertyGridFactory.GetPropertyWindow(GitHubApi);
                window.ShowDialog();
            }, icon: "settings"));

            BindingCommands.ChildActions.Add(marketAction);


            var marketProjectAction = new BindingAction();

            marketProjectAction.ChildActions.Add(new Command(GlobalHelper.Get("key_307"), async obj =>
            {
                var projectItem = obj as ProjectItem;
                var keep        = MessageBoxResult.Yes;
                if (projectItem == null)
                {
                    return;
                }
                if (this.CurrentProcessCollections.Any() || this.dataManager.DataCollections.Any())
                {
                    keep = MessageBox.Show(GlobalHelper.Get("keep_old_datas"), GlobalHelper.Get("key_99"),
                                           MessageBoxButton.YesNoCancel);
                    if (keep == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }
                var proj = await this.GetRemoteProjectContent(projectItem);
                LoadProject(proj, keep == MessageBoxResult.Yes);
            }, icon: "config"));


            var config = ConfigFile.GetConfig <DataMiningConfig>();

            if (config.Projects.Any())
            {
                var project = config.Projects.FirstOrDefault();
                if (project != null)
                {
                    ControlExtended.SafeInvoke(() => { CurrentProject = LoadProject(project.SavePath); }, LogType.Info,
                                               GlobalHelper.Get("key_303"));
                }
            }
            BindingCommands.ChildActions.Add(marketProjectAction);
            if (MainDescription.IsUIForm)
            {
                ProgramNameFilterView =
                    new ListCollectionView(PluginProvider.GetPluginCollection(typeof(IDataProcess)).ToList());

                ProgramNameFilterView.GroupDescriptions.Clear();
                ProgramNameFilterView.GroupDescriptions.Add(new PropertyGroupDescription("GroupName"));
                var taskView    = PluginProvider.GetObjectInstance <ICustomView>(GlobalHelper.Get("key_304"));
                var userControl = taskView as UserControl;
                if (userControl != null)
                {
                    userControl.DataContext = this;
                    dynamic control = userControl;
                    currentProcessTasksView = control.currentProcessTasksView;
                    ((INotifyCollectionChanged)CurrentProcessTasks).CollectionChanged += (s, e) =>
                    {
                        ControlExtended.UIInvoke(() =>
                        {
                            if (e.Action == NotifyCollectionChangedAction.Add)
                            {
                                dockableManager.ActiveThisContent(GlobalHelper.Get("key_304"));
                            }
                        });
                    }
                    ;
                    dockableManager.AddDockAbleContent(taskView.FrmState, this, taskView, GlobalHelper.Get("key_304"));
                }
                ProcessCollectionView = new ListCollectionView(ProcessCollection);
                ProcessCollectionView.GroupDescriptions.Clear();
                ProcessCollectionView.GroupDescriptions.Add(new PropertyGroupDescription("TypeName"));
            }

            var fileCommand = MainFrmUI.CommandCollection.FirstOrDefault(d => d.Text == GlobalHelper.Get("key_305"));

            fileCommand.ChildActions.Add(new BindingAction(GlobalHelper.Get("key_306"), obj => CreateNewProject())
            {
                Icon = "add"
            });
            fileCommand.ChildActions.Add(new BindingAction(GlobalHelper.Get("key_307"), obj =>
            {
                var keep = MessageBoxResult.No;
                if (this.CurrentProcessCollections.Any() || this.dataManager.DataCollections.Any())
                {
                    keep = MessageBox.Show(GlobalHelper.Get("keep_old_datas"), GlobalHelper.Get("key_99"),
                                           MessageBoxButton.YesNoCancel);
                    if (keep == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }
                LoadProject(keepLast: keep == MessageBoxResult.Yes);
            })
            {
                Icon = "inbox_out"
            });
            fileCommand.ChildActions.Add(new BindingAction(GlobalHelper.Get("key_308"), obj => SaveCurrentProject())
            {
                Icon = "save"
            });
            fileCommand.ChildActions.Add(new BindingAction(GlobalHelper.Get("key_309"), obj => SaveCurrentProject(false))
            {
                Icon = "save"
            });
            fileCommand.ChildActions.Add(new BindingAction(GlobalHelper.Get("generate_project_doc"), obj =>
            {
                if (CurrentProject == null)
                {
                    return;
                }
                var doc     = this.GenerateRemark(this.ProcessCollection);
                var docItem = new DocumentItem()
                {
                    Title = this.CurrentProject.Name, Document = doc
                };
                PropertyGridFactory.GetPropertyWindow(docItem).ShowDialog();
            }, obj => CurrentProject != null)
            {
                Icon = "help"
            });
            fileCommand.ChildActions.Add(new BindingAction(GlobalHelper.Get("recent_file"))
            {
                Icon         = "save",
                ChildActions =
                    new ObservableCollection <ICommand>(config.Projects.Select(d => new BindingAction(d.SavePath, obj =>
                {
                    var keep = MessageBoxResult.No;
                    if (this.CurrentProcessCollections.Any() || this.dataManager.DataCollections.Any())
                    {
                        keep = MessageBox.Show(GlobalHelper.Get("keep_old_datas"), GlobalHelper.Get("key_99"),
                                               MessageBoxButton.YesNoCancel);
                        if (keep == MessageBoxResult.Cancel)
                        {
                            return;
                        }
                    }
                    LoadProject(d.SavePath, keep == MessageBoxResult.Yes);
                })
                {
                    Icon = "folder"
                }))
            });
            var languageMenu = new BindingAction(GlobalHelper.Get("key_lang"))
            {
                Icon = "layout"
            };

            var files = Directory.GetFiles("Lang");

            foreach (var f in files)
            {
                var ba = new BindingAction(f, obj => { AppHelper.LoadLanguage(f); })
                {
                    Icon = "layout"
                };

                languageMenu.ChildActions.Add(ba);
            }
            //  helpCommands.ChildActions.Add(languageMenu);

            return(true);
        }
Ejemplo n.º 7
0
        public static object Set(this IDictionary <string, object> dict, string key, object oldValue, Type type = null)
        {
            object value;
            object data = null;

            if (dict == null)
            {
                return(oldValue);
            }
            if (type == null)
            {
                if (oldValue != null)
                {
                    type = oldValue.GetType();
                }
            }
            if (type == null)
            {
                return(null);
            }
            if (dict.TryGetValue(key, out data))
            {
                if (type.IsEnum)
                {
                    if (data is int)
                    {
                        object index = Convert.ChangeType(data, typeof(int));
                        return(index);
                    }
                    else
                    {
                        string item  = data.ToString();
                        object index = Enum.Parse(type, item);
                        return(index);
                    }
                }
                if (type == typeof(XFrmWorkAttribute))
                {
                    var item = (string)data;
                    XFrmWorkAttribute newone = PluginProvider.GetPlugin(item);
                    return(newone);
                }

                if (data == null)
                {
                    return(oldValue);
                }
                try
                {
                    value = Convert.ChangeType(data, type);
                }
                catch (Exception ex)
                {
                    XLogSys.Print.Error("字典序列化失败" + ex);
                    return(null);
                }

                return(value);
            }

            return(oldValue);
        }
Ejemplo n.º 8
0
        public override bool Init()
        {
            base.Init();
            dockableManager    = MainFrmUI as IDockableManager;
            dataManager        = MainFrmUI.PluginDictionary["数据管理"] as IDataManager;
            propertyGridWindow = MainFrmUI.PluginDictionary["属性配置器"] as XFrmWorkPropertyGrid;

            var aboutAuthor = new BindingAction("关于", d =>
            {
                var view       = PluginProvider.GetObjectInstance <ICustomView>("关于作者");
                var window     = new Window();
                window.Title   = "关于作者";
                window.Content = view;
                window.ShowDialog();
            })
            {
                Description = "Hawk版本与检查更新", Icon = "information"
            };
            var mainlink = new BindingAction("项目主页", d =>
            {
                var url = "https://github.com/ferventdesert/Hawk";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = "访问Hawk的开源项目地址", Icon = "home"
            };
            var helplink = new BindingAction("使用文档", d =>
            {
                var url = "https://github.com/ferventdesert/Hawk/wiki";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = "这里有使用Hawk的案例与完整教程", Icon = "question"
            };

            var feedback = new BindingAction("反馈问题", d =>
            {
                var url = "https://github.com/ferventdesert/Hawk/issues";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = "出现bug或者问题了?欢迎反馈", Icon = "reply_people"
            };


            var giveme = new BindingAction("捐赠", d =>
            {
                var url = "https://github.com/ferventdesert/Hawk/wiki/8-%E5%85%B3%E4%BA%8E%E4%BD%9C%E8%80%85%E5%92%8C%E6%8D%90%E8%B5%A0";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = "你的支持是作者更新Hawk的动力", Icon = "smiley_happy"
            };
            var blog = new BindingAction("博客", d =>
            {
                var url = "http://www.cnblogs.com/buptzym/";
                System.Diagnostics.Process.Start(url);
            })
            {
                Description = "作者沙漠君的博客", Icon = "tower"
            };

            var helpCommands = new BindingAction("帮助")
            {
                Icon = "magnify"
            };

            helpCommands.ChildActions.Add(mainlink);
            helpCommands.ChildActions.Add(helplink);

            helpCommands.ChildActions.Add(feedback);
            helpCommands.ChildActions.Add(giveme);
            helpCommands.ChildActions.Add(blog);
            helpCommands.ChildActions.Add(aboutAuthor);
            MainFrmUI.CommandCollection.Add(helpCommands);

            Hierarchy hierarchy    = (Hierarchy)LogManager.GetRepository();
            var       debugCommand = new BindingAction("调试")
            {
                ChildActions = new ObservableCollection <ICommand>()
                {
                    new BindingAction("级别设置")
                    {
                        ChildActions =
                            new ObservableCollection <ICommand>()
                        {
                            new BindingAction("Debug", obj => hierarchy.Root.Level = Level.Debug),
                            new BindingAction("Info", obj => hierarchy.Root.Level  = Level.Info),
                            new BindingAction("Warn", obj => hierarchy.Root.Level  = Level.Warn),
                            new BindingAction("Error", obj => hierarchy.Root.Level = Level.Error),
                            new BindingAction("Fatal", obj => hierarchy.Root.Level = Level.Fatal),
                        }
                    }
                },

                Icon = ""
            };

            MainFrmUI.CommandCollection.Add(debugCommand);
            debugCommand?.ChildActions.Add(new BindingAction("Web请求统计", obj =>
            {
                if (debugGrid == null)
                {
                    debugGrid = PropertyGridFactory.GetInstance(RequestManager.Instance);
                }
                else
                {
                    debugGrid.SetObjectView(RequestManager.Instance);
                }

                dynamic control =
                    (this.MainFrmUI as IDockableManager).ViewDictionary.FirstOrDefault(d => d.View == debugGrid)
                    ?.Container;
                if (control != null)
                {
                    control.Show();
                }

                else
                {
                    (this.MainFrmUI as IDockableManager).AddDockAbleContent(FrmState.Mini, debugGrid, "Web请求统计");
                }
            })
            {
                Icon = "graph_line"
            });
            ProcessCollection = new ObservableCollection <IDataProcess>();


            CurrentProcessTasks = new ObservableCollection <TaskBase>();
            BindingCommands     = new BindingAction("运行");
            var sysCommand = new BindingAction();

            sysCommand.ChildActions.Add(
                new Command(
                    "清空任务列表",
                    obj =>
            {
                if (MessageBox.Show("确定清空所有算法模块么?", "提示信息", MessageBoxButton.OKCancel) ==
                    MessageBoxResult.OK)
                {
                    ProcessCollection.RemoveElementsNoReturn(d => true, RemoveOperation);
                }
            }, obj => true,
                    "clear"));

            sysCommand.ChildActions.Add(
                new Command(
                    "保存全部任务",
                    obj =>
            {
                if (MessageBox.Show("确定保存所有算法模块么?", "提示信息", MessageBoxButton.OKCancel) ==
                    MessageBoxResult.OK)
                {
                    SaveCurrentTasks();
                }
            }, obj => true,
                    "save"));

            BindingCommands.ChildActions.Add(sysCommand);

            var taskAction1 = new BindingAction();


            taskAction1.ChildActions.Add(new Command("加载本任务",
                                                     obj => (obj as ProcessTask).Load(true),
                                                     obj => obj is ProcessTask, "inbox_out"));


            taskAction1.ChildActions.Add(new Command("删除任务",
                                                     obj => CurrentProject.Tasks.Remove(obj as ProcessTask),
                                                     obj => obj is ProcessTask, "delete"));
            taskAction1.ChildActions.Add(new Command("执行任务脚本",
                                                     (obj => (obj as ProcessTask).EvalScript()),
                                                     obj => (obj is ProcessTask) && CurrentProcessCollections.FirstOrDefault(d => d.Name == (obj as ProcessTask).Name) != null));
            taskAction1.ChildActions.Add(new Command("配置", obj => PropertyGridFactory.GetPropertyWindow(obj).ShowDialog()
                                                     ));



            BindingCommands.ChildActions.Add(taskAction1);
            var taskAction2 = new BindingAction("任务列表2");

            taskAction2.ChildActions.Add(new Command("开始任务",
                                                     obj =>
            {
                var task = obj as TaskBase;
                task.Start();
            },
                                                     obj =>
            {
                var task = obj as TaskBase;
                return(task != null && task.IsStart == false);
            }, "play"));

            taskAction2.ChildActions.Add(new Command("取消任务",
                                                     obj =>
            {
                var task = obj as TaskBase;
                if (task.IsStart)
                {
                    task.Remove();
                }

                task.Remove();
            },
                                                     obj =>
            {
                var task = obj as TaskBase;
                return(task != null);
            }, "cancel"));


            var taskListAction = new BindingAction("任务列表命令");

            taskListAction.ChildActions.Add(new Command("全选",
                                                        d => CurrentProcessTasks.Execute(d2 => d2.IsSelected = true), null, "check"));

            taskListAction.ChildActions.Add(new Command("反选",
                                                        d => CurrentProcessTasks.Execute(d2 => d2.IsSelected = !d2.IsSelected), null, "redo"));

            taskListAction.ChildActions.Add(new Command("暂停",
                                                        d => CurrentProcessTasks.Where(d2 => d2.IsSelected).Execute(d2 => d2.IsPause = true), null, "pause"));
            taskListAction.ChildActions.Add(new Command("恢复",
                                                        d => CurrentProcessTasks.Where(d2 => d2.IsSelected).Execute(d2 => d2.IsPause = false), null, "play"));

            taskListAction.ChildActions.Add(new Command("取消",
                                                        d => CurrentProcessTasks.RemoveElementsNoReturn(d2 => d2.IsSelected, d2 => d2.Remove()), null, "delete"));

            BindingCommands.ChildActions.Add(taskListAction);

            BindingCommands.ChildActions.Add(taskListAction);

            var processAction = new BindingAction();



            processAction.ChildActions.Add(new Command("新建或复制数据清洗", obj =>
            {
                if (obj != null)
                {
                    var process = GetProcess(obj);
                    if (process == null)
                    {
                        return;
                    }
                    var old = obj as IDataProcess;
                    if (old == null)
                    {
                        return;
                    }

                    //ProcessCollection.Remove(old);
                    var name = process.GetType().ToString().Split('.').Last();

                    var item = GetOneInstance(name, true, true);
                    (process as IDictionarySerializable).DictCopyTo(item as IDictionarySerializable);
                    item.Init();
                    item.Name = old.Name + "_copy";
                    ProcessCollection.Add(item);
                }
                else
                {
                    var plugin = this.GetOneInstance("SmartETLTool", true, true, true) as SmartETLTool;
                    plugin.Init();
                    ControlExtended.DockableManager.ActiveModelContent(plugin);
                }
            }, obj => true, "add"));

            processAction.ChildActions.Add(new Command("新建或复制采集器", obj =>
            {
                if (obj == null)
                {
                    var plugin = this.GetOneInstance("SmartCrawler", true, true, true) as SmartCrawler;
                    plugin.Init();
                    ControlExtended.DockableManager.ActiveModelContent(plugin);
                }
                else
                {
                    var process = GetProcess(obj);
                    if (process == null)
                    {
                        return;
                    }
                    var old = obj as IDataProcess;
                    if (old == null)
                    {
                        return;
                    }

                    //ProcessCollection.Remove(old);
                    var name = process.GetType().ToString().Split('.').Last();

                    var item = GetOneInstance(name, true, true);
                    (process as IDictionarySerializable).DictCopyTo(item as IDictionarySerializable);
                    item.Init();
                    item.Name = old.Name + "_copy";
                    ProcessCollection.Add(item);
                }
            }, obj => true, "cloud_add"));



            processAction.ChildActions.Add(new Command("保存任务", obj =>
            {
                var process = obj as IDataProcess;
                if (process == null)
                {
                    foreach (var target in CurrentProcessCollections)
                    {
                        SaveTask(target, false);
                    }
                }
                else
                {
                    SaveTask(process, true);
                }
            }, obj => true, "save"));
            processAction.ChildActions.Add(new Command("显示并配置", obj =>
            {
                var process = GetProcess(obj);
                if (process == null)
                {
                    return;
                }
                var view = (MainFrmUI as IDockableManager).ViewDictionary.FirstOrDefault(d => d.Model == process);
                if (view == null)
                {
                    LoadProcessView(process);
                }
                (MainFrmUI as IDockableManager).ActiveModelContent(process);
                ShowConfigUI(process);
            }, obj => true, "delete"));
            processAction.ChildActions.Add(new Command("移除", obj =>
            {
                var process = GetProcess(obj);
                if (process == null)
                {
                    return;
                }

                RemoveOperation(process);
                ProcessCollection.Remove(process);
                var tasks = this.CurrentProcessTasks.Where(d => d.Publisher == process).ToList();
                if (tasks.Any())
                {
                    foreach (var item in tasks)
                    {
                        item.Remove();
                        XLogSys.Print.Warn($"由于任务{process.Name} 已经被删除, 相关任务${item.Name} 也已经被强行取消");
                    }
                }
                ShowConfigUI(null);
            }, obj => true, "delete"));
            processAction.ChildActions.Add(new Command("打开欢迎页面", obj =>
            {
                ControlExtended.DockableManager.ActiveThisContent("模块管理");
            }, obj => true, "home"));


            BindingCommands.ChildActions.Add(processAction);
            BindingCommands.ChildActions.Add(taskAction2);
            var attributeactions = new BindingAction("模块");

            attributeactions.ChildActions.Add(new Command("添加", obj =>
            {
                var attr = obj as XFrmWorkAttribute;
                if (attr == null)
                {
                    return;
                }

                var process = GetOneInstance(attr.MyType.Name, newOne: true, isAddUI: true);
                process.Init();
            }, icon: "add"));
            BindingCommands.ChildActions.Add(attributeactions);

            var config = ConfigFile.GetConfig <DataMiningConfig>();

            if (config.Projects.Any())
            {
                var project = config.Projects.FirstOrDefault();
                if (project != null)
                {
                    ControlExtended.SafeInvoke(() =>
                    {
                        currentProject = ProjectItem.LoadProject(project.SavePath);
                        NotifyCurrentProjectChanged();
                    }, LogType.Info, "加载默认工程");
                }
            }

            if (MainDescription.IsUIForm)
            {
                ProgramNameFilterView =
                    new ListCollectionView(PluginProvider.GetPluginCollection(typeof(IDataProcess)).ToList());

                ProgramNameFilterView.GroupDescriptions.Clear();
                ProgramNameFilterView.GroupDescriptions.Add(new PropertyGroupDescription("GroupName"));
                var taskView    = PluginProvider.GetObjectInstance <ICustomView>("工作线程视图");
                var userControl = taskView as UserControl;
                if (userControl != null)
                {
                    userControl.DataContext = this;
                    ((INotifyCollectionChanged)CurrentProcessTasks).CollectionChanged += (s, e) =>
                    {
                        ControlExtended.UIInvoke(() => {
                            if (e.Action == NotifyCollectionChangedAction.Add)
                            {
                                dockableManager.ActiveThisContent("工作线程视图");
                            }
                        });
                    }
                    ;
                    dockableManager.AddDockAbleContent(taskView.FrmState, this, taskView, "工作线程视图");
                }
                ProcessCollectionView = new ListCollectionView(ProcessCollection);
                ProcessCollectionView.GroupDescriptions.Clear();
                ProcessCollectionView.GroupDescriptions.Add(new PropertyGroupDescription("TypeName"));



                OnPropertyChanged("ProjectTaskList");
                ProjectTaskList = new ListCollectionView(CurrentProject.Tasks);
                ProjectTaskList.GroupDescriptions.Clear();

                ProjectTaskList.GroupDescriptions.Add(new PropertyGroupDescription("TypeName"));
                OnPropertyChanged("ProjectTaskList");
            }

            var file = MainFrmUI.CommandCollection.FirstOrDefault(d => d.Text == "文件");

            file.ChildActions.Add(new BindingAction("新建项目", obj => CreateNewProject())
            {
                Icon = "add"
            });
            file.ChildActions.Add(new BindingAction("加载项目", obj => LoadProject())
            {
                Icon = "inbox_out"
            });
            file.ChildActions.Add(new BindingAction("保存项目", obj => SaveCurrentProject())
            {
                Icon = "save"
            });
            file.ChildActions.Add(new BindingAction("项目另存为", obj => SaveCurrentProject(false))
            {
                Icon = "save"
            });
            file.ChildActions.Add(new BindingAction("最近打开的文件")
            {
                Icon         = "save",
                ChildActions = new ObservableCollection <ICommand>(config.Projects.Select(d => new BindingAction(d.SavePath, obj => LoadProject(d.SavePath))
                {
                    Icon = "folder"
                }))
            });
            return(true);
        }
Ejemplo n.º 9
0
        public override bool Init()
        {
            if (MainDescription.IsUIForm)
            {
                DataCollections = new SafeObservable <DataCollection>();
                dockableManager = MainFrmUI as IDockableManager;
                var views = "223:Mini 794:Middle";
                foreach (var item in views.Split(' '))
                {
                    var item2   = item.Split(':');
                    var name    = item2[0];
                    var control = FrmState.Mini;
                    Enum.TryParse(item2[1], out control);
                    var itemName = "key_" + name;
                    itemName = GlobalHelper.Get(itemName);
                    var view        = PluginProvider.GetObjectInstance <ICustomView>(GlobalHelper.Get(itemName));
                    var userControl = view as UserControl;
                    if (userControl != null)
                    {
                        if (name == "223")
                        {
                            dynamic dcontrol = userControl;
                            dataListBox = dcontrol.dataListBox as ListBox;
                        }
                        userControl.DataContext = MainFrmUI;
                        dockableManager.AddDockAbleContent(control, view, itemName);
                    }
                }
            }

            else
            {
                DataCollections = new ObservableCollection <DataCollection>();
            }

            processManager = MainFrmUI.PluginDictionary["DataProcessManager"] as IProcessManager;


            commands = new List <ICommand>();
            var dbaction = new BindingAction();

            dbaction.ChildActions.Add(new Command(GlobalHelper.Get("key_224"),
                                                  obj =>
            {
                var w = PropertyGridFactory.GetPropertyWindow(obj);
                w.ShowDialog();
            },
                                                  obj => obj != null, "edit"));
            dbaction.ChildActions.Add(
                new Command(GlobalHelper.Get("key_142"), obj => RefreshConnect(obj as IDataBaseConnector),
                            obj => obj != null, "refresh"));
            dbaction.ChildActions.Add(
                new Command(GlobalHelper.Get("key_213"), obj =>
            {
                var query          = new QueryEntity();
                query.Connector    = obj as IDataBaseConnector;
                query.GetQueryFunc = d =>
                {
                    if (d == null)
                    {
                        return;
                    }
                    if (d.Any() == false)
                    {
                        return;
                    }

                    AddDataCollection(d, GetNewName());
                };
                PropertyGridFactory.GetPropertyWindow(query).ShowDialog();
            }, obj => obj != null, "magnify"));
            dbaction.ChildActions.Add(
                new Command(GlobalHelper.Get("key_225"), obj =>
            {
                if (
                    MessageBox.Show(GlobalHelper.Get("key_226"), GlobalHelper.Get("key_99"),
                                    MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                {
                    var con = obj as DBConnectorBase;
                    _dbConnections.Remove(con);
                }
            }, obj => obj != null, "delete"));
            var dataaction = new BindingAction();


            var tableAction = new BindingAction();

            tableAction.ChildActions.Add(new Command(
                                             GlobalHelper.Get("view"),
                                             async obj =>
            {
                var items = obj as TableInfo;
                List <IFreeDocument> dataAll = null;
                try
                {
                    dataAll = await
                              GetDataFromDB(items.Connector, items.Name, true,
                                            items.Connector is FileManager ? -1 : 200);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(GlobalHelper.Get("key_228") + ex.Message);
                    return;
                }


                if (dataAll == null || dataAll.Count == 0)
                {
                    XLogSys.Print.Warn(GlobalHelper.Get("key_229"));
                    return;
                }
                if (items.Connector is FileManager)
                {
                    var file = (items.Connector as FileManager).LastFileName;
                    var name = Path.GetFileNameWithoutExtension(file);
                    AddDataCollection(dataAll, name);
                    return;
                }
                var excel = PluginProvider.GetObjectInstance <IDataViewer>(GlobalHelper.Get("key_230"));
                if (excel == null)
                {
                    return;
                }
                var view = excel.SetCurrentView(dataAll.Select(d => d).ToList());

                if (ControlExtended.DockableManager != null)
                {
                    ControlExtended.DockableManager.AddDockAbleContent(
                        FrmState.Custom, view, items.Name);
                }
            },
                                             obj => obj != null));
            tableAction.ChildActions.Add(new Command(
                                             GlobalHelper.Get("key_231"),
                                             async obj =>
            {
                var items = obj as TableInfo;
                var datas = await GetDataFromDB(items.Connector, items.Name, true);
                if (datas == null)
                {
                    return;
                }
                AddDataCollection(datas, items.Name);
            },
                                             obj => obj != null, "add"));
            tableAction.ChildActions.Add(new Command(
                                             GlobalHelper.Get("key_232"),
                                             obj =>
            {
                var con = obj as TableInfo;
                ReadCollection(con.Connector, con.Name, true);
            },
                                             obj => obj != null, "layer_add"));
            tableAction.ChildActions.Add(new Command(
                                             GlobalHelper.Get("key_233"),
                                             obj =>
            {
                var items = obj as TableInfo;

                DropTable(items.Connector, items.Name);
            },
                                             obj => obj != null, "delete"));
            tableAction.ChildActions.Add(new Command(
                                             GlobalHelper.Get("key_234"),
                                             obj =>
            {
                var w = PropertyGridFactory.GetPropertyWindow(obj);
                w.ShowDialog();
            },
                                             obj => obj != null, "edit"));
            tableAction.ChildActions.Add(new Command(
                                             GlobalHelper.Get("key_213"),
                                             obj =>
            {
                var query          = new QueryEntity();
                query.TableInfo    = obj as TableInfo;
                query.Connector    = query.TableInfo.Connector;
                query.GetQueryFunc = d =>
                {
                    if (d == null)
                    {
                        return;
                    }
                    if (d.Any() == false)
                    {
                        return;
                    }

                    AddDataCollection(d, GetNewName());
                };
                PropertyGridFactory.GetPropertyWindow(query).ShowDialog();
            }, obj => obj != null, "magnify"));


            var visitData = new BindingAction(GlobalHelper.Get("key_235"));

            var visitCommands = PluginProvider.GetPluginCollection(typeof(IDataViewer)).Select(
                d =>
            {
                var comm     = new Command(d.Name);
                comm.Execute = d2 =>
                {
                    var data = d2 as DataCollection;

                    if (data.Count == 0)
                    {
                        MessageBox.Show(GlobalHelper.Get("key_236"), GlobalHelper.Get("key_99"));
                        return;
                    }


                    ControlExtended.UIInvoke(() =>
                    {
                        var view = PluginProvider.GetObjectInstance <IDataViewer>(d.Name);

                        var r = view.SetCurrentView(data.ComputeData);

                        if (ControlExtended.DockableManager != null)
                        {
                            ControlExtended.DockableManager.AddDockAbleContent(
                                FrmState.Float, r, data.Name + " " + d.Name);
                        }
                    });
                };
                return(comm);
            });

            visitData.Execute =
                obj => visitCommands.FirstOrDefault(d => d.Text == GlobalHelper.Get("key_230")).Execute(obj);
            foreach (var visitCommand in visitCommands)
            {
                visitData.ChildActions.Add(visitCommand);
            }

            dataaction.ChildActions.Add(new Command(
                                            GlobalHelper.Get("smartetl_name"), obj =>
            {
                var collection = GetSelectedCollection(obj).FirstOrDefault();
                if (collection == null)
                {
                    return;
                }

                var plugin = processManager.GetOneInstance("SmartETLTool", true, true, true) as SmartETLTool;

                dynamic generator = PluginProvider.GetObjectByType <IColumnProcess>("TableGE");
                generator.Father  = plugin;

                generator.TableSelector.SelectItem = collection.Name;
                plugin.CurrentETLTools.Add(generator);
                plugin.ETLMount++;
                plugin.Init();

                //plugin.RefreshSamples(true);
                ControlExtended.DockableManager.ActiveModelContent(plugin);
            }, obj => true, "new"));

            var saveData = new Command(GlobalHelper.Get("key_237"), d =>
            {
                var collection = GetSelectedCollection(d).FirstOrDefault();
                if (collection == null)
                {
                    return;
                }
                var ofd = new SaveFileDialog {
                    Filter = FileConnector.GetDataFilter(), DefaultExt = "*"
                };

                ofd.FileName = collection.Name + ".xlsx";
                if (ofd.ShowDialog() == true)
                {
                    var filename = ofd.FileName;
                    SaveFile(collection.Name, filename);
                }
            }, obj => true, "save");

            dataaction.ChildActions.Add(saveData);
            dataaction.ChildActions.Add(visitData);
            dataaction.ChildActions.Add(new Command(
                                            GlobalHelper.Get("key_238"),
                                            obj =>
            {
                if (obj != null)
                {
                    foreach (var collection in GetSelectedCollection(obj))
                    {
                        if (collection == null)
                        {
                            return;
                        }
                        var n  = collection.Clone(true);
                        n.Name = GetNewName(collection.Name);
                        DataCollections.Add(n);
                    }
                }
                else
                {
                    DataCollections.Add(new DataCollection(new List <IFreeDocument>())
                    {
                        Name = GetNewName(GlobalHelper.Get("key_239"))
                    });
                }
                ;
            }, obj => true, "add"));
            dataaction.ChildActions.Add(new Command(
                                            GlobalHelper.Get("key_240"), obj =>
            {
                var collection = GetSelectedCollection(obj);
                if (collection != null)
                {
                    PropertyGridFactory.GetPropertyWindow(collection).ShowDialog();
                }
            }, obj => true, "settings"));
            dataaction.ChildActions.Add(new Command(
                                            GlobalHelper.Get("key_169"), obj =>
            {
                foreach (var collection  in GetSelectedCollection(obj))
                {
                    if (collection != null)
                    {
                        DataCollections.Remove(collection);
                    }
                }
            }, obj => true, "delete"));

            var convert = new BindingAction(GlobalHelper.Get("key_241"));

            dataaction.ChildActions.Add(convert);
            convert.ChildActions.Add(new Command(GlobalHelper.Get("key_242"), obj =>
            {
                var coll = GetSelectedCollection(obj).FirstOrDefault();
                if (coll == null)
                {
                    return;
                }
                if (coll.Count > 500000)
                {
                    if (
                        MessageBox.Show(GlobalHelper.Get("key_243"), GlobalHelper.Get("key_99"),
                                        MessageBoxButton.YesNoCancel) !=
                        MessageBoxResult.Yes)
                    {
                        return;
                    }
                }
                var docuts = new List <IFreeDocument>();
                var task   = TemporaryTask <FreeDocument> .AddTempTaskSimple(GlobalHelper.Get("key_242"), coll.ComputeData, d =>
                {
                    if (d != null)
                    {
                        docuts.Add(d);
                    }
                }, result =>
                {
                    var collection = new DataCollection(docuts)
                    {
                        Name = coll.Name + '1'
                    };
                    AddDataCollection(collection);
                    DataCollections.Remove(coll);
                });
                processManager.CurrentProcessTasks.Add(task);
            }));
            var insertdb = new BindingAction(GlobalHelper.Get("key_244"));

            insertdb.SetChildActionSource(() =>
            {
                return(_dbConnections.Select(dataBaseConnector => new Command(dataBaseConnector.Name, obj =>
                {
                    var data = obj as DataCollection;
                    processManager.CurrentProcessTasks.Add(
                        TemporaryTask <FreeDocument> .AddTempTaskSimple(data.Name + GlobalHelper.Get("key_245"),
                                                                        dataBaseConnector.InserDataCollection(data), result => dataBaseConnector.RefreshTableNames(),
                                                                        count: data.Count / 1000));
                }, icon: "database")).Cast <ICommand>().ToList());
            });


            dataaction.ChildActions.Add(insertdb);
            var otherDataAction = new BindingAction();

            otherDataAction.ChildActions.Add(new Command(GlobalHelper.Get("key_132"), obj => CleanData(),
                                                         obj => DataCollections.Count > 0,
                                                         "clear"));


            commands.Add(dbaction);
            commands.Add(tableAction);
            commands.Add(dataaction);
            commands.Add(otherDataAction);
            var dblistAction = new BindingAction(GlobalHelper.Get("key_246"));

            var addnew = new BindingAction(GlobalHelper.Get("key_247"))
            {
                Icon = "add"
            };

            dblistAction.ChildActions.Add(addnew);
            foreach (var item in PluginProvider.GetPluginCollection(typeof(IDataBaseConnector)))
            {
                addnew.ChildActions.Add(new Command(item.Name)
                {
                    Execute = obj =>
                    {
                        var con  = PluginProvider.GetObjectInstance(item.MyType) as DBConnectorBase;
                        con.Name = item.Name;

                        _dbConnections.Add(con);
                    },
                    Icon = "connect"
                });
            }
            commands.Add(dblistAction);


            dockableManager = MainFrmUI as IDockableManager;
            if (processManager?.CurrentProject != null)

            {
                LoadDataConnections();
            }
            processManager.OnCurrentProjectChanged += (s, e) => LoadDataConnections();

            if (MainDescription.IsUIForm)
            {
                ConfigUI = PropertyGridFactory.GetInstance(_dbConnections.FirstOrDefault());
            }

            var changed = DataCollections as INotifyCollectionChanged;

            changed.CollectionChanged += (s, e) => OnDataSourceChanged(new EventArgs());

            return(true);
        }
Ejemplo n.º 10
0
        public override void DictDeserialize(IDictionary <string, object> docu, Scenario scenario = Scenario.Database)
        {
            base.DictDeserialize(docu);
            var doc = docu as FreeDocument;

            if (doc.Children != null)
            {
                var items = doc.Children;

                foreach (var item in items)
                {
                    var proces = new ProcessTask();
                    proces.Project = this;
                    proces.DictDeserialize(item);

                    Tasks.Add(proces);
                }
            }

            if (docu["DBConnections"] != null)
            {
                var items = docu["DBConnections"] as FreeDocument;

                if (items?.Children != null)
                {
                    foreach (var item in items.Children)
                    {
                        var type = item["TypeName"].ToString();
                        var conn = PluginProvider.GetObjectByType <IDataBaseConnector>(type) as DBConnectorBase;
                        if (conn == null)
                        {
                            continue;
                        }
                        conn.DictDeserialize(item);

                        DBConnections.Add(conn);
                    }
                }
            }
            if (DBConnections.FirstOrDefault(d => d.TypeName == "文件管理") == null)
            {
                var filemanager = new FileManager()
                {
                    Name = "最近打开的文件"
                };
                DBConnections.Add(filemanager);
            }
            if (DBConnections.FirstOrDefault(d => d.TypeName == "MongoDB") == null)
            {
                var mongo = new MongoDBConnector()
                {
                    Name = "MongoDB连接器"
                };
                mongo.DBName = "hawk";
                DBConnections.Add(mongo);
            }
            if (DBConnections.FirstOrDefault(d => d.TypeName == "SQLite数据库") == null)
            {
                var sqlite = new SQLiteDatabase()
                {
                    Name = "SQLite数据库"
                };
                sqlite.DBName = "hawk-sqlite";
                DBConnections.Add(sqlite);
            }
        }
Ejemplo n.º 11
0
        private void InitUI()

        {
            var alltools = CurrentETLTools.Take(ETLMount).ToList();


            if (generateFloatGrid)
            {
                var gridview = PluginProvider.GetObjectInstance <IDataViewer>("可编辑列表");

                var r = gridview.SetCurrentView(Documents);

                if (ControlExtended.DockableManager == null)
                {
                    return;
                }

                ControlExtended.DockableManager.AddDockAbleContent(
                    FrmState.Custom, r, "样例数据");
                generateFloatGrid = false;
            }
            else
            {
                var view = new GridView();


                Dict.Clear();
                var keys = new List <string> {
                    ""
                };
                var docKeys = Documents.GetKeys(null, SampleMount);

                keys.AddRange(docKeys);
                var tool = CurrentTool;


                foreach (var key in keys)
                {
                    var col = new GridViewColumn
                    {
                        Header = key,
                        DisplayMemberBinding = new Binding(string.Format("[{0}]", key)),
                        Width = 155
                    };
                    view.Columns.Add(col);

                    var group = new SmartGroup
                    {
                        Name  = key,
                        Value = alltools.Where(d => d.Column == key).ToList()
                    };

                    group.PropertyChanged += (s, e) =>
                    {
                        if (e.PropertyName == "Name")
                        {
                            var last = alltools.LastOrDefault() as IColumnDataTransformer;
                            if (last != null && last.TypeName == "列名修改器" && last.NewColumn == key)
                            {
                                last.NewColumn = group.Name;
                            }
                            else
                            {
                                last           = PluginProvider.GetObjectInstance("列名修改器") as IColumnDataTransformer;
                                last.NewColumn = group.Name;
                                last.Column    = key;
                                InsertModule(last);
                                ETLMount++;
                                OnPropertyChanged("ETLMount");
                                RefreshSamples();
                            }
                        }
                    };
                    Dict.Add(group
                             );
                }
                if (tool != null)
                {
                    Dict.Where(d => d.Name == tool.Column).Execute(d => d.GroupType = GroupType.Input);
                    var transformer = tool as IColumnDataTransformer;
                    if (transformer != null)
                    {
                        var newcol = transformer.NewColumn.Split(' ');
                        if (transformer.IsMultiYield)
                        {
                            Dict.Execute(d => d.GroupType = newcol.Contains(d.Name)? GroupType.Input:GroupType.Output);
                        }
                        else
                        {
                            Dict.Where(d => d.Name == transformer.NewColumn).Execute(d => d.GroupType = GroupType.Output);;
                        }
                    }
                }
                var nullgroup = Dict.FirstOrDefault(d => string.IsNullOrEmpty(d.Name));
                nullgroup.Value.AddRange(
                    alltools.Where(
                        d =>
                        Documents.GetKeys().Contains(d.Column) == false &&
                        string.IsNullOrEmpty(d.Column) == false));
                if (MainDescription.IsUIForm && IsUISupport)
                {
                    if (dataView != null)
                    {
                        dataView.View = view;
                    }
                }
            }
        }
Ejemplo n.º 12
0
 public CalculatorController(IEnumerable <Plugin> plugins, IServiceProvider serviceProvider, PluginProvider pluginProvider)
 {
     _plugins         = plugins;
     _serviceProvider = serviceProvider;
     _pluginProvider  = pluginProvider;
 }
Ejemplo n.º 13
0
        public override void DictDeserialize(IDictionary <string, object> docu, Scenario scenario = Scenario.Database)
        {
            base.DictDeserialize(docu);
            var doc = docu as FreeDocument;

            if (doc.Children != null)
            {
                var items = doc.Children;

                foreach (var item in items)
                {
                    var proces = new ProcessTask();
                    proces.Project = this;
                    proces.DictDeserialize(item);

                    Tasks.Add(proces);
                }
            }

            if (docu["DBConnections"] != null)
            {
                var items = docu["DBConnections"] as FreeDocument;

                if (items?.Children != null)
                {
                    foreach (var item in items.Children)
                    {
                        var type = item["TypeName"].ToString();
                        var conn = PluginProvider.GetObjectByType <IDataBaseConnector>(type) as DBConnectorBase;
                        if (conn == null)
                        {
                            continue;
                        }
                        conn.DictDeserialize(item);

                        DBConnections.Add(conn);
                    }
                }
            }
            if (docu["RunningTasks"] != null)
            {
                var tasks = docu["RunningTasks"] as FreeDocument;


                SavedRunningTasks = tasks?.Children;
            }

            if (docu["Parameters"] != null)
            {
                var tasks = docu["Parameters"] as FreeDocument;

                if (tasks != null)
                {
                    Parameters.AddRange(tasks?.Children?.Select(d =>
                    {
                        var param = new ParameterItem();
                        param.UnsafeDictDeserialize(d);
                        return(param);
                    }));
                }
            }

            ConfigSelector.SelectItem =
                docu["ParameterName"].ToString();

            if (DBConnections.FirstOrDefault(d => d.TypeName == GlobalHelper.Get("FileManager")) == null)
            {
                var filemanager = new FileManager {
                    Name = GlobalHelper.Get("recent_file")
                };
                DBConnections.Add(filemanager);
            }
            if (DBConnections.FirstOrDefault(d => d.TypeName == "MongoDB") == null)
            {
                var mongo = new MongoDBConnector {
                    Name = "MongoDB连接器"
                };
                mongo.DBName = "hawk";
                DBConnections.Add(mongo);
            }
            if (DBConnections.FirstOrDefault(d => d.TypeName == GlobalHelper.Get("SQLiteDatabase")) == null)
            {
                var sqlite = new SQLiteDatabase {
                    Name = GlobalHelper.Get("SQLiteDatabase")
                };
                sqlite.DBName = "hawk-sqlite";
                DBConnections.Add(sqlite);
            }
        }
Ejemplo n.º 14
0
        public void GreatHand()
        {
            var count              = 0;
            var crawTargets        = HtmlDoc.SearchPropertiesSmart(CrawlItems, RootXPath, IsAttribute);
            var currentCrawTargets = crawTargets.GetEnumerator();
            var result             = currentCrawTargets.MoveNext();

            if (result)
            {
                CrawTarget = currentCrawTargets.Current;
            }
            else
            {
                CrawTarget = null;
                XLogSys.Print.Warn("没有检查到任何可选的列表页面");
                return;
            }

            var crawitems     = CrawTarget.CrawItems;
            var datas         = HtmlDoc.GetDataFromXPath(crawitems, IsMultiData, CrawTarget.RootXPath);
            var propertyNames = new FreeDocument(datas.GetKeys().ToDictionary(d => d, d => (object)d));

            datas.Insert(0, propertyNames);
            var view = PluginProvider.GetObjectInstance <IDataViewer>("可编辑列表");
            var r    = view.SetCurrentView(datas);


            var name   = "手气不错_可修改第一列的属性名称";
            var window = new Window {
                Title = name
            };

            window.Content  = r;
            window.Closing += (s, e) =>
            {
                var check = MessageBox.Show("是否确认选择当前结果?【是】:确认结果,  【否】:检查下个目标,  【取消】:结束当前手气不错", "提示信息",
                                            MessageBoxButton.YesNoCancel);
                switch (check)
                {
                case MessageBoxResult.Yes:
                    foreach (var propertyName in propertyNames)
                    {
                        var item = crawitems.FirstOrDefault(d => d.Name == propertyName.Key);
                        if (item == null)
                        {
                            continue;
                        }
                        if (propertyName.Value == null)
                        {
                            continue;
                        }
                        item.Name = propertyName.Value.ToString();
                    }
                    CrawlItems.Clear();
                    RootXPath = CrawTarget.RootXPath;
                    CrawlItems.AddRange(crawitems);
                    currentCrawTargets = null;
                    break;

                case MessageBoxResult.No:
                    e.Cancel = true;
                    result   = currentCrawTargets.MoveNext();
                    count++;
                    if (result)
                    {
                        CrawTarget = currentCrawTargets.Current;
                    }
                    else
                    {
                        MessageBox.Show("已经搜索所有可能情况,搜索器已经返回开头");
                        crawTargets        = HtmlDoc.SearchPropertiesSmart(CrawlItems, RootXPath, IsAttribute);
                        currentCrawTargets = crawTargets.GetEnumerator();
                        count  = 0;
                        result = currentCrawTargets.MoveNext();
                        if (!result)
                        {
                            e.Cancel = false;
                        }
                        else
                        {
                            CrawTarget = currentCrawTargets.Current;
                        }
                    }

                    crawitems = CrawTarget.CrawItems;
                    var title = $"手气不错,第{count}次结果";
                    datas         = HtmlDoc.GetDataFromXPath(crawitems, IsMultiData, CrawTarget.RootXPath);
                    propertyNames = new FreeDocument(datas.GetKeys().ToDictionary(d => d, d => (object)d));
                    datas.Insert(0, propertyNames);
                    r = view.SetCurrentView(datas);
                    window.Content = r;
                    window.Title   = title;
                    break;

                case MessageBoxResult.Cancel:
                    return;
                }
            };


            window.ShowDialog();
        }
Ejemplo n.º 15
0
        public override bool Init()
        {
            base.Init();
            dockableManager    = MainFrmUI as IDockableManager;
            dataManager        = MainFrmUI.PluginDictionary["数据管理"] as IDataManager;
            propertyGridWindow = MainFrmUI.PluginDictionary["属性配置器"] as XFrmWorkPropertyGrid;


            ProcessCollection = new ObservableCollection <IDataProcess>();


            CurrentProcessTasks = new ObservableCollection <TaskBase>();
            BindingCommands     = new BindingAction("运行");
            var sysCommand = new BindingAction();

            sysCommand.ChildActions.Add(
                new Command(
                    "清空模块列表",
                    obj =>
            {
                if (MessageBox.Show("确定清空所有算法模块么?", "提示信息", MessageBoxButton.OKCancel) ==
                    MessageBoxResult.OK)
                {
                    ProcessCollection.RemoveElementsNoReturn(d => true, RemoveOperation);
                }
            }, obj => true,
                    "clear"));

            sysCommand.ChildActions.Add(
                new Command(
                    "保存全部模块",
                    obj =>
            {
                if (MessageBox.Show("确定保存所有算法模块么?", "提示信息", MessageBoxButton.OKCancel) ==
                    MessageBoxResult.OK)
                {
                    SaveCurrentTasks();
                }
            }, obj => true,
                    "clear"));

            BindingCommands.ChildActions.Add(sysCommand);

            var taskAction1 = new BindingAction();


            taskAction1.ChildActions.Add(new Command("加载本任务",
                                                     obj => (obj as ProcessTask).Load(true),
                                                     obj => obj is ProcessTask, "download"));


            taskAction1.ChildActions.Add(new Command("删除任务",
                                                     obj => CurrentProject.Tasks.Remove(obj as ProcessTask),
                                                     obj => obj is ProcessTask));
            taskAction1.ChildActions.Add(new Command("执行任务脚本",
                                                     (obj => (obj as ProcessTask).EvalScript()),
                                                     obj => (obj is ProcessTask) && CurrentProcessCollections.FirstOrDefault(d => d.Name == (obj as ProcessTask).Name) != null));

            BindingCommands.ChildActions.Add(taskAction1);
            var taskAction2 = new BindingAction("任务列表2");

            taskAction2.ChildActions.Add(new Command("开始任务",
                                                     obj =>
            {
                var task = obj as TaskBase;
                task.Start();
            },
                                                     obj =>
            {
                var task = obj as TaskBase;
                return(task != null && task.IsStart == false);
            }, "download"));

            taskAction2.ChildActions.Add(new Command("取消任务",
                                                     obj =>
            {
                var task = obj as TaskBase;
                if (task.IsStart)
                {
                    task.Cancel();
                }

                task.Remove();
            },
                                                     obj =>
            {
                var task = obj as TaskBase;
                return(task != null);
            }, "download"));


            var taskListAction = new BindingAction("任务列表命令");

            taskListAction.ChildActions.Add(new Command("全选",
                                                        d => CurrentProcessTasks.Execute(d2 => d2.IsSelected = true), null, "check"));

            taskListAction.ChildActions.Add(new Command("反选",
                                                        d => CurrentProcessTasks.Execute(d2 => d2.IsSelected = !d2.IsSelected), null, "redo"));

            taskListAction.ChildActions.Add(new Command("暂停",
                                                        d => CurrentProcessTasks.Where(d2 => d2.IsSelected).Execute(d2 => d2.IsPause = true), null, "pause"));
            taskListAction.ChildActions.Add(new Command("恢复",
                                                        d => CurrentProcessTasks.Where(d2 => d2.IsSelected).Execute(d2 => d2.IsPause = false), null, "play"));

            taskListAction.ChildActions.Add(new Command("取消",
                                                        d => CurrentProcessTasks.RemoveElementsNoReturn(d2 => d2.IsSelected, d2 => d2.Cancel()), null, "delete"));

            BindingCommands.ChildActions.Add(taskListAction);

            BindingCommands.ChildActions.Add(taskListAction);

            var processAction = new BindingAction();


            processAction.ChildActions.Add(new Command("配置", obj =>
            {
                var process = GetProcess(obj);
                if (process == null)
                {
                    return;
                }
                ShowConfigUI(process);
            }, obj => true, "settings"));
            processAction.ChildActions.Add(new Command("查看视图", obj =>
            {
                var process = GetProcess(obj);
                if (process == null)
                {
                    return;
                }
                (MainFrmUI as IDockableManager).ActiveModelContent(process);
            }, obj => true, "tv"));
            processAction.ChildActions.Add(new Command("拷贝", obj =>
            {
                var process = GetProcess(obj);
                if (process == null)
                {
                    return;
                }
                ProcessCollection.Remove(obj as IDataProcess);
                var item = GetOneInstance(process.TypeName, true, false);
                (process as IDictionarySerializable).DictCopyTo(item as IDictionarySerializable);
                item.Init();
                ProcessCollection.Add(item);
            }, obj => true, "new"));

            processAction.ChildActions.Add(new Command("移除", obj =>
            {
                var process = GetProcess(obj);
                if (process == null)
                {
                    return;
                }

                RemoveOperation(process);
                ProcessCollection.Remove(process);
                ShowConfigUI(null);
            }, obj => true, "delete"));

            processAction.ChildActions.Add(new Command("保存任务", obj =>
            {
                var process = obj as IDataProcess;
                if (process == null)
                {
                    return;
                }
                SaveTask(process, true);
            }, obj => obj is IDictionarySerializable));
            processAction.ChildActions.Add(new Command("显示并配置", obj =>
            {
                var process = GetProcess(obj);
                if (process == null)
                {
                    return;
                }
                var view = (MainFrmUI as IDockableManager).ViewDictionary.FirstOrDefault(d => d.Model == process);
                if (view == null)
                {
                    LoadProcessView(process);
                }
                (MainFrmUI as IDockableManager).ActiveModelContent(process);
                ShowConfigUI(process);
            }, obj => true, "delete"));


            BindingCommands.ChildActions.Add(processAction);
            BindingCommands.ChildActions.Add(taskAction2);
            var attributeactions = new BindingAction("模块");

            attributeactions.ChildActions.Add(new Command("添加", obj =>
            {
                var attr = obj as XFrmWorkAttribute;
                if (attr == null)
                {
                    return;
                }

                var process = GetOneInstance(attr.MyType.Name, newOne: true, isAddUI: true);
                process.Init();
            }));
            BindingCommands.ChildActions.Add(attributeactions);

            var config = ConfigFile.GetConfig <DataMiningConfig>();

            if (config.Projects.Any())
            {
                var project = config.Projects.FirstOrDefault();
                if (project != null)
                {
                    ControlExtended.SafeInvoke(() =>
                    {
                        currentProject = ProjectItem.LoadProject(project.SavePath);
                        NotifyCurrentProjectChanged();
                    }, LogType.Info, "加载默认工程");
                }
            }

            if (MainDescription.IsUIForm)
            {
                ProgramNameFilterView =
                    new ListCollectionView(PluginProvider.GetPluginCollection(typeof(IDataProcess)).ToList());

                ProgramNameFilterView.GroupDescriptions.Clear();
                ProgramNameFilterView.GroupDescriptions.Add(new PropertyGroupDescription("GroupName"));
                var taskView    = PluginProvider.GetObjectInstance <ICustomView>("任务管理视图");
                var userControl = taskView as UserControl;
                if (userControl != null)
                {
                    userControl.DataContext = this;
                    ((INotifyCollectionChanged)CurrentProcessTasks).CollectionChanged += (s, e) =>
                    {
                        ControlExtended.UIInvoke(() => {
                            if (e.Action == NotifyCollectionChangedAction.Add)
                            {
                                dockableManager.ActiveThisContent("任务管理视图");
                            }
                        });
                    }
                    ;
                    dockableManager.AddDockAbleContent(taskView.FrmState, this, taskView, "任务管理视图");
                }
                ProcessCollectionView = new ListCollectionView(ProcessCollection);
                ProcessCollectionView.GroupDescriptions.Clear();
                ProcessCollectionView.GroupDescriptions.Add(new PropertyGroupDescription("TypeName"));


                ProjectTaskList = new ListCollectionView(CurrentProject.Tasks);
                ProjectTaskList.GroupDescriptions.Clear();

                ProjectTaskList.GroupDescriptions.Add(new PropertyGroupDescription("TypeName"));


                OnPropertyChanged("ProjectTaskList");
                ProjectTaskList = new ListCollectionView(CurrentProject.Tasks);
                ProjectTaskList.GroupDescriptions.Clear();

                ProjectTaskList.GroupDescriptions.Add(new PropertyGroupDescription("TypeName"));
                OnPropertyChanged("ProjectTaskList");
            }

            var file = MainFrmUI.CommandCollection.FirstOrDefault(d => d.Text == "文件");

            file.ChildActions.Add(new BindingAction("新建项目", obj => CreateNewProject()));
            file.ChildActions.Add(new BindingAction("加载项目", obj => LoadProject()));
            file.ChildActions.Add(new BindingAction("保存项目", obj => SaveCurrentProject()));
            file.ChildActions.Add(new BindingAction("项目另存为", obj => SaveCurrentProject(false)));

            return(true);
        }
Ejemplo n.º 16
0
        public override bool Init()
        {
            if (MainDescription.IsUIForm)
            {
                DataCollections = new SafeObservable <DataCollection>();
                dockableManager = MainFrmUI as IDockableManager;

                var view        = PluginProvider.GetObjectInstance <ICustomView>("系统状态视图");
                var userControl = view as UserControl;
                if (userControl != null)
                {
                    userControl.DataContext = MainFrmUI;
                    dockableManager.AddDockAbleContent(FrmState.Mini, view, "系统状态视图");
                }
            }

            else
            {
                DataCollections = new ObservableCollection <DataCollection>();
            }

            processManager = MainFrmUI.PluginDictionary["模块管理"] as IProcessManager;


            commands = new List <ICommand>();
            var dbaction = new BindingAction();

            dbaction.ChildActions.Add(new Command("配置连接",
                                                  obj =>
            {
                Window w = PropertyGridFactory.GetPropertyWindow(obj);
                w.ShowDialog();
            },
                                                  obj => obj != null));
            dbaction.ChildActions.Add(
                new Command("刷新", obj => RefreshConnect(obj as IDataBaseConnector), obj => obj != null));
            dbaction.ChildActions.Add(
                new Command("执行查询", obj =>
            {
                var query          = new QueryEntity();
                query.Connector    = obj as IDataBaseConnector;
                query.GetQueryFunc = d =>
                {
                    if (d == null)
                    {
                        return;
                    }
                    if (d.Any() == false)
                    {
                        return;
                    }

                    AddDataCollection(d, GetNewName());
                };
                propertyGridWindow.SetObjectView(query);
            }, obj => obj != null));
            dbaction.ChildActions.Add(
                new Command("删除连接", obj =>
            {
                if (MessageBox.Show("确定要删除该连接吗?", "提示信息", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                {
                    var con = obj as DBConnectorBase;
                    _dbConnections.Remove(con);
                }
            }, obj => obj != null));
            var dataaction = new BindingAction();


            var tableAction = new BindingAction();

            tableAction.ChildActions.Add(new Command(
                                             "查看",
                                             async obj =>
            {
                var items = obj as TableInfo;

                List <IFreeDocument> dataAll =
                    await
                    GetDataFromDB(items.Connector, items.Name, true,
                                  items.Connector is FileManager ? -1 : 200);
                if (dataAll == null || dataAll.Count == 0)
                {
                    XLogSys.Print.Warn("没有在表中的发现可用的数据");
                    return;
                }
                if (items.Connector is FileManager)
                {
                    string file = (items.Connector as FileManager).LastFileName;
                    var name    = Path.GetFileNameWithoutExtension(file);
                    AddDataCollection(dataAll, name);
                    return;
                }
                var excel = PluginProvider.GetObjectInstance <IDataViewer>("可编辑列表");
                if (excel == null)
                {
                    return;
                }
                object view = excel.SetCurrentView(dataAll.Select(d => d as IFreeDocument).ToList());

                if (ControlExtended.DockableManager != null)
                {
                    ControlExtended.DockableManager.AddDockAbleContent(
                        FrmState.Custom, view, items.Name);
                }
            },
                                             obj => obj != null));
            tableAction.ChildActions.Add(new Command(
                                             "添加到数据集",
                                             async obj =>
            {
                var items = obj as TableInfo;
                List <IFreeDocument> datas = await GetDataFromDB(items.Connector, items.Name, true);
                if (datas == null)
                {
                    return;
                }
                AddDataCollection(datas, items.Name);
            },
                                             obj => obj != null));
            tableAction.ChildActions.Add(new Command(
                                             "添加虚拟数据集",
                                             obj =>
            {
                var con = obj as TableInfo;
                ReadCollection(con.Connector, con.Name, true);
            },
                                             obj => obj != null));
            tableAction.ChildActions.Add(new Command(
                                             "删除表",
                                             obj =>
            {
                var items = obj as TableInfo;

                DropTable(items.Connector, items.Name);
            },
                                             obj => obj != null));
            tableAction.ChildActions.Add(new Command(
                                             "查看属性",
                                             obj =>
            {
                Window w = PropertyGridFactory.GetPropertyWindow(obj);
                w.ShowDialog();
            },
                                             obj => obj != null));
            tableAction.ChildActions.Add(new Command(
                                             "执行查询",
                                             obj =>
            {
                var query          = new QueryEntity();
                query.TableInfo    = obj as TableInfo;
                query.Connector    = query.TableInfo.Connector;
                query.GetQueryFunc = d =>
                {
                    if (d == null)
                    {
                        return;
                    }
                    if (d.Any() == false)
                    {
                        return;
                    }

                    AddDataCollection(d, GetNewName());
                };
                propertyGridWindow.SetObjectView(query);
            }, obj => obj != null));


            var visitData = new BindingAction("浏览方式");

            IEnumerable <Command> visitCommands = PluginProvider.GetPluginCollection(typeof(IDataViewer)).Select(
                d =>
            {
                var comm     = new Command(d.Name);
                comm.Execute = d2 =>
                {
                    var data = d2 as DataCollection;

                    if (data.Count == 0)
                    {
                        MessageBox.Show("不存在任何数据", "提示信息");
                        return;
                    }


                    ControlExtended.UIInvoke(() =>
                    {
                        var view = PluginProvider.GetObjectInstance <IDataViewer>(d.Name);

                        object r = view.SetCurrentView(data.ComputeData);

                        if (ControlExtended.DockableManager != null)
                        {
                            ControlExtended.DockableManager.AddDockAbleContent(
                                FrmState.Float, r, data.Name + " " + d.Name);
                        }
                    });
                };
                return(comm);
            });

            visitData.Execute = obj => visitCommands.FirstOrDefault(d => d.Text == "可编辑列表").Execute(obj);
            foreach (Command visitCommand in visitCommands)
            {
                visitData.ChildActions.Add(visitCommand);
            }

            dataaction.ChildActions.Add(new Command(
                                            "数据清洗", obj =>
            {
                DataCollection collection = GetCollection(obj);
                if (collection == null)
                {
                    return;
                }

                var plugin        = processManager.GetOneInstance("SmartETLTool", true, true) as SmartETLTool;
                dynamic generator = PluginProvider.GetObjectByType <IColumnProcess>("TableGE");
                generator.TableSelector.SelectItem = collection;
                plugin.CurrentETLTools.Add(generator);
                plugin.RefreshSamples(true);
                ControlExtended.DockableManager.ActiveModelContent(plugin);
            }, obj => true, "new"));
            dataaction.ChildActions.Add(new Command(
                                            "拷贝", obj =>
            {
                DataCollection collection = GetCollection(obj);
                if (collection == null)
                {
                    return;
                }
                DataCollection n = collection.Clone(true);
                n.Name           = GetNewName(collection.Name);
                DataCollections.Add(n);
            }, obj => true, "page_new"));
            var saveData = new Command("另存为", d =>
            {
                DataCollection collection = GetCollection(d);
                if (collection == null)
                {
                    return;
                }
                var ofd = new SaveFileDialog {
                    Filter = FileConnector.GetDataFilter(), DefaultExt = "*"
                };

                ofd.FileName = collection.Name + ".xlsx";
                if (ofd.ShowDialog() == true)
                {
                    string filename = ofd.FileName;
                    SaveFile(collection.Name, filename);
                }
            }, obj => true, "save");

            dataaction.ChildActions.Add(saveData);
            dataaction.ChildActions.Add(visitData);
            dataaction.ChildActions.Add(new Command(
                                            "新建",
                                            obj =>
                                            DataCollections.Add(new DataCollection(new List <IFreeDocument>())
            {
                Name = GetNewName("新建数据集")
            }), obj => true, "box"));
            dataaction.ChildActions.Add(new Command(
                                            "配置", obj =>
            {
                DataCollection collection = GetCollection(obj);
                if (collection != null)
                {
                    propertyGridWindow.SetObjectView(collection);
                }
            }, obj => true, "settings"));
            dataaction.ChildActions.Add(new Command(
                                            "删除", obj =>
            {
                DataCollection collection = GetCollection(obj);
                if (collection != null)
                {
                    DataCollections.Remove(collection);
                }
            }, obj => true, "delete"));

            var convert = new BindingAction("转换表类型");

            dataaction.ChildActions.Add(convert);
            convert.ChildActions.Add(new Command("转为非虚拟数据集", obj =>
            {
                DataCollection coll = GetCollection(obj);
                if (coll.Count > 500000)
                {
                    if (
                        MessageBox.Show("本集合数据量较大,转换可能会占用较高的内存和导致程序崩溃,确定继续吗?", "提示信息", MessageBoxButton.YesNoCancel) !=
                        MessageBoxResult.Yes)
                    {
                        return;
                    }
                }
                var docuts = new List <IFreeDocument>();
                var task   = TemporaryTask.AddTempTask("转为非虚拟数据集", coll.ComputeData, d =>
                {
                    if (d != null)
                    {
                        docuts.Add(d as IFreeDocument);
                    }
                }, result =>
                {
                    var collection = new DataCollection(docuts)
                    {
                        Name = coll.Name + '1'
                    };
                    AddDataCollection(collection);
                    this.DataCollections.Remove(coll);
                });
                processManager.CurrentProcessTasks.Add(task);
            }));
            var insertdb = new BindingAction("保存到数据库");

            insertdb.SetChildActionSource(() =>
            {
                return(_dbConnections.Select(dataBaseConnector => new Command(dataBaseConnector.Name, obj =>
                {
                    var data = obj as DataCollection;
                    processManager.CurrentProcessTasks.Add(TemporaryTask.AddTempTask(data.Name + "插入到数据库", dataBaseConnector.InserDataCollection(data), result => dataBaseConnector.RefreshTableNames(), count: data.Count / 1000));
                })).Cast <ICommand>().ToList());
            });


            dataaction.ChildActions.Add(insertdb);
            var otherDataAction = new BindingAction();

            otherDataAction.ChildActions.Add(new Command("清空数据", obj => CleanData(), obj => DataCollections.Count > 0));


            commands.Add(dbaction);
            commands.Add(tableAction);
            commands.Add(dataaction);
            commands.Add(otherDataAction);
            var dblistAction = new BindingAction("数据库管理");

            var addnew = new BindingAction("增加新连接");

            dblistAction.ChildActions.Add(addnew);
            foreach (XFrmWorkAttribute item in PluginProvider.GetPluginCollection(typeof(IDataBaseConnector)))
            {
                addnew.ChildActions.Add(new Command(item.Name)
                {
                    Execute = obj =>
                    {
                        var con  = PluginProvider.GetObjectInstance(item.MyType) as DBConnectorBase;
                        con.Name = item.Name;

                        _dbConnections.Add(con);
                    }
                });
            }
            commands.Add(dblistAction);


            dockableManager = MainFrmUI as IDockableManager;
            if (processManager?.CurrentProject != null)

            {
                LoadDataConnections();
            }
            processManager.OnCurrentProjectChanged += (s, e) => LoadDataConnections();

            ConfigUI = PropertyGridFactory.GetInstance(_dbConnections.FirstOrDefault());


            propertyGridWindow = MainFrmUI.PluginDictionary["属性配置器"] as XFrmWorkPropertyGrid;
            var changed = DataCollections as INotifyCollectionChanged;

            changed.CollectionChanged += (s, e) => OnDataSourceChanged(new EventArgs());

            return(true);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Runs the set of plugins against the given string
        /// </summary>
        /// <param name="name"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        private PreflightPropertyResponseModel RunPluginsAgainstValue(string name, string val)
        {
            var model = new PreflightPropertyResponseModel
            {
                Label = name,
                Name  = name
            };

            if (val == null)
            {
                return(model);
            }

            var pluginProvider = new PluginProvider();

            foreach (IPreflightPlugin plugin in pluginProvider.Get())
            {
                // settings on the plugin are the defaults - set to correct values from _settings
                IEnumerable <SettingsModel> pluginSettings = _settings.Where(s => s.Tab == plugin.Name).ToList();
                plugin.Settings = pluginSettings;

                // ignore disabled plugins
                if (plugin.IsDisabled())
                {
                    continue;
                }
                if (!_fromSave && plugin.IsOnSaveOnly())
                {
                    continue;
                }

                try
                {
                    Type pluginType = plugin.GetType();
                    if (pluginType.GetMethod("Check") == null)
                    {
                        continue;
                    }

                    plugin.Check(_id, val, _settings);

                    if (plugin.Result != null)
                    {
                        if (plugin.FailedCount == 0)
                        {
                            plugin.FailedCount = plugin.Failed ? 1 : 0;
                        }

                        model.Plugins.Add(plugin);
                    }
                }
                catch (Exception e)
                {
                    // todo => log
                    string m = e.Message;
                }
            }

            // mark as failed if any sub-tests have failed
            model.FailedCount = model.Plugins.Sum(x => x.FailedCount);
            model.Failed      = model.FailedCount > 0;

            model.Plugins = model.Plugins.OrderBy(p => p.SortOrder).ToList();

            return(model);
        }