コード例 #1
0
ファイル: KissCIWebService.cs プロジェクト: jgreene/KissCI
        public void Start(string[] args)
        {
            var install = false;
            var uninstall = false;
            var serviceName = "";

            var options = new OptionSet()
            {
                { "install=", v => { serviceName = v; install = true; } },
                { "uninstall=", v => { serviceName = v; uninstall = true; } }
            };

            try
            {
                options.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(string.Format("error parsing arguments: {0}", ex));
                return;
            }

            if (string.IsNullOrEmpty(serviceName) == false)
                KissCIInstaller.ServiceName = serviceName;

            if (install)
            {
                using (var service = new ServiceManager(serviceName, typeof(KissCIWebService).Assembly))
                {
                    service.Install();
                    return;
                }
            }

            if (uninstall)
            {
                using (var service = new ServiceManager(serviceName, typeof(KissCIWebService).Assembly))
                {
                    service.Uninstall();
                    return;
                }
            }

            var root = DirectoryHelper.ExecutingDirectory().FullName;
            var port = int.Parse(ConfigurationManager.AppSettings["Port"]);
            var webPath = ConfigurationManager.AppSettings["WebPath"];
            if (string.IsNullOrEmpty(webPath))
                webPath = "KissCI.Web";

            var webRoot = Path.IsPathRooted(webPath) ? webPath : Path.Combine(root, webPath);
            var hostName = ConfigurationManager.AppSettings["HostName"];

            var server = new CassiniDev.Server(port, "/", webRoot, IPAddress.Any, hostName);
            server.Start();

            if (Environment.UserInteractive)
            {
                Console.ReadLine();
            }
        }
コード例 #2
0
        public void Can_override_service_creation_with_custom_implementation()
        {
            var serviceManager = new ServiceManager(typeof(BasicService).Assembly);
            serviceManager.Init();

            var container = serviceManager.Container;
            container.Register<IFoo>(c => new Foo());
            container.Register<IBar>(c => new Bar());

            var serviceController = serviceManager.ServiceController;

            var request = new AutoWire();

            var response = serviceController.Execute(request) as AutoWireResponse;

            Assert.That(response, Is.Not.Null);
            Assert.That(response.Foo as Foo, Is.Not.Null);
            Assert.That(response.Bar as Bar, Is.Not.Null);

            container.Register(c =>
                new AutoWireService(new Foo2()) {
                    Bar = new Bar2()
                });

            response = serviceController.Execute(request) as AutoWireResponse;

            Assert.That(response, Is.Not.Null);
            Assert.That(response.Foo as Foo2, Is.Not.Null);
            Assert.That(response.Bar as Bar2, Is.Not.Null);
        }
コード例 #3
0
        void TryLoginAndWatch (UIButton button, ServiceManager service, Action<UIViewController, bool, NSAction> presentAuthController = null)
        {
            UpdateLabel (button, service);
            service.StateChanged += (sender, e) =>
                UpdateLabel (button, service);

            button.TouchUpInside += (sender, e) => {
                switch (service.State) {
                case SessionState.LoggedIn:
                case SessionState.Authenticating:
                    service.CloseSession ();
                    service.DeleteStoredAccounts ();
                    break;
                case SessionState.LoggedOut:
                    var choiceUI = new ActionSheetChoiceProvider<Account> (button.Frame, View);
                    service.GetSessionAsync (LoginOptions.WithUIAndChoice (choiceUI, presentAuthController: presentAuthController));
                    break;
                }
            };

            try {
                service.GetSessionAsync (LoginOptions.NoUI);
            } catch (UriFormatException) {
                Console.WriteLine ("Open Services.cs and specify your API keys for each provider.");
                return;
            }
        }
コード例 #4
0
ファイル: TransportWrapper.cs プロジェクト: alexed1/dtrack
 public TransportWrapper(ITransport transport)
 {
     if (transport == null)
         throw new ArgumentNullException("transport");
     _transport = transport;
     _serviceManager = new ServiceManager<TransportWrapper>("SendGrid Service", "Email Services");
 }
コード例 #5
0
ファイル: MessageForm.cs プロジェクト: permyakov/janus
        public MessageForm(
            [NotNull] IServiceProvider provider,
            MessageFormMode mode,
            MessageInfo message)
        {
            if (provider == null)
                throw new ArgumentNullException("provider");

            _serviceManager = new ServiceManager(provider);

            InitializeComponent();

            _formMode = mode;
            _messageInfo = message ?? new MessageInfo();
            _previewSourceNum = OutboxManager.RegisterPreviewSource(this);

            _serviceManager.Publish<IMessageEditorService>(
                new MessageEditorService(this));

            CustomInitializeComponent();

            _menuGenerator = new StripMenuGenerator(_serviceManager, _menuStrip, "MessageEditor.Menu");
            _toolbarGenerator = new StripMenuGenerator(_serviceManager, _toolStrip, "MessageEditor.Toolbar");
            _tagsbarGenerator = new SmilesToolbarGenerator(_serviceManager, "Forum.MessageEditor.TagsBar", _tagsBar);

            _syntaxExtSvc = provider.GetRequiredService<IEditorSyntaxExtensibilityService>();
        }
コード例 #6
0
ファイル: RemotingManager.cs プロジェクト: FloodProject/flood
 public RemotingManager(IContextLoader contextLoader)
 {
     ServiceManager = new ServiceManager(this);
     DelegateManager = new DelegateManager(this);
     ReferenceManager = new ReferenceManager(this);
     ContextManager = new ContextManager(this, contextLoader);
 }
コード例 #7
0
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            ServiceManager serviceManager2 = new ServiceManager();
            this.rdr_renderPane = new RenderPane();
            this.prp_properties = new System.Windows.Forms.PropertyGrid();
            this.SuspendLayout();
            // 
            // rdr_renderPane
            // 
            this.rdr_renderPane.Location = new System.Drawing.Point(2, 2);
            this.rdr_renderPane.Name = "rdr_renderPane";
            this.rdr_renderPane.Services = serviceManager2;
            this.rdr_renderPane.Size = new System.Drawing.Size(781, 547);
            this.rdr_renderPane.TabIndex = 18;
            this.rdr_renderPane.Text = "button2";
            // 
            // prp_properties
            // 
            this.prp_properties.Location = new System.Drawing.Point(789, 46);
            this.prp_properties.Name = "prp_properties";
            this.prp_properties.Size = new System.Drawing.Size(318, 339);
            this.prp_properties.TabIndex = 19;
            // 
            // RenderPaneTestForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1106, 551);
            this.Controls.Add(this.prp_properties);
            this.Controls.Add(this.rdr_renderPane);
            this.Name = "RenderPaneTestForm";
            this.Text = "RenderPaneTestForm";
            this.ResumeLayout(false);

        }
コード例 #8
0
ファイル: ExclusiveService.cs プロジェクト: cliftonm/clifton
 public static void Demo()
 {
     ServiceManager svcMgr = new ServiceManager();
     svcMgr.RegisterSingleton<IAnimal, Cat>();
     IAnimal animal = svcMgr.Get<IAnimal>();
     animal.Speak();
 }
コード例 #9
0
ファイル: Module.cs プロジェクト: FloodProject/flood
        public void OnLoad(ServiceManager serviceManager)
        {
            var windowManager = serviceManager.GetGlobalService<IWindowManager>();
            var editorWindowTask = windowManager.GetCreateWindow("Editor");
            editorWindowTask.Wait();
            var editorWindow = editorWindowTask.Result;

            var gui = new GuiRenderable();
            editorWindow.AddRenderable(gui);

            var paneManager = new PaneManager(gui.Canvas);
            serviceManager.GetCreateImplementation<IPaneManager>(paneManager);

            paneManager.AddPane(new Pane { Title = "Pane1" });
            paneManager.AddPane(new Pane { Title = "Pane2" });

            var application = serviceManager.Application;

            var nativeWindowManager = application.Engine.WindowManager;
            fileMenu = nativeWindowManager.CreateMenu();
            openItem = fileMenu.AppendItem("Open", MenuItemKind.Normal);
            openItem.Selected +=
                () => nativeWindowManager.OpenFileDialog("*", FileDialogFlags.Open);
            fileMenu.AppendItem("Close", MenuItemKind.Normal);
            fileMenu.AppendItem("New", MenuItemKind.Normal);

            var menuBar = nativeWindowManager.CreateMenuBar();
            menuBar.Append(fileMenu, "File");

            var nativeWindow = application.WindowManager.GetWindow("Editor");
            nativeWindow.nativeWindow.MenuBar = menuBar;
            nativeWindow.nativeWindow.Show(true);
        }
コード例 #10
0
ファイル: NoteManager.cs プロジェクト: scottroot2/MagicMirror
 public async Task<Note[]> GetData()
 {
     ServiceManager noteServiceManager =
         new ServiceManager(new Uri("http://mirrorservice.azurewebsites.net/api/notes"));
     var response =  await noteServiceManager.CallService<Note[]>();
     return response;
 }
コード例 #11
0
        public static void Bootstrap()
        {
            serviceManager = new ServiceManager();
            serviceManager.RegisterSingleton<IModuleManager, ModuleManager>();

            try
            {
                IModuleManager moduleMgr = serviceManager.Get<IModuleManager>();
                List<AssemblyFileName> moduleFilenames = moduleMgr.GetModuleList(XmlFileName.Create("modules.xml"));

                moduleMgr.RegisterModules(moduleFilenames);
                serviceManager.FinishedInitialization();
            }
            catch (ReflectionTypeLoadException ex)
            {
                foreach (var item in ex.LoaderExceptions)
                {
                    MessageBox.Show(item.Message + "\r\n" + ex.StackTrace, "Reflection Type Loader Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "Initialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: philfanzhou/PredictFuture
        static void Main(string[] args)
        {
            Console.WriteLine("=================================");
            Console.WriteLine("");
            Console.WriteLine("=================================");

            if (Process.GetProcessesByName("PF.DistributedService.Hosting").Length > 1)
            {
                Console.WriteLine("The PF.DistributedService.Hosting is already running");
                Console.WriteLine("Press any key to exit....");
                Console.Read();
            }
            else
            {
                ServiceInitialize.Init();

                var serviceManager =
                    new ServiceManager(new List<object>
                    {
                        typeof (AuthenticationService),
                        typeof (OAuth2AuthorizationServer),
                        typeof (CrosscuttingService),
                        typeof (FinanceDataService),
                        typeof (PriceDataService)
                    });
                serviceManager.Open();
                Console.WriteLine("service start sucessfully.");
                Console.Read();
            }
        }
コード例 #13
0
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            ServiceManager serviceManager1 = new ServiceManager();
            this.btn_loadTerrain = new System.Windows.Forms.Button();
            this.fil_openTerrain = new System.Windows.Forms.OpenFileDialog();
            this.rdr_terrainView = new RenderPane();
            this.prp_terrainProperties = new System.Windows.Forms.PropertyGrid();
            this.btn_done = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // btn_loadTerrain
            // 
            this.btn_loadTerrain.Location = new System.Drawing.Point(254, 488);
            this.btn_loadTerrain.Name = "btn_loadTerrain";
            this.btn_loadTerrain.Size = new System.Drawing.Size(90, 36);
            this.btn_loadTerrain.TabIndex = 0;
            this.btn_loadTerrain.Text = "Set Terrain File";
            this.btn_loadTerrain.UseVisualStyleBackColor = true;
            this.btn_loadTerrain.Click += new System.EventHandler(this.btn_loadTerrain_Click);
            // 
            // rdr_terrainView
            // 
            this.rdr_terrainView.Location = new System.Drawing.Point(350, 12);
            this.rdr_terrainView.Name = "rdr_terrainView";
            this.rdr_terrainView.Services = serviceManager1;
            this.rdr_terrainView.Size = new System.Drawing.Size(670, 512);
            this.rdr_terrainView.TabIndex = 0;
            // 
            // prp_terrainProperties
            // 
            this.prp_terrainProperties.Location = new System.Drawing.Point(12, 248);
            this.prp_terrainProperties.Name = "prp_terrainProperties";
            this.prp_terrainProperties.Size = new System.Drawing.Size(332, 234);
            this.prp_terrainProperties.TabIndex = 1;
            // 
            // btn_done
            // 
            this.btn_done.Location = new System.Drawing.Point(12, 488);
            this.btn_done.Name = "btn_done";
            this.btn_done.Size = new System.Drawing.Size(90, 36);
            this.btn_done.TabIndex = 2;
            this.btn_done.Text = "Done";
            this.btn_done.UseVisualStyleBackColor = true;
            this.btn_done.Click += new System.EventHandler(this.btn_done_Click);
            // 
            // TerrainEditorForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1032, 536);
            this.Controls.Add(this.btn_done);
            this.Controls.Add(this.prp_terrainProperties);
            this.Controls.Add(this.rdr_terrainView);
            this.Controls.Add(this.btn_loadTerrain);
            this.Name = "TerrainEditorForm";
            this.Text = "LoadTerrainForm";
            this.ResumeLayout(false);

        }
コード例 #14
0
        public void DoubleAddException()
        {
            var manager = new ServiceManager();
            var empty = new EmptyClass();

            manager.SetProvider(empty);
            manager.SetProvider(empty);
        }
コード例 #15
0
ファイル: ImapClientWrapper.cs プロジェクト: alexed1/dtrack
        public void Initialize(String serverURL, int port, bool useSSL)
        {
            _serviceManager = new ServiceManager<ImapClientWrapper>("Imap Service: " + serverURL, "Email Services");

            _internalClient = new ImapClient(serverURL, port, useSSL);
            
            _serviceManager.LogEvent("Installed event listener for new messages.");
        }
コード例 #16
0
ファイル: CronCommand.cs プロジェクト: huoxudong125/ServerX
 private static OptionSet GetOptions(Options options = null, ServiceManager svc = null)
 {
     return new OptionSet
     {
         { "status|s=", "Displays status information for all cron jobs", v => options.Subdirectory = v },
         { "<>", v => options.ExtensionIDs.Add(v) },
     };
 }
コード例 #17
0
 private static OptionSet GetOptions(Options options = null, ServiceManager svc = null)
 {
     return new OptionSet
     {
         { "subdir|s=", "Restricts the extensions to be restarted to a specific extension subdirectory", v => options.Subdirectory = v },
         { "<>", v => options.ExtensionIDs.Add(v) },
     };
 }
コード例 #18
0
        private void FinishConstruction()
        {
            _packetReader = new BinaryReader(_packetStream);

            Services = new ServiceManager(this);

            Services.Add<PacketEventService>();
            Services.Add<InternalPacketManagerService>();
        }
コード例 #19
0
        public static void StartNetworkServices(GTM.GHIElectronics.EthernetENC28 ethernetENC28, string deviceName, bool connected, string uniqueDeviceIdentifier = "")
        {
            ethernetENC28.UseThisNetworkInterface();
            while (!ethernetENC28.IsNetworkConnected) {
                Thread.Sleep(1000);
            }

            sm = Utilities.StartNetworkServices(deviceName, connected, uniqueDeviceIdentifier);
        }
コード例 #20
0
        public void GetProvider()
        {
            var manager = new ServiceManager();
            var empty = new EmptyClass();

            manager.SetProvider(empty);

            Assert.AreSame(manager.GetProvider<EmptyClass>(), empty);
        }
コード例 #21
0
ファイル: InstanceDemo.cs プロジェクト: cliftonm/clifton
 public static void Demo()
 {
     ServiceManager svcMgr = new ServiceManager();
     svcMgr.RegisterInstanceOnly<ICat, Cat>();
     IAnimal cat1 = svcMgr.Get<ICat>();
     cat1.Name = "Fido";
     IAnimal cat2 = svcMgr.Get<ICat>(cat => cat.Name = "Morris");
     cat1.Speak();
     cat2.Speak();
 }
コード例 #22
0
ファイル: FavoritesDummyForm.cs プロジェクト: permyakov/janus
 private FavoritesDummyForm(IServiceProvider provider)
 {
     _serviceManager = new ServiceManager(provider);
     _favManager = provider.GetRequiredService<IFavoritesManager>();
     InitializeComponent();
     FillImages();
     CustomInitializeComponent();
     _serviceManager.Publish<IFavoritesDummyFormService>(new FavoritesDummyFormService(this));
     _contextMenuGenerator = new StripMenuGenerator(_serviceManager, _contextMenuStrip, "Favorites.ContextMenu");
 }
コード例 #23
0
ファイル: SingletonDemo.cs プロジェクト: cliftonm/clifton
 public static void Demo()
 {
     ServiceManager svcMgr = new ServiceManager();
     svcMgr.RegisterSingleton<ICat, Cat>();
     svcMgr.RegisterSingleton<IDog, Dog>();
     IAnimal animal1 = svcMgr.Get<ICat>();
     IAnimal animal2 = svcMgr.Get<IDog>();
     animal1.Speak();
     animal2.Speak();
 }
コード例 #24
0
ファイル: ServiceManagerTests.cs プロジェクト: alfeg/nunit
        public void SetUp()
        {
            _serviceManager = new ServiceManager();

            _settingsService = new FakeSettingsService();
            _serviceManager.AddService(_settingsService);

            _projectService = new FakeProjectService();
            _serviceManager.AddService(_projectService);
        }
コード例 #25
0
		public void Start(ServiceManager serviceManager)
		{
			CommandManager commandManager = (CommandManager)serviceManager.GetService(typeof(CommandManager));
			ExportModelCommand showCommand = new ExportModelCommand();
			commandManager.Commands.Add(showCommand);

			CommandBarManager commandBarManager = (CommandBarManager)serviceManager.GetService(typeof(CommandBarManager));
			CommandBar commandBar = commandBarManager.CommandBars.AddCommandBar("Export Model");
			commandBarManager.RootTools.AddButtonTool(showCommand.Key, "Export Model", null, showCommand);
			commandBar.Tools.AddTool(showCommand.Key);
		}
コード例 #26
0
        public void Generic_Service_should_not_get_registered_with_generic_parameter()
        {
            var serviceManager = new ServiceManager(typeof(GenericService<>).Assembly);
            serviceManager.Init();

            // We should definately *not* be able to call the generic service with a "T" request object :)
            var serviceController = serviceManager.ServiceController;
            var requestType = typeof(GenericService<>).GetGenericArguments()[0];
            var exception = Assert.Throws<System.NotImplementedException>(() => serviceController.GetService(requestType));

            Assert.That(exception.Message, Is.StringContaining("Unable to resolve service"));
        }
コード例 #27
0
        public void Can_inject_RequestContext_for_IRequiresRequestContext_services()
        {
            var serviceManager = new ServiceManager(typeof(RequiresContextService).Assembly);
            serviceManager.Init();

            var serviceController = serviceManager.ServiceController;

            var request = new RequiresContext();
            var response = serviceController.Execute(request, new HttpRequestContext(request))
                as RequiresContextResponse;

            Assert.That(response, Is.Not.Null);
        }
コード例 #28
0
ファイル: JanusHost.cs プロジェクト: permyakov/janus
        internal JanusHost(IServiceProvider serviceProvider)
        {
            _serviceManager =
                serviceProvider == null
                    ? new ServiceManager(true)
                    : new ServiceManager(true, serviceProvider);

            // TODO: Hack! Must be eliminated.
            ApplicationManager.Instance.ServiceProvider = this;

            _serviceManager.PublishDisposable<IEventBroker>(new EventBroker());
            InitExtensibility();
            _activePartManager = ActivePartsHelper.CreateAndPublishManager(_serviceManager);
        }
コード例 #29
0
        private static void Main()
        {
            serviceManager = new ServiceManager();

            var filePath = ConfigurationManager.AppSettings["FilePath"];
            var fileName = ConfigurationManager.AppSettings["FileName"];
            FileAttachment fileAttachment = new FileAttachment
            {
                FileStream = new FileStream(filePath+fileName, FileMode.Open),
                OriginalName = fileName
            };

            var requestId = Int32.Parse(ConfigurationManager.AppSettings["RequestId"]);
            AddAttachmentToRequest(requestId, fileAttachment);
        }
コード例 #30
0
ファイル: SearchDummyForm.cs プロジェクト: permyakov/janus
        public SearchDummyForm(IServiceProvider provider)
        {
            _asyncOperation = AsyncHelper.CreateOperation();
            _serviceManager = new ServiceManager(provider);

            _serviceManager.Publish<IDefaultCommandService>(
                new DefaultCommandService("Janus.Forum.GoToMessage"));

            this.AssignServices(provider);

            InitializeComponent();

            _msgViewer = new MsgViewer(_serviceManager) { Dock = DockStyle.Fill };
            _splitContainer.Panel2.Controls.Add(_msgViewer);
            CustomInitializeComponent();
        }
コード例 #31
0
 public MappingService(ServiceManager <IService> Services) : base(Services)
 {
 }
コード例 #32
0
 /// <summary>
 /// Retrives contained language host if already created.
 /// </summary>
 /// <param name="textBuffer">Contained language buffer</param>
 /// <returns>Contained language host for this buffer and language, <seealso cref="IContainedLanguageHost"/> if it exists</returns>
 public static IContainedLanguageHost TryGetHost(ITextBuffer textBuffer)
 {
     return(ServiceManager.GetService <IContainedLanguageHost>(textBuffer));
 }
コード例 #33
0
        protected async Task <List <Card> > GetPointOfInterestLocationCards(DialogContext sc, List <PointOfInterestModel> pointOfInterestList)
        {
            var state = await Accessor.GetAsync(sc.Context);

            var service        = ServiceManager.InitMapsService(Settings);
            var addressService = ServiceManager.InitAddressMapsService(Settings);
            var cards          = new List <Card>();

            if (pointOfInterestList != null && pointOfInterestList.Count > 0)
            {
                for (var i = 0; i < pointOfInterestList.Count; i++)
                {
                    if (sc.ActiveDialog.Id.Equals(Actions.CheckForCurrentLocation))
                    {
                        pointOfInterestList[i] = await addressService.GetPointOfInterestDetailsAsync(pointOfInterestList[i]);
                    }
                    else
                    {
                        pointOfInterestList[i] = await service.GetPointOfInterestDetailsAsync(pointOfInterestList[i]);
                    }

                    // Increase by one to avoid zero based options to the user which are confusing
                    pointOfInterestList[i].Index = i + 1;

                    if (string.IsNullOrEmpty(pointOfInterestList[i].PointOfInterestImageUrl))
                    {
                        pointOfInterestList[i].PointOfInterestImageUrl = GetCardImageUri(FallbackPointOfInterestImageFileName);
                    }

                    if (string.IsNullOrEmpty(pointOfInterestList[i].Name))
                    {
                        // Show address as the name
                        pointOfInterestList[i].Name    = pointOfInterestList[i].Address;
                        pointOfInterestList[i].Address = string.Empty;
                    }

                    pointOfInterestList[i].ProviderDisplayText = string.Format($"{PointOfInterestSharedStrings.POWERED_BY} **{{0}}**", pointOfInterestList[i].Provider.Aggregate((j, k) => j + "&" + k).ToString());

                    // If multiple points of interest share the same name, use their combined name & address as the speak property.
                    // Otherwise, just use the name.
                    if (pointOfInterestList.Where(x => x.Name == pointOfInterestList[i].Name).Skip(1).Any())
                    {
                        var promptTemplate     = POISharedResponses.PointOfInterestSuggestedActionName;
                        var promptReplacements = new StringDictionary
                        {
                            { "Name", pointOfInterestList[i].Name },
                            { "Address", pointOfInterestList[i].AddressForSpeak },
                        };
                        pointOfInterestList[i].Speak = ResponseManager.GetResponse(promptTemplate, promptReplacements).Text;
                    }
                    else
                    {
                        pointOfInterestList[i].Speak = pointOfInterestList[i].Name;
                    }
                }

                state.LastFoundPointOfInterests = pointOfInterestList;

                foreach (var pointOfInterest in pointOfInterestList)
                {
                    cards.Add(new Card("PointOfInterestDetails", pointOfInterest));
                }
            }

            return(cards);
        }
コード例 #34
0
 /// <summary>
 /// 生成默认的设置
 /// </summary>
 /// <returns></returns>
 static Config.ClientConfig GetDefaultConfig()
 {
     return(new ClientConfig()
     {
         Themes = "Default",
         HostListViewConfig = new ListConfig()
         {
             FirstGroupType = ListConfig.GroupType.None,
             SecondGroupType = ListConfig.GroupType.None,
             FirstOrder = ListConfig.SortOrder.State,
             SecondOrder = ListConfig.SortOrder.IP
         },
         IPMClientConfig = new FSLib.IPMessager.Entity.Config
         {
             Port = 2425,
             GroupName = Environment.MachineName,
             NickName = Environment.UserName,
             ForceOldContract = true,
             IgnoreNoAddListFlag = false,
             EnableHostNotifyBroadcast = false,
             HostName = Environment.MachineName,
             AutoReplyWhenAbsence = true,
             AutoDetectVersion = true,
             BanedHost = new List <string>(),
             KeepedHostList = new List <string>(),
             BindedIP = IPAddress.Any,
             VersionInfo = "飞鸽传书.Net " + Application.ProductVersion + ",BY 木鱼",
             AbsenceSuffix = " [离开]",
             Services = ServiceManager.GetServices(GetAddinPath()),
             EnableBPContinue = true,
             TaskKeepTime = 600,
             TasksMultiReceiveCount = 1
         },
         AbsenceMessage = new List <string>()
         {
             "我有事暂时不在,稍后联系你",
             "我吃饭去了!",
             "我玩游戏去了!",
             "还钱请电话,借钱请关机!"
         },
         FrameContainerConfig = new IPMessagerNet.UI.Forms.FrameContainerConfig()
         {
             HostListContainerTopMost = true,
             HostListFloat = false,
             MinimizeToTray = true,
             WindowState = -1,
             HostListContainerWindowState = -1
         },
         HostGroupConfig = new SerializableDictionary <string, string>(),
         HostInfo = new HostInfoConfig()
         {
             DisplayStyle = HostNameDisplayStyle.MemoBeforeName,
             HostMemo = new SerializableDictionary <string, string>(),
             HostOfflineTip = HostBallonTip.All,
             HostOnlineTip = HostBallonTip.All,
             OfflineTip = new List <string>(),
             OnlineTip = new List <string>(),
             DisableHostTipInQuite = true
         },
         ChatConfig = new ChatAreaConfig()
         {
             EnableCtrlEnterShortKey = true
         },
         FunctionConfig = new ClientFunctionConfig()
         {
             Share_CalculateFolderSize = true
         }
     });
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="POCOExcelRowConverter{T}"/> class.
 /// </summary>
 /// <param name="parent">O365Extension to which the result of the request for data will be returned</param>
 public POCOExcelRowConverter(ServiceManager serviceManager)
 {
     this._serviceManager = serviceManager;
 }
コード例 #36
0
ファイル: EditorDocumentMock.cs プロジェクト: fpcMotif/RTVS
 public EditorDocumentMock(IEditorTree tree)
 {
     EditorTree = tree;
     ServiceManager.AddService <IREditorDocument>(this, tree.TextBuffer);
 }
コード例 #37
0
        private void monthCalendar1_Drop(object sender, RoutedEventArgs e)
        {
            ExDragEventArgs arg = (ExDragEventArgs)e;

            if (arg.DragEventArgs.Data.GetDataPresent("DateTime"))
            {
                DateTime date       = (DateTime)arg.DragEventArgs.Data.GetData("DateTime");
                DateTime targetDate = (DateTime)arg.DirectTarget.Tag;
                var      result     = entriesViewer.CalendarControl.GetDateInfo(date);
                if (result.Count == 1)
                {
                    var dayInfo = (TrainingDayInfo)result[0];

                    TrainingDayDTO day = getTrainingDay(date);
                    if (targetDate.IsFuture() && !UIHelper.EnsurePremiumLicence())
                    {
                        return;
                    }
                    if (Keyboard.IsKeyDown(Key.LeftCtrl))
                    {
                        dayInfo.IsProcessing = true;
                        ParentWindow.RunAsynchronousOperation(x =>
                        {
                            //if (day.GlobalId != Constants.UnsavedGlobalId)
                            //{//user select Cut operation so we should only move this one time (not many time like with Copy operation)
                            //    WorkoutDayGetOperation operation = new WorkoutDayGetOperation();
                            //    operation.UserId = User.Id;
                            //    operation.Operation = GetOperation.Current;
                            //    operation.WorkoutDateTime = day.TrainingDate;
                            //    day = ServiceManager.GetTrainingDay(operation);
                            //}
                            try
                            {
                                day = day.Copy();
                                day.ChangeDate(targetDate);
                                var result1 = ServiceManager.SaveTrainingDay(day);
                                if (result1.TrainingDay != null)
                                {
                                    cache.Add(result1.TrainingDay);
                                }
                            }
                            catch (OldDataException ex)
                            {
                                UIHelper.Invoke(() => ExceptionHandler.Default.Process(ex, "ErrorOldTrainingDay".TranslateStrings(), ErrorWindow.MessageBox), Dispatcher);
                            }
                            catch (Exception ex)
                            {
                                UIHelper.Invoke(() => ExceptionHandler.Default.Process(ex, "ErrorMoveTrainingDay".TranslateStrings(), ErrorWindow.EMailReport), Dispatcher);
                            }
                            finally
                            {
                                dayInfo.IsProcessing = false;
                            }
                        });
                    }
                    else if (BAMessageBox.AskYesNo("QMoveTrainingDay".TranslateStrings()) == MessageBoxResult.Yes)
                    {
                        if (day.CanMove)
                        {
                            dayInfo.IsProcessing = true;
                            ParentWindow.RunAsynchronousOperation(x =>
                            {
                                //if (day.GlobalId != Constants.UnsavedGlobalId)
                                //{//user select Cut operation so we should only move this one time (not many time like with Copy operation)
                                //    WorkoutDayGetOperation operation = new WorkoutDayGetOperation();
                                //    operation.UserId = User.Id;
                                //    operation.Operation = GetOperation.Current;
                                //    operation.WorkoutDateTime = day.TrainingDate;
                                //    day = ServiceManager.GetTrainingDay(operation);
                                //}
                                try
                                {
                                    day = day.StandardClone();
                                    day.ChangeDate(targetDate);
                                    var result1 = ServiceManager.SaveTrainingDay(day);
                                    cache.Remove(date);

                                    if (result1.TrainingDay != null)
                                    {
                                        day = result1.TrainingDay;
                                        cache.Add(day);
                                    }
                                }
                                catch (OldDataException ex)
                                {
                                    UIHelper.Invoke(() => ExceptionHandler.Default.Process(ex, "ErrorOldTrainingDay".TranslateStrings(), ErrorWindow.MessageBox), Dispatcher);
                                }
                                catch (Exception ex)
                                {
                                    UIHelper.Invoke(() => ExceptionHandler.Default.Process(ex, "ErrorMoveTrainingDay".TranslateStrings(), ErrorWindow.EMailReport), Dispatcher);
                                }
                                finally
                                {
                                    dayInfo.IsProcessing = false;
                                }
                            });
                        }
                        else
                        {
                            BAMessageBox.ShowError("ErrorCannotMoveTrainingDayFixedEntries".TranslateStrings());
                        }
                    }
                }
            }
        }
コード例 #38
0
 NotificationService()
 {
     ServiceManager.Register <INotificationService>(this);
 }
コード例 #39
0
 /// <summary>
 /// 构造函数
 /// </summary>
 public FavoriteScriptMgeSvr() : base()
 {
     _SessionMgeSvr     = ServiceManager.GetService <ISessionMgeSvr>();
     daoManager         = ServiceConfig.GetInstance().DaoManager;
     _FavoriteScriptDao = (IFavoriteScriptDao)daoManager.GetDao(typeof(IFavoriteScriptDao));
 }
コード例 #40
0
 public static RCompletionController FromTextView(ITextView textView)
 {
     return(ServiceManager.GetService <RCompletionController>(textView));
 }
コード例 #41
0
 protected override bool OnPopupMenu()
 {
     ServiceManager.Get <InterfaceActionService> ().TrackActions["TrackContextMenuAction"].Activate();
     return(true);
 }
コード例 #42
0
        private void Init()
        {
            SettingsManager.Instance.Load();
            LanguagesManager.Instance.SetCurrentLanguage(SettingsManager.Instance.UseLanguage);

            {
                string configPath = Path.Combine(AmoebaEnvironment.Paths.ConfigPath, "Service");
                if (!Directory.Exists(configPath))
                {
                    Directory.CreateDirectory(configPath);
                }

                _serviceManager = new ServiceManager(configPath, AmoebaEnvironment.Config.Cache.BlocksPath, BufferManager.Instance);
                _serviceManager.Load();

                {
                    var locations = new List <Location>();

                    using (var reader = new StreamReader("Locations.txt"))
                    {
                        string line;

                        while ((line = reader.ReadLine()) != null)
                        {
                            locations.Add(AmoebaConverter.FromLocationString(line));
                        }
                    }

                    _serviceManager.SetCloudLocations(locations);
                }

                if (_serviceManager.Config.Core.Download.BasePath == null)
                {
                    lock (_serviceManager.LockObject)
                    {
                        var oldConfig = _serviceManager.Config;
                        _serviceManager.SetConfig(new ServiceConfig(new CoreConfig(oldConfig.Core.Network, new DownloadConfig(AmoebaEnvironment.Paths.DownloadsPath, oldConfig.Core.Download.ProtectedPercentage)), oldConfig.Connection, oldConfig.Message));
                    }
                }
            }

            {
                string configPath = Path.Combine(AmoebaEnvironment.Paths.ConfigPath, "Control", "Message");
                if (!Directory.Exists(configPath))
                {
                    Directory.CreateDirectory(configPath);
                }

                _messageManager = new MessageManager(configPath, _serviceManager);
                _messageManager.Load();
            }

            {
                this.Title = SettingsManager.Instance.AccountInfo.ObserveProperty(n => n.DigitalSignature)
                             .Select(n => $"Amoeba {AmoebaEnvironment.Version} - {n.ToString()}").ToReactiveProperty().AddTo(_disposable);

                this.RelationCommand = new ReactiveCommand().AddTo(_disposable);
                this.RelationCommand.Subscribe(() => this.Relation()).AddTo(_disposable);

                this.OptionsCommand = new ReactiveCommand().AddTo(_disposable);
                this.OptionsCommand.Subscribe(() => this.Options()).AddTo(_disposable);

                this.CheckBlocksCommand = new ReactiveCommand().AddTo(_disposable);
                this.CheckBlocksCommand.Subscribe(() => this.CheckBlocks()).AddTo(_disposable);

                this.LanguageCommand = new ReactiveCommand <string>().AddTo(_disposable);
                this.LanguageCommand.Subscribe((n) => LanguagesManager.Instance.SetCurrentLanguage(n)).AddTo(_disposable);

                this.WebsiteCommand = new ReactiveCommand().AddTo(_disposable);
                this.WebsiteCommand.Subscribe(() => this.Website()).AddTo(_disposable);

                this.VersionCommand = new ReactiveCommand().AddTo(_disposable);
                this.VersionCommand.Subscribe(() => this.Version()).AddTo(_disposable);

                this.IsProgressDialogOpen = new ReactiveProperty <bool>().AddTo(_disposable);

                this.ReceivingSpeed = new ReactiveProperty <decimal>().AddTo(_disposable);
                this.SendingSpeed   = new ReactiveProperty <decimal>().AddTo(_disposable);

                this.WindowSettings = new ReactiveProperty <WindowSettings>().AddTo(_disposable);
            }

            {
                string configPath = Path.Combine(AmoebaEnvironment.Paths.ConfigPath, "View", "MainWindow");
                if (!Directory.Exists(configPath))
                {
                    Directory.CreateDirectory(configPath);
                }

                _settings = new Settings(configPath);
                int version = _settings.Load("Version", () => 0);

                this.WindowSettings.Value = _settings.Load(nameof(WindowSettings), () => new WindowSettings());
                this.DynamicOptions.SetProperties(_settings.Load(nameof(DynamicOptions), () => Array.Empty <DynamicOptions.DynamicPropertyInfo>()));
            }

            {
                this.CloudControlViewModel        = new CloudControlViewModel(_serviceManager, _dialogService);
                this.ChatControlViewModel         = new ChatControlViewModel(_serviceManager, _messageManager, _dialogService);
                this.StoreControlViewModel        = new StoreControlViewModel(_serviceManager, _dialogService);
                this.StorePublishControlViewModel = new UploadControlViewModel(_serviceManager, _dialogService);
                this.SearchControlViewModel       = new SearchControlViewModel(_serviceManager, _messageManager, _dialogService);
                this.DownloadControlViewModel     = new DownloadControlViewModel(_serviceManager, _dialogService);
                this.UploadControlViewModel       = new UploadControlViewModel(_serviceManager, _dialogService);
            }

            {
                _watchManager = new WatchManager(_serviceManager, _dialogService);
            }

            {
                Backup.Instance.SaveEvent += this.Save;
            }

            this.Setting_TrafficView();
        }
コード例 #43
0
        protected override void ImportCore()
        {
            LibraryImportManager import_manager = ServiceManager.Get <LibraryImportManager> ();

            SafeUri db_uri = rhythmbox_db_uri;

            // Check if library is located in the old place (.gnome2/rhythmbox/rhythmdb.db)
            if (!Banshee.IO.File.Exists(rhythmbox_db_uri))
            {
                db_uri = rhythmbox_db_uri_old;
            }

            if (!IsValidXmlDocument(db_uri))
            {
                LogError(SafeUri.UriToFilename(db_uri), "Rhythmbox library is corrupted.");
                return;
            }

            // Load Rhythmbox library
            Stream      stream_db  = Banshee.IO.File.OpenRead(db_uri);
            XmlDocument xml_doc_db = new XmlDocument();

            xml_doc_db.Load(stream_db);
            XmlElement db_root = xml_doc_db.DocumentElement;

            stream_db.Close();

            if (db_root == null || !db_root.HasChildNodes || db_root.Name != "rhythmdb")
            {
                LogError(SafeUri.UriToFilename(db_uri), "Unable to open Rhythmbox library.");
                return;
            }

            count     = db_root.ChildNodes.Count;
            processed = 0;

            // Import Rhythmbox playlists if playlist file is available
            SafeUri rhythmbox_playlists_uri = new SafeUri(Hyena.Paths.Combine(
                                                              Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                                                              ".local", "share", "rhythmbox", "playlists.xml"
                                                              ));

            bool playlists_available = Banshee.IO.File.Exists(rhythmbox_playlists_uri);

            // Look at the old location too
            if (!playlists_available)
            {
                rhythmbox_playlists_uri = new SafeUri(Hyena.Paths.Combine(
                                                          Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                                                          ".gnome2", "rhythmbox", "playlists.xml"
                                                          ));

                playlists_available = Banshee.IO.File.Exists(rhythmbox_playlists_uri);
            }

            XmlElement playlists_root = null;

            if (playlists_available)
            {
                if (IsValidXmlDocument(rhythmbox_playlists_uri))
                {
                    Stream      stream_playlists  = Banshee.IO.File.OpenRead(rhythmbox_playlists_uri);
                    XmlDocument xml_doc_playlists = new XmlDocument();
                    xml_doc_playlists.Load(stream_playlists);
                    playlists_root = xml_doc_playlists.DocumentElement;
                    stream_playlists.Close();

                    if (playlists_root == null || !playlists_root.HasChildNodes || playlists_root.Name != "rhythmdb-playlists")
                    {
                        playlists_available = false;
                    }
                    else
                    {
                        count += playlists_root.ChildNodes.Count;
                    }
                }
                else
                {
                    LogError(SafeUri.UriToFilename(rhythmbox_playlists_uri), "Rhythmbox playlists are corrupted.");
                    playlists_available = false;
                }
            }

            ImportSongs(import_manager, db_root.SelectNodes("/rhythmdb/entry[@type='song']"));

            //ImportPodcasts (import_manager, db_root.SelectNodes ("/rhythmdb/entry[@type='podcast-post']"));

            if (playlists_available)
            {
                ImportStaticPlaylists(playlists_root.SelectNodes("/rhythmdb-playlists/playlist[@type='static']"));
            }

            import_manager.NotifyAllSources();
        }
コード例 #44
0
 public void SetUp()
 {
     _serviceManager = new ServiceManager();
     _registration   = new CustomRegistration();
     _serviceManager.RegisterBootstrap(BootstrapRegistration.For <IRegistration>(_registration));
 }
コード例 #45
0
        public PodcastActions(PodcastSource source) : base(ServiceManager.Get <InterfaceActionService> (), "Podcast")
        {
            this.podcast_source = source;
            ImportantByDefault  = false;

            Add(
                new ActionEntry(
                    "PodcastUpdateAllAction", Stock.Refresh,
                    Catalog.GetString("Refresh"), null,  //"<control><shift>U",
                    Catalog.GetString("Check all podcasts for new episodes"),
                    OnPodcastUpdateAll
                    ),
                new ActionEntry(
                    "PodcastAddAction", Stock.Add,
                    Catalog.GetString("Add Podcast..."), "<control><shift>F",
                    Catalog.GetString("Subscribe to a new podcast"),
                    OnPodcastAdd
                    )
                );

            Add(
                new ActionEntry("PodcastFeedPopupAction", null,
                                String.Empty, null, null, OnFeedPopup),

                new ActionEntry("EpisodePodcastMenu", null,
                                Catalog.GetString("Podcast"), null, null, null),

                new ActionEntry(
                    "PodcastDeleteAction", Stock.Delete,
                    Catalog.GetString("Unsubscribe and Delete"),
                    null, String.Empty,
                    OnPodcastDelete
                    ),
                new ActionEntry(
                    "PodcastUpdateFeedAction", Stock.Refresh,
                    Catalog.GetString("Check for New Episodes"),
                    null, String.Empty,
                    OnPodcastUpdate
                    ),
                new ActionEntry(
                    "PodcastDownloadAllAction", Stock.Save,
                    Catalog.GetString("Download All Episodes"),
                    null, String.Empty,
                    OnPodcastDownloadAllEpisodes
                    ),
                new ActionEntry(
                    "PodcastHomepageAction", Stock.JumpTo,
                    Catalog.GetString("Visit Podcast Homepage"),
                    null, String.Empty,
                    OnPodcastHomepage
                    ),
                new ActionEntry(
                    "PodcastPropertiesAction", Stock.Properties,
                    Catalog.GetString("Properties"),
                    null, String.Empty,
                    OnPodcastProperties
                    ),
                new ActionEntry(
                    "EpisodePodcastProperties", null,
                    Catalog.GetString("Podcast Properties"), null, String.Empty,
                    OnEpisodePodcastProperties
                    ),
                new ActionEntry(
                    "PodcastItemMarkNewAction", null,
                    Catalog.GetString("Mark as New"),
                    null, String.Empty,
                    OnPodcastItemMarkNew
                    ),
                new ActionEntry(
                    "PodcastItemMarkOldAction", null,
                    Catalog.GetString("Archive"), "y", String.Empty,
                    OnPodcastItemMarkOld
                    ),
                new ActionEntry(
                    "PodcastItemDownloadAction", Stock.Save,
                    /* Translators: this is a verb used as a button name, not a noun*/
                    Catalog.GetString("Download"),
                    "<control><shift>D", String.Empty,
                    OnPodcastItemDownload
                    ),
                new ActionEntry(
                    "PodcastItemCancelAction", Stock.Cancel,
                    Catalog.GetString("Cancel Download"),
                    "<control><shift>C", String.Empty,
                    OnPodcastItemCancel
                    ),
                new ActionEntry(
                    "PodcastItemDeleteFileAction", Stock.Remove,
                    "",
                    null, String.Empty,
                    OnPodcastItemDeleteFile
                    ),
                new ActionEntry(
                    "PodcastItemLinkAction", Stock.JumpTo,
                    Catalog.GetString("Visit Website"),
                    null, String.Empty,
                    OnPodcastItemLink
                    ),
                new ActionEntry(
                    "PodcastItemPropertiesAction", Stock.Properties,
                    Catalog.GetString("Properties"),
                    null, String.Empty,
                    OnPodcastItemProperties
                    )
                );

            this["PodcastAddAction"].ShortLabel = Catalog.GetString("Add Podcast");

            actions_id = Actions.UIManager.AddUiFromResource("GlobalUI.xml");
            Actions.AddActionGroup(this);

            ServiceManager.SourceManager.ActiveSourceChanged += HandleActiveSourceChanged;
            OnSelectionChanged(null, null);
        }
コード例 #46
0
 public FamingService(EnergizeClient client)
 {
     this.ServiceManager = client.ServiceManager;
     this.MessageSender  = client.MessageSender;
     this.Logger         = client.Logger;
 }
コード例 #47
0
        public void Paste()
        {
            if (IsSelectedDateFuture && !UIHelper.EnsurePremiumLicence())
            {
                return;
            }
            if (Clipboard.ContainsData(Shared.Constants.ClipboardFormat))
            {
                if (SelectedTrainingDay == null)
                {
                    var  day          = (TrainingDayDTO)Clipboard.GetData(Shared.Constants.ClipboardFormat);
                    bool isCut        = !day.IsNew;
                    var  originalDay  = day.StandardClone();
                    var  selectedDate = entriesViewer.CalendarControl.SelectedDate;
                    var  dayInfo      = GetDayInfo(day.TrainingDate);
                    dayInfo.IsProcessing = true;
                    if (isCut)
                    {
                        Clipboard.Clear();
                    }
                    ParentWindow.RunAsynchronousOperation(x =>
                    {
                        try
                        {
                            if (isCut)
                            {
                                //user select Cut operation so we should only move this one time (not many time like with Copy operation)
                                //WorkoutDayGetOperation operation = new WorkoutDayGetOperation();
                                //operation.UserId = User.Id;
                                //operation.Operation = GetOperation.Current;
                                //operation.WorkoutDateTime = day.TrainingDate;
                                //day = ServiceManager.GetTrainingDay(operation);
                            }

                            day.ChangeDate(selectedDate);
                            var result1 = ServiceManager.SaveTrainingDay(day);
                            if (isCut)
                            {
                                cache.Remove(originalDay.TrainingDate);
                            }
                            if (result1.TrainingDay != null)
                            {
                                day = result1.TrainingDay;
                                cache.Add(day);
                            }

                            //ServiceManager.SaveTrainingDay(day);
                            //fillImplementation(day.TrainingDate, User, null);
                            //this.Fill(User, day.TrainingDate);
                        }
                        catch (OldDataException ex)
                        {
                            UIHelper.Invoke(() => ExceptionHandler.Default.Process(ex, EnumLocalizer.Default.GetStringsString("ErrorOldTrainingDay"), ErrorWindow.MessageBox), Dispatcher);
                        }
                        catch (Exception ex)
                        {
                            UIHelper.Invoke(() => ExceptionHandler.Default.Process(ex, EnumLocalizer.Default.GetStringsString("ErrorMoveTrainingDay"), ErrorWindow.EMailReport), Dispatcher);
                        }
                        finally
                        {
                            dayInfo.IsProcessing = false;
                        }
                    });
                }
                else
                {
                    BAMessageBox.ShowError(EnumLocalizer.Default.GetStringsString("ErrorCannotPaste"));
                }
            }
        }
コード例 #48
0
 public GyroServiceProvider(ServiceManager m) : base(m)
 {
     Input.gyro.enabled = true;
     Calibrate();
 }
 public ExcelConverter(ServiceManager serviceManager)
 {
     _serviceManager = serviceManager;
 }
コード例 #50
0
 public override void Detach(ITextView textView)
 {
     ServiceManager.RemoveService <RCompletionController>(TextView);
     base.Detach(textView);
 }
コード例 #51
0
        public async Task <DialogTurnResult> ShowEventsSummary(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var tokenResponse = sc.Result as TokenResponse;

                var state = await Accessor.GetAsync(sc.Context);

                if (state.SummaryEvents == null)
                {
                    // this will lead to error when test
                    if (string.IsNullOrEmpty(state.APIToken))
                    {
                        state.Clear();
                        return(await sc.EndDialogAsync(true));
                    }

                    var calendarService = ServiceManager.InitCalendarService(state.APIToken, state.EventSource);

                    var searchDate = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, state.GetUserTimeZone());

                    if (state.StartDate.Any())
                    {
                        searchDate = state.StartDate.Last();
                    }

                    var results = await GetEventsByTime(new List <DateTime>() { searchDate }, state.StartTime, state.EndDate, state.EndTime, state.GetUserTimeZone(), calendarService);

                    var  searchedEvents     = new List <EventModel>();
                    bool searchTodayMeeting = state.StartDate.Any() &&
                                              !state.StartTime.Any() &&
                                              !state.EndDate.Any() &&
                                              !state.EndTime.Any() &&
                                              EventModel.IsSameDate(searchDate, TimeConverter.ConvertUtcToUserTime(DateTime.UtcNow, state.GetUserTimeZone()));
                    foreach (var item in results)
                    {
                        if (!searchTodayMeeting || item.StartTime >= DateTime.UtcNow)
                        {
                            searchedEvents.Add(item);
                        }
                    }

                    if (searchedEvents.Count == 0)
                    {
                        await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(SummaryResponses.ShowNoMeetingMessage));

                        state.Clear();
                        return(await sc.EndDialogAsync(true));
                    }
                    else
                    {
                        var responseParams = new StringDictionary()
                        {
                            { "Count", searchedEvents.Count.ToString() },
                            { "EventName1", searchedEvents[0].Title },
                            { "DateTime", state.StartDateString ?? CalendarCommonStrings.Today },
                            { "EventTime1", SpeakHelper.ToSpeechMeetingTime(TimeConverter.ConvertUtcToUserTime(searchedEvents[0].StartTime, state.GetUserTimeZone()), searchedEvents[0].IsAllDay == true) },
                            { "Participants1", DisplayHelper.ToDisplayParticipantsStringSummary(searchedEvents[0].Attendees) }
                        };

                        if (searchedEvents.Count == 1)
                        {
                            await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(SummaryResponses.ShowOneMeetingSummaryMessage, ResponseBuilder, responseParams));
                        }
                        else
                        {
                            responseParams.Add("EventName2", searchedEvents[searchedEvents.Count - 1].Title);
                            responseParams.Add("EventTime2", SpeakHelper.ToSpeechMeetingTime(TimeConverter.ConvertUtcToUserTime(searchedEvents[searchedEvents.Count - 1].StartTime, state.GetUserTimeZone()), searchedEvents[searchedEvents.Count - 1].IsAllDay == true));
                            responseParams.Add("Participants2", DisplayHelper.ToDisplayParticipantsStringSummary(searchedEvents[searchedEvents.Count - 1].Attendees));

                            await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(SummaryResponses.ShowMultipleMeetingSummaryMessage, ResponseBuilder, responseParams));
                        }
                    }

                    await ShowMeetingList(sc, searchedEvents.GetRange(0, Math.Min(state.PageSize, searchedEvents.Count)), false);

                    state.SummaryEvents = searchedEvents;
                }
                else
                {
                    await ShowMeetingList(sc, state.SummaryEvents.GetRange(state.ShowEventIndex *state.PageSize, Math.Min(state.PageSize, state.SummaryEvents.Count - (state.ShowEventIndex *state.PageSize))), false);
                }

                return(await sc.NextAsync());
            }
            catch (SkillException ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
コード例 #52
0
ファイル: Boot.cs プロジェクト: uxmal/MOSA-Project
        /// <summary>
        /// Main
        /// </summary>
        public static void Main()
        {
            Kernel.x86.Kernel.Setup();

            Console = ConsoleManager.Controller.Boot;

            Console.Clear();
            Console.Goto(0, 0);
            Console.ScrollRow       = 23;
            Console.Color           = ScreenColor.White;
            Console.BackgroundColor = ScreenColor.Green;

            Debug = ConsoleManager.Controller.Boot;

            Console.Write("                   MOSA OS Version 1.5 - Compiler Version 1.5");
            FillLine();
            Console.Color           = ScreenColor.White;
            Console.BackgroundColor = ScreenColor.Black;

            Console.WriteLine("> Initializing services...");

            // Create Service manager and basic services
            var serviceManager = new ServiceManager();

            var deviceService = new DeviceService();

            var diskDeviceService    = new DiskDeviceService();
            var partitionService     = new PartitionService();
            var pciControllerService = new PCIControllerService();
            var pciDeviceService     = new PCIDeviceService();

            serviceManager.AddService(deviceService);
            serviceManager.AddService(diskDeviceService);
            serviceManager.AddService(partitionService);
            serviceManager.AddService(pciControllerService);
            serviceManager.AddService(pciDeviceService);

            Console.WriteLine("> Initializing hardware abstraction layer...");

            // Set device driver system with the hardware HAL
            var hardware = new HAL.Hardware();

            DeviceSystem.Setup.Initialize(hardware, deviceService.ProcessInterrupt);

            Console.WriteLine("> Registering device drivers...");
            deviceService.RegisterDeviceDriver(DeviceDriver.Setup.GetDeviceDriverRegistryEntries());

            Console.WriteLine("> Starting devices...");

            deviceService.Initialize(new X86System(), null);

            Console.Write("> Probing for ISA devices...");
            var isaDevices = deviceService.GetChildrenOf(deviceService.GetFirstDevice <ISABus>());

            Console.WriteLine("[Completed: " + isaDevices.Count.ToString() + " found]");

            foreach (var device in isaDevices)
            {
                Console.Write("  ");
                Bullet(ScreenColor.Yellow);
                Console.Write(" ");
                InBrackets(device.Name, ScreenColor.White, ScreenColor.Green);
                Console.WriteLine();
            }

            Console.Write("> Probing for PCI devices...");
            var devices = deviceService.GetDevices <PCIDevice>();

            Console.WriteLine("[Completed: " + devices.Count.ToString() + " found]");

            foreach (var device in devices)
            {
                Console.Write("  ");
                Bullet(ScreenColor.Yellow);
                Console.Write(" ");

                var pciDevice = device.DeviceDriver as PCIDevice;
                InBrackets(device.Name + ": " + pciDevice.VendorID.ToString("x") + ":" + pciDevice.DeviceID.ToString("x") + " " + pciDevice.SubSystemID.ToString("x") + ":" + pciDevice.SubSystemVendorID.ToString("x") + " (" + pciDevice.Function.ToString("x") + ":" + pciDevice.ClassCode.ToString("x") + ":" + pciDevice.SubClassCode.ToString("x") + ":" + pciDevice.ProgIF.ToString("x") + ":" + pciDevice.RevisionID.ToString("x") + ")", ScreenColor.White, ScreenColor.Green);

                var children = deviceService.GetChildrenOf(device);

                if (children.Count != 0)
                {
                    var child = children[0];

                    Console.WriteLine();
                    Console.Write("    ");

                    var pciDevice2 = child.DeviceDriver as PCIDevice;
                    InBrackets(child.Name, ScreenColor.White, ScreenColor.Green);
                }

                Console.WriteLine();
            }

            Console.Write("> Probing for disk controllers...");
            var diskcontrollers = deviceService.GetDevices <IDiskControllerDevice>();

            Console.WriteLine("[Completed: " + diskcontrollers.Count.ToString() + " found]");

            foreach (var device in diskcontrollers)
            {
                Console.Write("  ");
                Bullet(ScreenColor.Yellow);
                Console.Write(" ");
                InBrackets(device.Name, ScreenColor.White, ScreenColor.Green);
                Console.WriteLine();
            }

            Console.Write("> Probing for disks...");
            var disks = deviceService.GetDevices <IDiskDevice>();

            Console.WriteLine("[Completed: " + disks.Count.ToString() + " found]");

            foreach (var disk in disks)
            {
                Console.Write("  ");
                Bullet(ScreenColor.Yellow);
                Console.Write(" ");
                InBrackets(disk.Name, ScreenColor.White, ScreenColor.Green);
                Console.Write(" " + (disk.DeviceDriver as IDiskDevice).TotalBlocks.ToString() + " blocks");
                Console.WriteLine();
            }

            partitionService.CreatePartitionDevices();

            Console.Write("> Finding partitions...");
            var partitions = deviceService.GetDevices <IPartitionDevice>();

            Console.WriteLine("[Completed: " + partitions.Count.ToString() + " found]");

            //foreach (var partition in partitions)
            //{
            //	Console.Write("  ");
            //	Bullet(ScreenColor.Yellow);
            //	Console.Write(" ");
            //	InBrackets(partition.Name, ScreenColor.White, ScreenColor.Green);
            //	Console.Write(" " + (partition.DeviceDriver as IPartitionDevice).BlockCount.ToString() + " blocks");
            //	Console.WriteLine();
            //}

            Console.Write("> Finding file systems...");

            foreach (var partition in partitions)
            {
                var fat = new FatFileSystem(partition.DeviceDriver as IPartitionDevice);

                if (fat.IsValid)
                {
                    Console.WriteLine("Found a FAT file system!");

                    const string filename = "TEST.TXT";

                    var location = fat.FindEntry(filename);

                    if (location.IsValid)
                    {
                        Console.Write("Found: " + filename);

                        var fatFileStream = new FatFileStream(fat, location);

                        uint len = (uint)fatFileStream.Length;

                        Console.WriteLine(" - Length: " + len.ToString());

                        Console.Write("Reading File: ");

                        for (; ;)
                        {
                            int i = fatFileStream.ReadByte();

                            if (i < 0)
                            {
                                break;
                            }

                            Console.Write((char)i);
                        }

                        Console.WriteLine();
                    }
                }
            }

            // Get StandardKeyboard
            var standardKeyboards = deviceService.GetDevices("StandardKeyboard");

            if (standardKeyboards.Count == 0)
            {
                Console.WriteLine("No Keyboard!");
                ForeverLoop();
            }

            var standardKeyboard = standardKeyboards[0].DeviceDriver as IKeyboardDevice;

            Debug = ConsoleManager.Controller.Debug;

            // setup keymap
            var keymap = new US();

            // setup keyboard (state machine)
            var keyboard = new DeviceSystem.Keyboard(standardKeyboard, keymap);

            // setup app manager
            var manager = new AppManager(Console, keyboard, serviceManager);

            IDT.SetInterruptHandler(manager.ProcessInterrupt);

            Logger.Log("<SELFTEST:PASSED>");

            manager.Start();
        }
コード例 #53
0
ファイル: MucService.cs プロジェクト: xjsaber/CommunityServer
 public void RemoveRoom(MucRoom room)
 {
     ServiceManager.UnregisterService(room.Jid);
     MucStorage.RemoveMuc(room.Jid);
 }
コード例 #54
0
 public EndpointHostConfig(string serviceName, ServiceManager serviceManager)
     : this()
 {
     this.ServiceName    = serviceName;
     this.ServiceManager = serviceManager;
 }
コード例 #55
0
        /// <summary>
        /// Look up points of interest, render cards, and ask user which to route to.
        /// </summary>
        /// <param name="sc">Step Context.</param>
        /// <param name="cancellationToken">Cancellation Token.</param>
        /// <returns>Dialog Turn Result.</returns>
        protected async Task <DialogTurnResult> GetPointOfInterestLocations(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                var service            = ServiceManager.InitMapsService(Settings, sc.Context.Activity.Locale);
                var addressMapsService = ServiceManager.InitAddressMapsService(Settings, sc.Context.Activity.Locale);

                var pointOfInterestList = new List <PointOfInterestModel>();
                var cards = new List <Card>();

                if (string.IsNullOrEmpty(state.Keyword) && string.IsNullOrEmpty(state.Address))
                {
                    // No entities identified, find nearby locations
                    pointOfInterestList = await service.GetNearbyPointOfInterestListAsync(state.CurrentCoordinates.Latitude, state.CurrentCoordinates.Longitude);

                    cards = await GetPointOfInterestLocationCards(sc, pointOfInterestList);
                }
                else if (!string.IsNullOrEmpty(state.Keyword) && !string.IsNullOrEmpty(state.Address))
                {
                    // Get first POI matched with address, if there are multiple this could be expanded to confirm which address to use
                    var pointOfInterestAddressList = await addressMapsService.GetPointOfInterestListByAddressAsync(state.CurrentCoordinates.Latitude, state.CurrentCoordinates.Longitude, state.Address);

                    if (pointOfInterestAddressList.Any())
                    {
                        var pointOfInterest = pointOfInterestAddressList[0];
                        pointOfInterestList = await service.GetPointOfInterestListByQueryAsync(pointOfInterest.Geolocation.Latitude, pointOfInterest.Geolocation.Longitude, state.Keyword);

                        cards = await GetPointOfInterestLocationCards(sc, pointOfInterestList);
                    }
                    else
                    {
                        // No POIs found from address - search near current coordinates
                        pointOfInterestList = await service.GetPointOfInterestListByQueryAsync(state.CurrentCoordinates.Latitude, state.CurrentCoordinates.Longitude, state.Keyword);

                        cards = await GetPointOfInterestLocationCards(sc, pointOfInterestList);
                    }
                }
                else if (!string.IsNullOrEmpty(state.Keyword))
                {
                    // Fuzzy query search with keyword
                    pointOfInterestList = await service.GetPointOfInterestListByQueryAsync(state.CurrentCoordinates.Latitude, state.CurrentCoordinates.Longitude, state.Keyword);

                    cards = await GetPointOfInterestLocationCards(sc, pointOfInterestList);
                }
                else if (!string.IsNullOrEmpty(state.Address))
                {
                    // Fuzzy query search with address
                    pointOfInterestList = await service.GetPointOfInterestListByAddressAsync(state.CurrentCoordinates.Latitude, state.CurrentCoordinates.Longitude, state.Address);

                    cards = await GetPointOfInterestLocationCards(sc, pointOfInterestList);
                }

                if (cards.Count() == 0)
                {
                    var replyMessage = ResponseManager.GetResponse(POISharedResponses.NoLocationsFound);
                    await sc.Context.SendActivityAsync(replyMessage);
                }
                else if (cards.Count == 1)
                {
                    return(await sc.PromptAsync(Actions.ConfirmPrompt, new PromptOptions { Prompt = ResponseManager.GetCardResponse(POISharedResponses.PromptToGetRoute, cards) }));
                }
                else
                {
                    var options = GetPointOfInterestPrompt(POISharedResponses.MultipleLocationsFound, pointOfInterestList, cards);

                    return(await sc.PromptAsync(Actions.SelectPointOfInterestPrompt, options));
                }

                state.ClearLuisResults();

                return(await sc.EndDialogAsync());
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
コード例 #56
0
        protected override string ProcessItem(string file_path)
        {
            if (!DatabaseImportManager.IsWhiteListedFile(file_path))
            {
                return(null);
            }

            // Hack to ignore Podcast files
            if (file_path.Contains("Podcasts"))
            {
                return(null);
            }

            //Hyena.Log.DebugFormat ("Rescanning item {0}", file_path);
            try {
                SafeUri uri = new SafeUri(file_path);

                using (var reader = ServiceManager.DbConnection.Query(fetch_command, psource.DbId, uri.AbsoluteUri)) {
                    if (reader.Read())
                    {
                        //Hyena.Log.DebugFormat ("Found it in the db!");
                        DatabaseTrackInfo track = DatabaseTrackInfo.Provider.Load(reader);

                        MergeIfModified(track);

                        // Either way, update the LastSyncStamp
                        track.LastSyncedStamp = DateTime.Now;
                        track.Save(false);
                        status = String.Format("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle);
                    }
                    else
                    {
                        // This URI is not in the database - try to find it based on MetadataHash in case it was simply moved
                        DatabaseTrackInfo track = new DatabaseTrackInfo();
                        Banshee.Streaming.StreamTagger.TrackInfoMerge(track, uri);

                        using (var similar_reader = ServiceManager.DbConnection.Query(
                                   fetch_similar_command, psource.DbId, scan_started, track.MetadataHash)) {
                            DatabaseTrackInfo similar_track = null;
                            while (similar_reader.Read())
                            {
                                similar_track = DatabaseTrackInfo.Provider.Load(similar_reader);
                                if (!Banshee.IO.File.Exists(similar_track.Uri))
                                {
                                    //Hyena.Log.DebugFormat ("Apparently {0} was moved to {1}", similar_track.Uri, file_path);
                                    similar_track.Uri = uri;
                                    MergeIfModified(similar_track);
                                    similar_track.LastSyncedStamp = DateTime.Now;
                                    similar_track.Save(false);
                                    status = String.Format("{0} - {1}", similar_track.DisplayArtistName, similar_track.DisplayTrackTitle);
                                    break;
                                }
                                similar_track = null;
                            }

                            // If we still couldn't find it, try to import it
                            if (similar_track == null)
                            {
                                //Hyena.Log.DebugFormat ("Couldn't find it, so queueing to import it");
                                status = System.IO.Path.GetFileNameWithoutExtension(file_path);
                                ServiceManager.Get <Banshee.Library.LibraryImportManager> ().ImportTrack(file_path);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Hyena.Log.Exception(e);
            }
            return(null);
        }
コード例 #57
0
    protected void Page_Load(object sender, EventArgs e)
    {
        #region 接收参数

        // TaskID
        bool bIsValid = PageCommon.ValidateQueryString(this, "TaskID", QueryStringType.ID);
        if (bIsValid == false)
        {
            this.Response.Write("{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"Missing required query string.\"}");
            return;
        }
        string sTaskID = this.Request.QueryString["TaskID"].ToString();
        int    iTaskID = Convert.ToInt32(sTaskID);

        // LoanID
        bIsValid = PageCommon.ValidateQueryString(this, "LoanID", QueryStringType.ID);
        if (bIsValid == false)
        {
            this.Response.Write("{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"Missing required query string.\"}");
            return;
        }
        string sLoanID = this.Request.QueryString["LoanID"].ToString();
        int    iLoanID = Convert.ToInt32(sLoanID);

        #endregion

        // json示例
        // {"ExecResult":"Success","ErrorMsg":"","EmailTemplateID":"1", "LoanClosed":"Yes"}
        // {"ExecResult":"Failed","ErrorMsg":"执行数据库脚本时发生错误。"}

        string sErrorMsg        = string.Empty;
        string sEmailTemplateID = string.Empty;
        bool   bIsSuccess       = false;
        string LoanClosed       = "No";
        var    result           = "";
        try
        {
            #region complete task

            int iEmailTemplateId = 0;
            bIsSuccess = LPWeb.DAL.WorkflowManager.CompleteTask(iTaskID, this.CurrUser.iUserID, ref iEmailTemplateId);

            if (bIsSuccess == false)
            {
                sErrorMsg = "Failed to invoke WorkflowManager.CompleteTask.";
                return;
            }

            if (iEmailTemplateId != 0)
            {
                sEmailTemplateID = iEmailTemplateId.ToString();
            }

            #endregion

            #region update point file stage

            int iLoanStageID = 0;

            #region get loan task info

            LoanTasks LoanTaskManager = new LoanTasks();
            DataTable LoanTaskInfo    = LoanTaskManager.GetLoanTaskInfo(iTaskID);
            if (LoanTaskInfo.Rows.Count == 0)
            {
                bIsSuccess = false;
                sErrorMsg  = "Invalid task id.";
                return;
            }
            string sLoanStageID = LoanTaskInfo.Rows[0]["LoanStageId"].ToString();
            if (sLoanStageID == string.Empty)
            {
                bIsSuccess = false;
                sErrorMsg  = "Invalid loan stage id.";
                return;
            }
            iLoanStageID = Convert.ToInt32(sLoanStageID);

            #endregion
            bIsSuccess = true;
            if (!WorkflowManager.StageCompleted(iLoanStageID))
            {
                sErrorMsg = "Completed task successfully.";
                return;
            }

            #region invoke PointManager.UpdateStage()

            //add by  gdc 20111212  Bug #1306
            LPWeb.BLL.PointFiles pfile = new PointFiles();
            var model = pfile.GetModel(iLoanID);
            if (model != null && !string.IsNullOrEmpty(model.Name.Trim()))
            {
                #region check Point File Status first
                ServiceManager sm = new ServiceManager();
                using (LP2ServiceClient service = sm.StartServiceClient())
                {
                    CheckPointFileStatusReq checkFileReq = new CheckPointFileStatusReq();
                    checkFileReq.hdr               = new ReqHdr();
                    checkFileReq.hdr.UserId        = CurrUser.iUserID;
                    checkFileReq.hdr.SecurityToken = "SecurityToken";
                    checkFileReq.FileId            = iLoanID;
                    CheckPointFileStatusResp checkFileResp = service.CheckPointFileStatus(checkFileReq);
                    if (checkFileResp == null || checkFileResp.hdr == null || !checkFileResp.hdr.Successful)
                    {
                        sErrorMsg = "Unable to get Point file status from Point Manager.";
                        WorkflowManager.UnCompleteTask(iTaskID, CurrUser.iUserID);
                        bIsSuccess = false;
                        return;
                    }
                    if (checkFileResp.FileLocked)
                    {
                        sErrorMsg = checkFileResp.hdr.StatusInfo;
                        WorkflowManager.UnCompleteTask(iTaskID, CurrUser.iUserID);
                        bIsSuccess = false;
                        return;
                    }
                }
                #endregion
                #region UPdatePointFileStage  WCF
                string sError = LoanTaskCommon.UpdatePointFileStage(iLoanID, this.CurrUser.iUserID, iLoanStageID);

                // the last one, sleep 1 second
                System.Threading.Thread.Sleep(1000);

                if (sError == string.Empty) // success
                {
                    sErrorMsg = "Completed task successfully.";
                }
                else
                {
                    sErrorMsg = "Completed task successfully but failed to update stage date in Point.";
                    //sErrorMsg = "Failed to update point file stage: " + sError.Replace("\"", "\\\"");
                }
                #endregion
            }
            if (WorkflowManager.IsLoanClosed(iLoanID))
            {
                LoanClosed = "Yes";
            }
            return;

            #endregion
        }
        catch (System.ServiceModel.EndpointNotFoundException ee)
        {
            sErrorMsg = "Completed task successfully but failed to update stage date in Point.";
            return;
        }
        catch (Exception ex)
        {
            if (bIsSuccess)
            {
                sErrorMsg = "Completed task successfully but encountered an error:" + ex.Message;
            }
            else
            {
                sErrorMsg = "Failed to complete task, reason:" + ex.Message;
            }
            //sErrorMsg = "Exception happened when invoke WorkflowManager.CompleteTask: " + ex.ToString().Replace("\"", "\\\"");
            bIsSuccess = false;
            return;
        }
        finally
        {
            if (bIsSuccess)
            {
                result = "{\"ExecResult\":\"Success\",\"ErrorMsg\":\"" + sErrorMsg + "\",\"EmailTemplateID\":\"" + sEmailTemplateID + "\",\"TaskID\":\"" + sTaskID + "\",\"LoanClosed\":\"" + LoanClosed + "\"}";
            }
            //result = "{\"ExecResult\":\"Success\",\"ErrorMsg\":\"\",\"EmailTemplateID\":\"" + sEmailTemplateID + "\",\"LoanClosed\":\"" + LoanClosed + "\"}";
            else
            {
                result = "{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"" + sErrorMsg + "\"}";
            }
            this.Response.Write(result);
        }

        #endregion
    }
コード例 #58
0
        public FakeSkill(SkillConfigurationBase services, ConversationState conversationState, UserState userState, IBotTelemetryClient telemetryClient, bool skillMode = false, ServiceManager serviceManager = null)
        {
            _skillMode         = skillMode;
            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _serviceManager    = serviceManager ?? new ServiceManager();

            _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _telemetryClient, _serviceManager, _skillMode));
        }
コード例 #59
0
        public async Task <DialogTurnResult> ShowNextEvent(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                var askParameter = new AskParameterModel(state.AskParameterContent);
                if (string.IsNullOrEmpty(state.APIToken))
                {
                    return(await sc.EndDialogAsync(true));
                }

                var calendarService = ServiceManager.InitCalendarService(state.APIToken, state.EventSource);

                var eventList = await calendarService.GetUpcomingEvents();

                var nextEventList = new List <EventModel>();
                foreach (var item in eventList)
                {
                    if (item.IsCancelled != true && (nextEventList.Count == 0 || nextEventList[0].StartTime == item.StartTime))
                    {
                        nextEventList.Add(item);
                    }
                }

                if (nextEventList.Count == 0)
                {
                    await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowNoMeetingMessage));
                }
                else
                {
                    if (nextEventList.Count == 1)
                    {
                        // if user asked for specific details
                        if (askParameter.NeedDetail)
                        {
                            var tokens = new StringDictionary()
                            {
                                { "EventName", nextEventList[0].Title },
                                { "EventStartTime", TimeConverter.ConvertUtcToUserTime(nextEventList[0].StartTime, state.GetUserTimeZone()).ToString("h:mm tt") },
                                { "EventEndTime", TimeConverter.ConvertUtcToUserTime(nextEventList[0].EndTime, state.GetUserTimeZone()).ToString("h:mm tt") },
                                { "EventDuration", nextEventList[0].ToDurationString() },
                                { "EventLocation", nextEventList[0].Location },
                            };

                            await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.BeforeShowEventDetails, tokens));

                            if (askParameter.NeedTime)
                            {
                                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ReadTime, tokens));
                            }

                            if (askParameter.NeedDuration)
                            {
                                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ReadDuration, tokens));
                            }

                            if (askParameter.NeedLocation)
                            {
                                // for some event there might be no localtion.
                                if (string.IsNullOrEmpty(tokens["EventLocation"]))
                                {
                                    await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ReadNoLocation));
                                }
                                else
                                {
                                    await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ReadLocation, tokens));
                                }
                            }
                        }

                        var speakParams = new StringDictionary()
                        {
                            { "EventName", nextEventList[0].Title },
                            { "PeopleCount", nextEventList[0].Attendees.Count.ToString() },
                        };

                        speakParams.Add("EventTime", SpeakHelper.ToSpeechMeetingDateTime(TimeConverter.ConvertUtcToUserTime(nextEventList[0].StartTime, state.GetUserTimeZone()), nextEventList[0].IsAllDay == true));

                        if (string.IsNullOrEmpty(nextEventList[0].Location))
                        {
                            await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowNextMeetingNoLocationMessage, speakParams));
                        }
                        else
                        {
                            speakParams.Add("Location", nextEventList[0].Location);
                            await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowNextMeetingMessage, speakParams));
                        }
                    }
                    else
                    {
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowMultipleNextMeetingMessage));
                    }

                    await ShowMeetingList(sc, nextEventList, true);
                }

                state.Clear();
                return(await sc.EndDialogAsync(true));
            }
            catch (SkillException ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
コード例 #60
0
        public async Task <DialogTurnResult> ShowEventsSummary(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var tokenResponse = sc.Result as TokenResponse;

                var state = await Accessor.GetAsync(sc.Context);

                var options = sc.Options as ShowMeetingsDialogOptions;
                if (state.SummaryEvents == null)
                {
                    // this will lead to error when test
                    if (string.IsNullOrEmpty(state.APIToken))
                    {
                        state.Clear();
                        return(await sc.EndDialogAsync(true));
                    }

                    var calendarService = ServiceManager.InitCalendarService(state.APIToken, state.EventSource);

                    var searchDate = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, state.GetUserTimeZone());

                    if (state.StartDate.Any())
                    {
                        searchDate = state.StartDate.Last();
                    }

                    var results = await GetEventsByTime(new List <DateTime>() { searchDate }, state.StartTime, state.EndDate, state.EndTime, state.GetUserTimeZone(), calendarService);

                    var  searchedEvents     = new List <EventModel>();
                    bool searchTodayMeeting = SearchesTodayMeeting(state);
                    foreach (var item in results)
                    {
                        if (!searchTodayMeeting || item.StartTime >= DateTime.UtcNow)
                        {
                            searchedEvents.Add(item);
                        }
                    }

                    if (searchedEvents.Count == 0)
                    {
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowNoMeetingMessage));

                        state.Clear();
                        return(await sc.EndDialogAsync(true));
                    }
                    else
                    {
                        if (options != null && options.Reason == ShowMeetingReason.ShowOverviewAgain)
                        {
                            var responseParams = new StringDictionary()
                            {
                                { "Count", searchedEvents.Count.ToString() },
                                { "DateTime", state.StartDateString ?? CalendarCommonStrings.Today }
                            };
                            if (searchedEvents.Count == 1)
                            {
                                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowOneMeetingSummaryAgainMessage, responseParams));
                            }
                            else
                            {
                                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowMeetingSummaryAgainMessage, responseParams));
                            }
                        }
                        else
                        {
                            var responseParams = new StringDictionary()
                            {
                                { "Count", searchedEvents.Count.ToString() },
                                { "EventName1", searchedEvents[0].Title },
                                { "DateTime", state.StartDateString ?? CalendarCommonStrings.Today },
                                { "EventTime1", SpeakHelper.ToSpeechMeetingTime(TimeConverter.ConvertUtcToUserTime(searchedEvents[0].StartTime, state.GetUserTimeZone()), searchedEvents[0].IsAllDay == true) },
                                { "Participants1", DisplayHelper.ToDisplayParticipantsStringSummary(searchedEvents[0].Attendees) }
                            };

                            if (searchedEvents.Count == 1)
                            {
                                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowOneMeetingSummaryMessage, responseParams));
                            }
                            else
                            {
                                responseParams.Add("EventName2", searchedEvents[searchedEvents.Count - 1].Title);
                                responseParams.Add("EventTime2", SpeakHelper.ToSpeechMeetingTime(TimeConverter.ConvertUtcToUserTime(searchedEvents[searchedEvents.Count - 1].StartTime, state.GetUserTimeZone()), searchedEvents[searchedEvents.Count - 1].IsAllDay == true));
                                responseParams.Add("Participants2", DisplayHelper.ToDisplayParticipantsStringSummary(searchedEvents[searchedEvents.Count - 1].Attendees));

                                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowMultipleMeetingSummaryMessage, responseParams));
                            }
                        }
                    }

                    await ShowMeetingList(sc, GetCurrentPageMeetings(searchedEvents, state), !searchTodayMeeting);

                    state.SummaryEvents = searchedEvents;
                    if (state.SummaryEvents.Count == 1)
                    {
                        return(await sc.PromptAsync(Actions.Prompt, new PromptOptions()));
                    }
                }
                else
                {
                    var currentPageMeetings = GetCurrentPageMeetings(state.SummaryEvents, state);
                    if (options != null && options.Reason == ShowMeetingReason.ShowFilteredMeetings)
                    {
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowMultipleFilteredMeetings, new StringDictionary()
                        {
                            { "Count", state.SummaryEvents.Count.ToString() }
                        }));
                    }
                    else
                    {
                        var responseParams = new StringDictionary()
                        {
                            { "Count", state.SummaryEvents.Count.ToString() },
                            { "EventName1", currentPageMeetings[0].Title },
                            { "DateTime", state.StartDateString ?? CalendarCommonStrings.Today },
                            { "EventTime1", SpeakHelper.ToSpeechMeetingTime(TimeConverter.ConvertUtcToUserTime(currentPageMeetings[0].StartTime, state.GetUserTimeZone()), currentPageMeetings[0].IsAllDay == true) },
                            { "Participants1", DisplayHelper.ToDisplayParticipantsStringSummary(currentPageMeetings[0].Attendees) }
                        };
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.ShowMeetingSummaryNotFirstPageMessage, responseParams));
                    }

                    await ShowMeetingList(sc, GetCurrentPageMeetings(state.SummaryEvents, state), !SearchesTodayMeeting(state));
                }

                return(await sc.PromptAsync(Actions.Prompt, new PromptOptions { Prompt = ResponseManager.GetResponse(SummaryResponses.ReadOutMorePrompt) }));
            }
            catch (SkillException ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }