Пример #1
0
 public Sender(
     NetworkService<GroupCommunicationMessage> networkService, 
     IIdentifierFactory idFactory)
 {
     _networkService = networkService;
     _idFactory = idFactory;
 }
        static internal int checkDelegate(IntPtr l,int p,out NetworkService.PacketHandlerDelegate ua) {
            int op = extractFunction(l,p);
			if(LuaDLL.lua_isnil(l,p)) {
				ua=null;
				return op;
			}
            else if (LuaDLL.lua_isuserdata(l, p)==1)
            {
                ua = (NetworkService.PacketHandlerDelegate)checkObj(l, p);
                return op;
            }
            LuaDelegate ld;
            checkType(l, -1, out ld);
            if(ld.d!=null)
            {
                ua = (NetworkService.PacketHandlerDelegate)ld.d;
                return op;
            }
			LuaDLL.lua_pop(l,1);
			
			l = LuaState.get(l).L;
            ua = (Packet a1) =>
            {
                int error = pushTry(l);

				pushValue(l,a1);
				ld.pcall(1, error);
				LuaDLL.lua_settop(l, error-1);
			};
			ld.d=ua;
			return op;
		}
Пример #3
0
    private IEnumerator StartupManagers()
    {
        NetworkService network = new NetworkService();

        foreach (var item in _startSequence)
        {
            if(item == null) continue;
            item.Startup(network);
        }

        yield return null;

        int numModules = _startSequence.Count;
        int numReady = 0;

        while (numReady < numModules)
        {
            int lastReady = numReady;
            numReady = 0;

            foreach (var item in _startSequence)
            {
                if(item == null) continue;
                if(item.status == ManagerStatus.Started) numReady++;
            }

            if(numReady > lastReady)
                Debug.LogFormat("<size=20><color=red><b><i>{0} {1}</i></b></color></size>", numReady, numModules);

            yield return null;
        }

        Debug.LogFormat("<size=20><color=red><b><i>{0}</i></b></color></size>", "all managers started up");
    }
Пример #4
0
    private IEnumerator StartupManagers()
    {
        NetworkService network = new NetworkService();

        foreach (IGameManager manager in _startSequence) {
            manager.Startup(network);
        }

        yield return null;

        int numModules = _startSequence.Count;
        int numReady = 0;

        while (numReady < numModules) {
            int lastReady = numReady;
            numReady = 0;

            foreach (IGameManager manager in _startSequence) {
                if (manager.status == ManagerStatus.Started) {
                    numReady++;
                }
            }

            if (numReady > lastReady) {
                Debug.Log("Progress: " + numReady + "/" + numModules);
                Messenger<int, int>.Broadcast(StartupEvent.MANAGERS_PROGRESS, numReady, numModules);
            }

            yield return null;
        }

        Debug.Log("All managers started up");
        Messenger.Broadcast(StartupEvent.MANAGERS_STARTED);
    }
Пример #5
0
    private IEnumerator StartupManagers()
    {
        NetworkService network = new NetworkService();

        foreach (IGameManager manager in _startSequence) {
            manager.Startup(network);
        }

        yield return null;

        int numModules = _startSequence.Count;
        int numReady = 0;

        while (numReady < numModules) {
            int lastReady = numReady;
            numReady = 0;

            foreach (IGameManager manager in _startSequence) {
                if (manager.status == ManagerStatus.Started) {
                    numReady++;
                }
            }

            if (numReady > lastReady)
                Debug.Log("Progress: " + numReady + "/" + numModules);

            yield return null;
        }

        Debug.Log("All managers started up");
    }
Пример #6
0
        protected SessionViewModel(NetworkService network)
        {
            Subscriptions = new ObservableCollection<SubscriptionViewModel> ();

            User = new UserViewModel (new User());
            UserAuth = new UserService(network);
            GameService = new GameService(network);
        }
Пример #7
0
 public void Startup(NetworkService service)
 {
     if(service == null) return;
     Debug.LogFormat("<size=20><color=red><b><i>{0}</i></b></color></size>", "weather manager starting...");
     _network = service;
     StartCoroutine(_network.GetWeatherXML(OnXMLDataLoaded));
     status = ManagerStatus.Initializing;
 }
Пример #8
0
    public void Startup(NetworkService service)
    {
        Debug.Log("Images manager starting...");

        _network = service;

        // any long-running startup tasks go here, and set status to 'Initializing' until those tasks are complete
        status = ManagerStatus.Started;
    }
Пример #9
0
		public GameViewModel(NetworkService network) : base(network)
        {
            Title = "Sorteo";

            _players = new ObservableCollection<PlayerViewModel>();

			Model = new Game ();
			//History = new ObservableCollection<EventLogViewModel> ();
			Winners = new ObservableCollection<PlayerViewModel> ();
        }
Пример #10
0
    public void Startup(NetworkService service)
    {
        Debug.Log("Weather manager starting...");

        _network = service;
        //StartCoroutine(_network.GetWeatherXML(OnXMLDataLoaded));
        StartCoroutine(_network.GetWeatherJSON(OnJSONDataLoaded));

        status = ManagerStatus.Initializing;
    }
Пример #11
0
        /// <summary>
        /// Initiate the controllerModul
        /// </summary>
        private void InitiateController()
        {
            Logger.LogInfo("New Program start");
            fileService = new FileService(this);
            networkService = new NetworkService(this);
            graphicControl = new GraphicalInterfaceController(this, chatForm);

            Logger.LogInfo("Start network service.");
            networkService.Start();
        }
Пример #12
0
    public void Startup(NetworkService service)
    {
        Debug.Log("Data manager starting...");

        _network = service;

        _filename = Path.Combine(Application.persistentDataPath, "game.dat");

        // any long-running startup tasks go here, and set status to 'Initializing' until those tasks are complete
        status = ManagerStatus.Started;
    }
Пример #13
0
	static public int constructor(IntPtr l) {
		try {
			NetworkService o;
			o=new NetworkService();
			pushValue(l,true);
			pushValue(l,o);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
Пример #14
0
        public RaffleViewModel(NetworkService network)
        {
            Title = "Sorteo";
            Network = network;

            Players = new ObservableCollection<PlayerViewModel>();
            Groups = new ObservableCollection<GroupViewModel>(
                new[]
                {
                    GetLocalGroup(),
                    GetMeetupGroup()
                }
            );

            SelectedGroup = Groups.First();
        }
Пример #15
0
        public MailSendView(IWorkSpace provider, object[] arg)
            : this()
        {
            _serviceProvider = provider;

            if (arg.Length != 0)
            {
                _image = arg[0] as Image;
                _photoMode = (PhotoShotMode)arg[1];
            }
            else
            {
                throw new Exception("Отсутствует список изображений в списке параметров при активации PrintView.");
            }

            _networkService = _serviceProvider.GetService<NetworkService>();
        }
Пример #16
0
        private GroupCommClient(
            [Parameter(typeof(GroupCommConfigurationOptions.SerializedGroupConfigs))] ISet<string> groupConfigs,
            [Parameter(typeof(TaskConfigurationOptions.Identifier))] string taskId,
            NetworkService<GroupCommunicationMessage> networkService,
            AvroConfigurationSerializer configSerializer,
            IInjector injector)
        {
            _commGroups = new Dictionary<string, ICommunicationGroupClient>();
            _networkService = networkService;
            networkService.Register(new StringIdentifier(taskId));

            foreach (string serializedGroupConfig in groupConfigs)
            {
                IConfiguration groupConfig = configSerializer.FromString(serializedGroupConfig);
                IInjector groupInjector = injector.ForkInjector(groupConfig);
                ICommunicationGroupClient commGroupClient = groupInjector.GetInstance<ICommunicationGroupClient>();
                _commGroups[commGroupClient.GroupName] = commGroupClient;
            }
        }
Пример #17
0
    private IEnumerator StartupManagers()
    {
        NetworkService network = new NetworkService();

        foreach (IGameManager manager in _startSequence)
        {
            manager.Startup(network);
        }

        yield return(null);

        int numModules = _startSequence.Count;
        int numReady   = 0;

        while (numReady < numModules)
        {
            int lastReady = numReady;
            numReady = 0;

            foreach (IGameManager manager in _startSequence)
            {
                if (manager.status == ManagerStatus.Started)
                {
                    numReady++;
                }
            }

            if (numReady > lastReady)
            {
                Debug.Log("Progress: " + numReady + "/" + numModules);
                Messenger <int, int> .Broadcast(
                    StartupEvent.MANAGERS_PROGRESS, numReady, numModules);
            }
            yield return(null);
        }
        Debug.Log("All managers started up");
        Messenger.Broadcast(StartupEvent.MANAGERS_STARTED);
    }
Пример #18
0
        public async void GetTopHeadlines()
        {
            if (NetworkService.ExistsInternetConnection())
            {
                connectionState = "CONNECTED";
                //get the list of TopHeadlines
                //topHeadlines = await restServices.GetTopHeadlines();
                //gNewsAPI = await restServices.GetGNewsLocalNGHeadlines();
                newsArticles = await restServices.BindAllNewsHeadlines();

                if (newsArticles != null)
                {
                    OnPropertyChanged(nameof(NewsArticles));
                }
                //if (gNewsAPI != null)
                //{
                //    gNewsArticles = gNewsAPI.Articles;
                //    OnPropertyChanged(nameof(GNewsArticles));
                //}

                //if (topHeadlines != null)
                //{
                //    articles = topHeadlines.Articles;
                //    OnPropertyChanged(nameof(Articles));
                //}

                isrefreshing = false;
                OnPropertyChanged(nameof(IsRefreshing));
            }
            else
            {
                //internet connection does not exist
                connectionState = "DISCONNECTED";
                ConnectionBoxViewVariables("White", "Red", true, "Internet Connection Lost");
            }
            OnPropertyChanged(nameof(ConnectionState));
            OnPropertyChanged(nameof(APIResults));
        }
Пример #19
0
        public MainViewModel()
        {
            MenuItems = new List <MenuItem>()
            {
                new MenuItem()
                {
                    Command     = new RelayCommand(() => ViewModelNavigation.NavigateAsync <UserOrgsViewModel>(this)),
                    Name        = ClientResources.MainMenu_SwitchOrgs,
                    FontIconKey = "fa-users"
                },
                new MenuItem()
                {
                    Command     = new RelayCommand(() => ViewModelNavigation.NavigateAsync <ChangePasswordViewModel>(this)),
                    Name        = ClientResources.MainMenu_ChangePassword,
                    FontIconKey = "fa-key"
                },
                new MenuItem()
                {
                    Command     = new RelayCommand(() => ViewModelNavigation.NavigateAsync <InviteUserViewModel>(this)),
                    Name        = ClientResources.MainMenu_InviteUser,
                    FontIconKey = "fa-user"
                },
                new MenuItem()
                {
                    Command     = new RelayCommand(() => ViewModelNavigation.NavigateAsync <AboutViewModel>(this)),
                    Name        = "About",
                    FontIconKey = "fa-info"
                },
                new MenuItem()
                {
                    Command     = new RelayCommand(() => Logout()),
                    Name        = ClientResources.Common_Logout,
                    FontIconKey = "fa-sign-out"
                }
            };

            ShowIoTAppStudioCommand = new RelayCommand(() => NetworkService.OpenURI(new Uri("https://www.IoTAppStudio.com")));
        }
Пример #20
0
        /// <summary>
        /// Method called when a network status changed event is triggered
        /// </summary>
        /// <param name="sender">Object that sent the event</param>
        /// <param name="args">Event arguments</param>
        protected override async void OnNetworkStatusChanged(object sender, object args)
        {
            base.OnNetworkStatusChanged(sender, args);
            this.ViewModel?.ContentViewModel?.UpdateNetworkStatus();

            // If no network connection, nothing to do
            if (!NetworkService.HasInternetAccess())
            {
                return;
            }

            // Check if the user has an active and online session
            if (!await AppService.CheckActiveAndOnlineSessionAsync(true))
            {
                return;
            }

            // If user is not already logged in, resume the session
            if (!Convert.ToBoolean(SdkService.MegaSdk.isLoggedIn()))
            {
                UiService.OnUiThread(async() =>
                {
                    if (!await this.ViewModel?.FastLoginAsync())
                    {
                        return;
                    }

                    if (this.ViewModel?.ContentViewModel is CloudDriveViewModel)
                    {
                        var contentViewModel = this.ViewModel.ContentViewModel as CloudDriveViewModel;
                        if (!contentViewModel.ActiveFolderView.IsLoaded)
                        {
                            contentViewModel.LoadFolders();
                        }
                    }
                });
            }
        }
Пример #21
0
    void parseConnectionSearchMessage(string message)
    {
        try {
            NetworkMessage networkMessage = NetworkMessage.decodeMessage(message);
            string         messageType    = networkMessage.thisMessageType();
            Debug.Log("[CLIENT] got connection ping from server. " + message);
            if (messageType == typeof(DiscoveryPingMessage).FullName)
            {
                DiscoveryPingMessage dpm = (DiscoveryPingMessage)networkMessage;
                this.node       = new NetworkNode(dpm.sourceIp.ToString(), Config.serverListenPort);
                this.serverNode = new NetworkNode(dpm.sourceIp.ToString(), Config.clientListenPort);
                startListening(this.serverNode);

                // send initial connection message
                ipAddress = NetworkService.GetSelfIP();
                PlayerUpdateMessage joinMsg = new PlayerUpdateMessage(ipAddress, "join");
                this.sendMessageToServer(joinMsg);
                serverDiscoveryClient.Close();
            }
        } catch (Exception e) {
            Debug.Log(whoAmI() + e);
        }
    }
Пример #22
0
    protected override void mapBindings()
    {
        base.mapBindings();

        mediationBinder.Bind <StartButtonView>().To <StartButtonMediator>();
        mediationBinder.Bind <OptionView>().To <OptionMediator>();
        mediationBinder.Bind <OptionsPanelView>().To <OptionsPanelMediator>();

        NetworkService networkService = GameObject.FindGameObjectWithTag("NetworkHelper").GetComponent <NetworkService>();

        injectionBinder.Bind <NetworkService>().ToValue(networkService);

        OptionsManager optionsManager = GameObject.FindGameObjectWithTag("OptionsManager").GetComponent <OptionsManager>();

        injectionBinder.Bind <OptionsManager>().To(optionsManager);

        injectionBinder.Bind <SpawnOptionsSignal>().ToSingleton();
        injectionBinder.Bind <ClearOptionsSignal>().ToSingleton();

        commandBinder.Bind <StartSignal>().To <GetInitialTurnCommand>();
        commandBinder.Bind <GetChildrenSignal>().To <GetChildrenCommand>();
        commandBinder.Bind <OptionSelectedSignal>().To <SelectOptionCommand>();
    }
Пример #23
0
        static void Main(string[] args)
        {
            var service        = new NetworkService();
            var userManager    = new UserManager();
            var logicProcessor = new LogicProcessor(service, userManager);

            logicProcessor.StartLogic();

            var listenAddress = "0.0.0.0";
            var listenPort    = 23452;
            var backlog       = 100;

            service.Initialize(logicProcessor, userManager);
            service.Listen(listenAddress, listenPort, backlog);

            Console.WriteLine($"Server Initialized. Address({listenAddress}), Port({listenPort}), Backlog({backlog})");

            while (true)
            {
                // TODO :: 여기에 현재 몇명이 접속했는지 등의 정보를 Console.Title로 기록.
                System.Threading.Thread.Sleep(1000);
            }
        }
Пример #24
0
        public void updateDay()
        {
            // _day = null;
            if (this._day == null || (this._day.Date.Date.Year != DateTime.Now.Date.Year || this._day.Date.Date.DayOfYear != DateTime.Now.Date.DayOfYear))
            {
                //create day

                this._day          = new Day();
                this._day.User     = this.user;
                this._day.Date     = DateTime.Now;
                this._day.LastMeal = (int)DateTime.Now.TimeOfDay.TotalMinutes;

                DayDB ddb = new DayDB(this._day);

                ddb.save();

                var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                localSettings.Values["dayID"] = _day.DayID;

                List <Eat> eats = new List <Eat> {
                };
                eats.Add(new Eat(_day.DayID, "Breakfest"));
                eats.Add(new Eat(_day.DayID, "Lunch"));
                eats.Add(new Eat(_day.DayID, "Dinner"));

                foreach (Eat e in eats)
                {
                    EatDB edb = new EatDB(e);
                    edb.save();
                }

                this.tbDate.Text = DateTime.Now.Day.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Year.ToString();

                //Update meals from servers everyday
                NetworkService.updateMeals();
            }
        }
Пример #25
0
    private IEnumerator StartupManagers()
    {
        var network = new NetworkService();

        foreach (IGameManager manager in _startSequence)
        {
            manager.Startup(network);
        }

        yield return(null);

        var numModels = _startSequence.Count;
        var numReady  = 0;

        while (numReady < numModels)
        {
            var lastReady = numReady;
            numReady = 0;

            foreach (IGameManager manager in _startSequence)
            {
                if (manager.status == ManagerStatus.Started)
                {
                    numReady++;
                }
            }

            if (numReady > lastReady)
            {
                Debug.Log($"Progress: {numReady} / {numModels}");
            }

            yield return(null);
        }

        Debug.Log("All managers started up");
    }
Пример #26
0
    private IEnumerator StartupManagers()
    {
        NetworkService network = new NetworkService();

        foreach (IGameManager manager in _startSequence)
        {
            manager.Startup(network);
        }

        yield return(null);

        int numModules = _startSequence.Count;
        int numReady   = 0;

        while (numReady < numModules) // Пока не заработали все диспетчеры
        {
            int lastReady = numReady;
            numReady = 0;

            foreach (IGameManager manager in _startSequence)
            {
                if (manager.status == ManagerStatus.Started)
                {
                    numReady++;
                }
            }

            if (numReady > lastReady)
            {
                Debug.Log("Progress: " + numReady + "/" + numModules);
            }

            yield return(null); // Остановка на один кадр перед следующей проверкой
        }

        Debug.Log("All managers started up");
    }
Пример #27
0
        static void Main(string[] args)
        {
            PacketBufferManager.initialize(2000);
            // CNetworkService객체는 메시지의 비동기 송,수신 처리를 수행한다.
            // 메시지 송,수신은 서버, 클라이언트 모두 동일한 로직으로 처리될 수 있으므로
            // CNetworkService객체를 생성하여 Connector객체에 넘겨준다.
            var service = new NetworkService(true);

            // endpoint정보를 갖고있는 Connector생성. 만들어둔 NetworkService객체를 넣어준다.
            CConnector connector = new CConnector(service);

            // 접속 성공시 호출될 콜백 매소드 지정.
            connector.connected_callback += on_connected_gameserver;
            var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7979);

            connector.connect(endpoint);
            //System.Threading.Thread.Sleep(10);

            while (true)
            {
                Console.Write("> ");
                string line = Console.ReadLine();
                if (line == "q")
                {
                    break;
                }

                var msg = Packet.create((short)PROTOCOL.CHAT_MSG_REQ);
                msg.push(line);
                game_servers[0].send(msg);
            }

            ((CRemoteServerPeer)game_servers[0]).token.disconnect();

            //System.Threading.Thread.Sleep(1000 * 20);
            Console.ReadKey();
        }
Пример #28
0
        public static void Start()
        {
            var logger   = new Log4NetLogger();
            var sysinfo  = new SystemInfo();
            var endpoint = new IPEndPoint(NetworkService.GetAddress(), 22008);


            var server  = new WebSocketQueueServer(endpoint, sysinfo, logger);
            var manager = new ConnectionManager(server, logger, sysinfo);

            var cliFactories = new ICliSessionFactory[]
            {
                // creates cmd.exe sessions
                new CommandSessionFactory(logger),

                // creates powershell sessions
                new PowerShellFactory(logger)
            };

            server.Queue.SubscribeInstance(new CreateTerminalRequestHandler(manager, cliFactories, logger, sysinfo));
            server.Queue.SubscribeInstance(new CloseTerminalRequestHandler(manager, logger));
            server.Queue.SubscribeInstance(new InputTerminalRequestHandler(manager, logger));
            server.Queue.SubscribeInstance(new AesHandshakeRequestHandler(manager, logger));


            try
            {
                server.StartAsync();
                Console.WriteLine("Terminal Server bound to " + NetworkService.GetAddress() + ":" + 22008);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex);
                Console.ResetColor();
            }
        }
Пример #29
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (!NetworkService.IsNetworkAvailable())
            {
                UpdateGUI(false);
                return;
            }

            _nodeDetailsViewModel.Initialize(App.GlobalListener);

            if (App.AppInformation.IsStartupModeActivate)
            {
                // Needed on every UI interaction
                SdkService.MegaSdk.retryPendingConnections();

                if (!App.AppInformation.HasPinLockIntroduced && SettingsService.LoadSetting <bool>(SettingsResources.UserPinLockIsEnabled))
                {
                    NavigateService.NavigateTo(typeof(PasswordPage), NavigationParameter.Normal, this.GetType());
                    return;
                }

                App.AppInformation.IsStartupModeActivate = false;

#if WINDOWS_PHONE_81
                // Check to see if any files have been picked
                var app = Application.Current as App;
                if (app != null && app.FolderPickerContinuationArgs != null)
                {
                    FolderService.ContinueFolderOpenPicker(app.FolderPickerContinuationArgs,
                                                           new FolderViewModel(SdkService.MegaSdk, App.AppInformation, _nodeViewModel.ParentContainerType));
                }
#endif
                return;
            }
        }
Пример #30
0
        public async Task <ActionResult <IEnumerable <Network> > > Get(Cluster cluster)
        {
            if (cluster == null)
            {
                return(BadRequest());
            }
            Adapter adapter = await _context.Adapters.Where(x => x.IsOK).Include(c => c.Credentials).Include(p => p.Provider).SingleOrDefaultAsync(a => a.Id == cluster.Datacenter.Adapter.Id);

            if (adapter?.Provider == null)
            {
                return(BadRequest());
            }
            List <Network> networks = new List <Network>();

            switch (adapter.Provider.ProviderType)
            {
            case ProviderType.Ovirt:
                ServicesResponse servicesResponse = await NetworkService.GetNetworks(cluster.Id, adapter);

                if (servicesResponse.isSuccess)
                {
                    Ovirt.Networks ovirtNetworks = (Ovirt.Networks)servicesResponse.resultObject;
                    networks.AddRange(ovirtNetworks.Network.ConvertAll(x => (Network)x));
                }
                break;

            case ProviderType.VMware:
                var response = await EasyAdmin.Services.VMware.NetworkService.GetNetworksListAsync(adapter, cluster);

                if (response.isSuccess)
                {
                    return(response.resultObject);
                }
                break;
            }
            return(networks);
        }
Пример #31
0
    private IEnumerator StartupManagers()
    {
        NetworkService network = new NetworkService();

        foreach (IGameManager manager in _startSequence)
        {
            manager.StartUp(network);
        }

        yield return(null);

        int numModules = _startSequence.Count;
        int numReady   = 0;

        while (numReady < numModules)
        {
            int lastReady = numReady;
            numReady = 0;

            foreach (IGameManager manager in _startSequence)
            {
                if (manager.status == ManagerStatus.Started)
                {
                    numReady++;
                }
            }

            if (numReady > lastReady)
            {
                Debug.Log("Progress: " + numReady + "/" + numModules);
            }

            yield return(null);
        }

        Debug.Log("All managers started up");
    }
Пример #32
0
        protected override void RunItem(string path)
        {
            if (Args.IsCancelled)
            {
                Cancel();
                return;
            }

            var stopwatch = new Stopwatch(MethodBase.GetCurrentMethod().Name, true);

            try
            {
                Log.WriteWarning("---", typeof(AnalyzeNetworkLoop).FullName, MethodBase.GetCurrentMethod().Name);
                Log.WriteWarning($"Running AnalyzeNetwork for file \"{path}\"", typeof(AnalyzeNetworkLoop).FullName, MethodBase.GetCurrentMethod().Name);
                var file = XmlDal.CacheModel.GetFile(path);
                Log.WriteWarning("BuildNetwork on Source", typeof(AnalyzeNetworkLoop).FullName, MethodBase.GetCurrentMethod().Name);
                NetworkService.CheckNetworkMessages(file, null, "");

                Log.WriteWarning($"{file.Network.NetworkMessages.Count} Network Messages to process...", typeof(AnalyzeNetworkLoop).FullName, MethodBase.GetCurrentMethod().Name);

                lock (file.Network)
                {
                    var loop = new AnalyzeNetworkMessageLoop
                    {
                        Queue      = new Queue <NetworkMessageInfo>(file.Network.NetworkMessages),
                        Report     = Args.Report,
                        SourcePath = file.Path
                    };
                    loop.Run();
                }
            }
            finally
            {
                Log.WriteWarning($"Completed AnalyzeNetwork for file \"{path}\"", typeof(AnalyzeNetworkLoop).FullName, MethodBase.GetCurrentMethod().Name);
                stopwatch.Stop();
            }
        }
        public void GetFreeNetwork()
        {
            List <Network> networks = new List <Network>
            {
                new Network
                {
                    Id     = 1, Address = "192.168.10.0", Description = "LAN10", NetworkAddress = 3232238080, Status = 0,
                    Parent = 1, PoolId = 1, Size = 24
                },
                new Network
                {
                    Id     = 38, Address = "192.168.11.0", Description = "LAN11", NetworkAddress = 3232267008, Status = 0,
                    Parent = 1, PoolId = 1, Size = 24
                },
            };
            Mock <NetworkStore> mockStore = new Mock <NetworkStore>();

            mockStore.Setup(store => store.ListNetworks(null)).Returns(networks);
            mockStore.Setup(store => store.GetNetwork(It.IsAny <int>())).Returns <int>(id =>
            {
                return(null);
            });
            mockStore.Setup(store => store.AddNetwork(It.IsAny <ulong>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int?>()))
            .Returns <ulong, int, int, int?>((na, size, poolId, parent) =>
            {
                return(new Network
                {
                    NetworkAddress = na, Size = (byte)size, PoolId = poolId, Parent = parent
                });
            });
            NetworkService service = new NetworkService(mockStore.Object);

            service.GetFreeNetwork(25, 1);
//            parent.Status = NetworkStatus.Parent;
            mockStore.Verify(store => store.ChangeNetwork(It.Is <Network>(n => n.Status == NetworkStatus.Parent)));
        }
Пример #34
0
 private async void spinnerProveedor_ItemSelectedAsync(object sender, AdapterView.ItemSelectedEventArgs e)
 {
     if (spinnerAdapterArticulo.Count > 0)
     {
         spinnerAdapterArticulo.Clear();
         NameArticulo.Clear();
         IDArticulo.Clear();
         spinnerAdapterArticulo.NotifyDataSetChanged();
     }
     try {
         await NetworkService.GetProveedoresService().GetProveedor(int.Parse(IDProveedor[e.Position].ToString())).ContinueWith(post => {
             if (post.IsCompleted && post.Status == TaskStatus.RanToCompletion)
             {
                 post.Result.Articulos.ToList().ForEach(x => {
                     spinnerAdapterArticulo.Add(x.Descripcion);
                     IDArticulo.Add(x.ArticuloId.ToString());
                 });
                 spinnerAdapterArticulo.NotifyDataSetChanged();
             }
         }, TaskScheduler.FromCurrentSynchronizationContext()).ConfigureAwait(false);
     } catch (Exception) {
         throw;
     }
 }
Пример #35
0
        private async Task <SyncMessage> UploadUserDoneWorkoutsAsync(NetworkService nS)
        {
            var doneWorkouts = _context.DoneWorkouts
                               .Include(w => w.DoneExerciseItems)
                               .ThenInclude(e => e.ExerciseItem)
                               .Where(w => w.UserId.Equals(_userId));

            foreach (var doneWorkout in doneWorkouts)
            {
                if (doneWorkout.State == StoreItemState.CreatedClientside)
                {
                    var response = await nS.PostDoneWorkout(_userId, doneWorkout);

                    if (response.IsSuccessStatusCode)
                    {
                        doneWorkout.State = StoreItemState.EqualsWithServer;
                    }
                    else
                    {
                        return new SyncMessage()
                               {
                                   Result = SyncronizationMessages.ModifiedInstancesUploadFail
                               }
                    };
                }
            }
            _context.DoneWorkouts.UpdateRange(doneWorkouts);

            await _context.SaveChangesAsync();

            return(new SyncMessage()
            {
                IsSucessfull = true,
                Result = SyncronizationMessages.ModifiedInstancesUploadSucess
            });
        }
Пример #36
0
        public static void CheckAndSetProxy()
        {
            var ssid = NetworkService.GetConnectingSSID();

            if (ssid == string.Empty)
            {
                return;
            }
            var settings = AutoProxyConfig.Current.Proxy.FindSetting(ssid);

            if (settings.Count != 0)
            {
                var setting = settings.First();
                ProxySettingService.SetProxy(setting);
                IntegrationManager.INSTANCE.SetProxy(setting);
                NotificationService.SendNotify(Resources.SetProxy, $"SSID: {ssid}");
            }
            else
            {
                ProxySettingService.UnsetProxy();
                IntegrationManager.INSTANCE.UnsetProxy();
                NotificationService.SendNotify(Resources.UnsetProxy);
            }
        }
Пример #37
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (NetworkService networkService = user.GetService <NetworkService>())
            {
                // Set the networkCode field to null.
                networkService.RequestHeader.networkCode = null;

                try
                {
                    Network network = networkService.makeTestNetwork();

                    Console.WriteLine(
                        "Test network with network code \"{0}\" and display name \"{1}\" " +
                        "created.\nYou may now sign in at " +
                        "http://www.google.com/dfp/main?networkCode={0}",
                        network.networkCode, network.displayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to make test network. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Пример #38
0
        /// <summary>
        /// Returns if there is a network available and the user is online (logged in).
        /// <para>If there is not a network available, show the corresponding error message if enabled.</para>
        /// <para>If the user is not logged in, also Navigates to the "LoginPage".</para>
        /// </summary>
        /// <param name="showMessageDialog">
        /// Boolean parameter to indicate if show error messages.
        /// <para>Default value is false.</para>
        /// </param>
        /// <returns>True if the user is online. False in other case.</returns>
        public bool IsUserOnline(bool showMessageDialog = false)
        {
            if (!NetworkService.IsNetworkAvailable(showMessageDialog))
            {
                return(false);
            }

            bool isOnline = Convert.ToBoolean(App.MegaSdk.isLoggedIn());

            if (!isOnline)
            {
                if (showMessageDialog)
                {
                    OnUiThread(() =>
                    {
                        var customMessageDialog = new CustomMessageDialog(
                            AppMessages.UserNotOnline_Title,
                            AppMessages.UserNotOnline,
                            App.AppInformation,
                            MessageDialogButtons.Ok);

                        customMessageDialog.OkOrYesButtonTapped += (sender, args) =>
                                                                   NavigateService.NavigateTo(typeof(LoginPage), NavigationParameter.Normal);

                        customMessageDialog.ShowDialog();
                    });
                }
                else
                {
                    OnUiThread(() =>
                               NavigateService.NavigateTo(typeof(LoginPage), NavigationParameter.Normal));
                }
            }

            return(isOnline);
        }
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ProductService productTemplateService =
                       (ProductService)user.GetService(DfpService.v201708.ProductService))

                using (NetworkService networkService =
                           (NetworkService)user.GetService(DfpService.v201708.NetworkService)) {
                    // Create a product.
                    Product product = new Product();
                    product.name = "Non-sales programmatic product #" + new Random().Next(int.MaxValue);

                    // Set required Marketplace information.
                    product.productMarketplaceInfo = new ProductMarketplaceInfo()
                    {
                        additionalTerms       = "Additional terms for the product",
                        adExchangeEnvironment = AdExchangeEnvironment.DISPLAY
                    };

                    // Set common required fields for a programmatic product.
                    product.productType     = ProductType.DFP;
                    product.rateType        = RateType.CPM;
                    product.lineItemType    = LineItemType.STANDARD;
                    product.priority        = 8;
                    product.environmentType = EnvironmentType.BROWSER;
                    product.rate            = new Money()
                    {
                        currencyCode = "USD", microAmount = 6000000L
                    };

                    CreativePlaceholder placeholder = new CreativePlaceholder();
                    placeholder.size = new Size()
                    {
                        width = 300, height = 250, isAspectRatio = false
                    };
                    product.creativePlaceholders = new CreativePlaceholder[] { placeholder };

                    // Create inventory targeting to serve to run of network..
                    String          rootAdUnitId    = networkService.getCurrentNetwork().effectiveRootAdUnitId;
                    AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
                    adUnitTargeting.adUnitId           = rootAdUnitId;
                    adUnitTargeting.includeDescendants = true;

                    Targeting productTargeting = new Targeting();
                    productTargeting.inventoryTargeting = new InventoryTargeting()
                    {
                        targetedAdUnits = new AdUnitTargeting[] { adUnitTargeting }
                    };

                    product.builtInTargeting = productTargeting;

                    try {
                        // Create the product on the server.
                        Product[] products = productTemplateService.createProducts(
                            new Product[] { product });

                        foreach (Product createdProduct in products)
                        {
                            Console.WriteLine("A programmatic product with ID \"{0}\" and name \"{1}\" " +
                                              "was created.", createdProduct.id, createdProduct.name);
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Failed to create products. Exception says \"{0}\"",
                                          e.Message);
                    }
                }
        }
Пример #40
0
 private void OnStart()
 {
     Debug.Log(string.Format("Server start success, ip={0} tcp port={1} ", NetworkService.GetLocalIP(), TCP_PORT), ConsoleColor.Green);
 }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (InventoryService inventoryService = user.GetService <InventoryService>())
            {
                // Get the NetworkService.
                NetworkService networkService = user.GetService <NetworkService>();

                // Set the parent ad unit's ID for all ad units to be created under.
                String effectiveRootAdUnitId =
                    networkService.getCurrentNetwork().effectiveRootAdUnitId;

                // Create local ad unit object.
                AdUnit adUnit = new AdUnit();
                adUnit.name               = "Video_Ad_Unit";
                adUnit.parentId           = effectiveRootAdUnitId;
                adUnit.description        = "Ad unit description.";
                adUnit.targetWindow       = AdUnitTargetWindow.BLANK;
                adUnit.explicitlyTargeted = true;

                // Create master ad unit size.
                AdUnitSize masterAdUnitSize = new AdUnitSize();
                Size       size1            = new Size();
                size1.width                      = 400;
                size1.height                     = 300;
                size1.isAspectRatio              = false;
                masterAdUnitSize.size            = size1;
                masterAdUnitSize.environmentType = EnvironmentType.VIDEO_PLAYER;

                // Create companion sizes.
                AdUnitSize companionAdUnitSize1 = new AdUnitSize();
                Size       size2 = new Size();
                size2.width                          = 300;
                size2.height                         = 250;
                size2.isAspectRatio                  = false;
                companionAdUnitSize1.size            = size2;
                companionAdUnitSize1.environmentType = EnvironmentType.BROWSER;

                AdUnitSize companionAdUnitSize2 = new AdUnitSize();
                Size       size3 = new Size();
                size3.width                          = 728;
                size3.height                         = 90;
                size3.isAspectRatio                  = false;
                companionAdUnitSize2.size            = size3;
                companionAdUnitSize2.environmentType = EnvironmentType.BROWSER;

                // Add companions to master ad unit size.
                masterAdUnitSize.companions = new AdUnitSize[]
                {
                    companionAdUnitSize1,
                    companionAdUnitSize2
                };

                // Set the size of possible creatives that can match this ad unit.
                adUnit.adUnitSizes = new AdUnitSize[]
                {
                    masterAdUnitSize
                };

                try
                {
                    // Create the ad unit on the server.
                    AdUnit[] createdAdUnits = inventoryService.createAdUnits(new AdUnit[]
                    {
                        adUnit
                    });

                    foreach (AdUnit createdAdUnit in createdAdUnits)
                    {
                        Console.WriteLine(
                            "A video ad unit with ID \"{0}\" was created under parent with ID " +
                            "\"{1}\".", createdAdUnit.id, createdAdUnit.parentId);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create video ad units. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Пример #42
0
 public MainScene()
 {
     this.networkService        = WaveServices.GetService <NetworkService>();
     this.discoveredHostButtons = new List <Entity>();
 }
Пример #43
0
        /// <summary>
        /// Handle protocol activations.
        /// </summary>
        /// <param name="e">Details about the activate request and process.</param>
        protected override async void OnActivated(IActivatedEventArgs e)
        {
            NetworkService.CheckNetworkChange();

            if (e.Kind == ActivationKind.Protocol)
            {
                // Handle URI activation
                ProtocolActivatedEventArgs eventArgs = e as ProtocolActivatedEventArgs;

                // Initialize the links information
                LinkInformationService.Reset();

                bool      validUri  = true;
                Exception exception = null;
                try
                {
                    validUri = eventArgs.Uri.IsWellFormedOriginalString();
                    if (validUri)
                    {
                        // Use OriginalString to keep uppercase and lowercase letters
                        LinkInformationService.ActiveLink = UriService.ReformatUri(eventArgs.Uri.OriginalString);
                    }
                }
                catch (UriFormatException ex)
                {
                    validUri  = false;
                    exception = ex;
                }
                finally
                {
                    if (!validUri)
                    {
                        LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Invalid URI detected during app activation", exception);
                        await DialogService.ShowAlertAsync(ResourceService.AppMessages.GetString("AM_InvalidUri_Title"),
                                                           ResourceService.AppMessages.GetString("AM_InvalidUri"));
                    }
                }

                Frame rootFrame = CreateRootFrame();

                if (eventArgs.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // When the navigation stack isn't restored navigate to the first page, configuring
                // the new page by passing required information as a navigation parameter
                if (rootFrame.Content == null)
                {
                    rootFrame.Navigate(typeof(MainPage), eventArgs);
                }

                // Ensure the current window is active
                Window.Current.Activate();

                // Check session and special navigation
                await AppService.CheckActiveAndOnlineSessionAsync();

                // Validate product subscription license on background thread
                var task = Task.Run(() => LicenseService.ValidateLicensesAsync());
            }
        }
Пример #44
0
	////////////////////////////////////////////////////////////////
	// Configuration

	private void LoadConfiguration ()
	{
		Config fsq_config = Conf.Get (Conf.Names.FilesQueryableConfig);
		Config daemon_config = Conf.Get (Conf.Names.DaemonConfig);
		Config bs_config = Conf.Get (Conf.Names.BeagleSearchConfig);

		allow_root_toggle.Active = daemon_config.GetOption (Conf.Names.AllowRoot, false);
		auto_search_toggle.Active = bs_config.GetOption (Conf.Names.BeagleSearchAutoSearch, true);
		battery_toggle.Active = daemon_config.GetOption (Conf.Names.IndexOnBattery, false);
		screensaver_toggle.Active = daemon_config.GetOption (Conf.Names.IndexFasterOnScreensaver, true);

		autostart_toggle.Active = IsAutostartEnabled ();

		binding = bs_config.GetOption ("KeyBinding", null);
		if (String.IsNullOrEmpty (binding)) {
			// Move old preference value to new
			bool binding_ctrl = bs_config.GetOption (Conf.Names.KeyBinding_Ctrl, false);
			bool binding_alt = bs_config.GetOption (Conf.Names.KeyBinding_Alt, false);
			string binding_key = bs_config.GetOption (Conf.Names.KeyBinding_Key, "F12");
			KeyBinding show_binding = new KeyBinding (binding_key, binding_ctrl, binding_alt);

			binding = show_binding.ToString ();
		}

		shortcut_label.Text = String.Format (Catalog.GetString ("Display the search window by pressing {0}"), binding);

		if (fsq_config.GetOption (Conf.Names.IndexHomeDir, true))
			index_home_toggle.Active = true;

		List<string[]> values = fsq_config.GetListOptionValues (Conf.Names.Roots);
		if (values != null)
			foreach (string[] root in values)
				include_view.AddPath (root [0]);

		values = fsq_config.GetListOptionValues (Conf.Names.ExcludeSubdirectory);
		if (values != null)
			foreach (string[] subdir in values)
				exclude_view.AddItem (new ExcludeItem (ExcludeType.Path, subdir [0]));

		values = fsq_config.GetListOptionValues (Conf.Names.ExcludePattern);
		if (values != null)
			foreach (string[] pattern in values)
				exclude_view.AddItem (new ExcludeItem (ExcludeType.Pattern, pattern [0]));

		values = daemon_config.GetListOptionValues (Conf.Names.ExcludeMailfolder);
		if (values != null)
			foreach (string[] mailfolder in values)
				exclude_view.AddItem (new ExcludeItem (ExcludeType.MailFolder, mailfolder [0]));

		Config networking_config = Conf.Get (Conf.Names.NetworkingConfig);
                allow_webinterface_toggle.Active = networking_config.GetOption ("WebInterface", false);
                allow_global_access_toggle.Active = networking_config.GetOption (Conf.Names.ServiceEnabled, false);

		List<string[]> services = networking_config.GetListOptionValues (Conf.Names.NetworkServices);
		if (services != null) {
			foreach (string[] svc in services) {
				NetworkService s = new NetworkService ();
				s.Name = svc [0];
				s.UriString = svc [1];
				s.IsProtected = false;
				s.Cookie = null;
				networking_view.AddNode (s);
			}
		}

                require_password_toggle.Active = networking_config.GetOption (Conf.Names.PasswordRequired, true);
                index_name_entry.Text = networking_config.GetOption (Conf.Names.ServiceName, String.Empty);
                string password = networking_config.GetOption (Conf.Names.ServicePassword, String.Empty);
		password = password.PadRight (12);
                password_entry.Text = password.Substring (0, 12);

		values = daemon_config.GetListOptionValues (Conf.Names.DeniedBackends);
		if (values != null)
			foreach (string[] backend in values)
				backend_view.Set (backend[0], false);
	}
Пример #45
0
 public void StartUp(NetworkService service)
 {
     Debug.Log("Image manager started..");
     network = service;
     status  = ManagerStatus.Started;
 }
Пример #46
0
		public void RemoveNode (NetworkService service) 	 
		{ 	 
			find_node = service; 	 
			found_iter = TreeIter.Zero; 	 
			
			this.Model.Foreach (new TreeModelForeachFunc (ForeachFindNode)); 	 
			
			store.Remove (ref found_iter); 	 
			nodes.Remove (service); 	 
		} 	 
Пример #47
0
		public void AddNode (NetworkService service) 	 
		{ 	 
			nodes.Add (service); 	 
			store.AppendValues (service); 	 
		} 	 
Пример #48
0
 public TcpMessageClient(NetworkService netService)
 {
     this.netService = netService;
     connected = false;
 }
Пример #49
0
 public void Startup(NetworkService service)
 {
     Debug.LogFormat("<size=20><color=red><b><i>{0}</i></b></color></size>", "Images manager starting...");
     _network = service;
     status = ManagerStatus.Started;
 }
Пример #50
0
 //private Socket client = null;
 public TcpMessageServer(NetworkService netService)
 {
     this.netService = netService;
 }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201705.ReportService);

            // Get the NetworkService.
            NetworkService networkService = (NetworkService)user.GetService(
                DfpService.v201705.NetworkService);

            // Set the file path where the report will be saved.
            String filePath = _T("INSERT_FILE_PATH_HERE");

            // Get the root ad unit ID to filter on.
            String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

            // Create statement to filter on an ancestor ad unit with the root ad unit ID to include all
            // ad units in the network.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("PARENT_AD_UNIT_ID = :parentAdUnitId")
                                                .AddValue("parentAdUnitId", long.Parse(rootAdUnitId));

            // Create report query.
            ReportQuery reportQuery = new ReportQuery();

            reportQuery.dimensions =
                new Dimension[] { Dimension.AD_UNIT_ID, Dimension.AD_UNIT_NAME };
            reportQuery.columns = new Column[] { Column.AD_SERVER_IMPRESSIONS,
                                                 Column.AD_SERVER_CLICKS, Column.DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS,
                                                 Column.DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS,
                                                 Column.TOTAL_INVENTORY_LEVEL_IMPRESSIONS,
                                                 Column.TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE };

            // Set the filter statement.
            reportQuery.statement = statementBuilder.ToStatement();

            reportQuery.adUnitView    = ReportQueryAdUnitView.HIERARCHICAL;
            reportQuery.dateRangeType = DateRangeType.LAST_WEEK;

            // Create report job.
            ReportJob reportJob = new ReportJob();

            reportJob.reportQuery = reportQuery;

            try {
                // Run report.
                reportJob = reportService.runReportJob(reportJob);

                ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id);

                // Set download options.
                ReportDownloadOptions options = new ReportDownloadOptions();
                options.exportFormat                  = ExportFormat.CSV_DUMP;
                options.useGzipCompression            = true;
                reportUtilities.reportDownloadOptions = options;

                // Download the report.
                using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
                    reportResponse.Save(filePath);
                }
                Console.WriteLine("Report saved to \"{0}\".", filePath);
            } catch (Exception e) {
                Console.WriteLine("Failed to run inventory report. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Пример #52
0
    public void Startup(NetworkService service)
    {
        Debug.Log("Audio manager starting...");

        _network = service;

        music1Source.ignoreListenerVolume = true;
        music2Source.ignoreListenerVolume = true;
        music1Source.ignoreListenerPause = true;
        music2Source.ignoreListenerPause = true;

        soundVolume = 1f;
        musicVolume = 1f;

        _activeMusic = music1Source;
        _inactiveMusic = music2Source;

        // any long-running startup tasks go here, and set status to 'Initializing' until those tasks are complete
        status = ManagerStatus.Started;
    }
Пример #53
0
 public NetworksV1Controller(NetworkService networkService, IAuthenticationContext authenticationContext)
 {
     _networkService        = networkService;
     _authenticationContext = authenticationContext;
 }
    public void Startup(NetworkService service)
    {
        Debug.Log("Inventory manager starting...");

        _network = service;

        // start empty
        UpdateData(new Dictionary<string, int>());

        // any long-running startup tasks go here, and set status to 'Initializing' until those tasks are complete
        status = ManagerStatus.Started;
    }