Exemplo n.º 1
0
 public CommandsController(ServerContext context)
 {
     _context = context ?? new ServerContext();
     _resolver = new CommandResolver(_context);
     _runner = new CommandRunner(_context);
     _executor = new CommandsExecutor(_context);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Starts the application and modules
        /// </summary>
        public void Start()
        {
            if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile);
            //Load configuration
            ConfigFile configurationFile = new ConfigFile("config.json");
            BaseConfiguration config = configurationFile.Load();
            this.config = config;
            //Set up context
            this.serverContext = new ServerContext(config);
            //Set up ctrl + c handling
                Console.CancelKeyPress += Console_CancelKeyPress;
            //We do a query to sql lite here, give it a chance to connect and cache without
            //having to do it on the first request
            Console.WriteLine("Loading Sql Lite");
            using (var context = new PersistanceContext())
            {
                context.Projects.Any();
                //we dont care about the result
            }
            //Start Subsystems
            StartSubsystem(new HTTPModule());
            StartSubsystem(new SimulationModule());
            StartSubsystem(new WebsocketModule());

            Console.WriteLine("Press any key to close");
            Console.ReadKey();
            this.StopModules();
        }
Exemplo n.º 3
0
		public static void DefaultHandler (ServerContext ctx)
		{
			var request = ctx.Request;

			ctx.Expect (request.AcceptTypes, Is.Null, "#1");
			ctx.Expect (request.ContentLength64, Is.EqualTo (0), "#2");
			ctx.Expect (request.ContentType, Is.Null, "#3");
			ctx.Expect (request.Cookies.Count, Is.EqualTo (0), "#4");
			ctx.Expect (request.HasEntityBody, Is.False, "#5");
			ctx.Expect (request.Headers ["Host"], Is.EqualTo (Server.Host), "#6b");
			ctx.Expect (request.HttpMethod, Is.EqualTo ("GET"), "#7");
			ctx.Expect (request.IsAuthenticated, Is.False, "#8");
			ctx.Expect (request.IsLocal, Is.EqualTo (Server.IsLocal), "#9");
			ctx.Expect (request.IsSecureConnection, Is.False, "#10");
			ctx.Expect (request.IsWebSocketRequest, Is.False, "#11");
			ctx.Expect (request.KeepAlive, Is.True, "#12");
			ctx.Expect (request.ProtocolVersion, Is.EqualTo (HttpVersion.Version11), "#13");
			ctx.Expect (request.ServiceName, Is.Null, "#14");
			ctx.Expect (request.UrlReferrer, Is.Null, "#15");
			// FIXME: CFNetwork seems to set the UserAgent automatically.
			// context.Expect (request.UserAgent, Is.Null, "#16");
			ctx.Expect (request.UserLanguages, Is.Null, "#17");

			ctx.Response.StatusCode = 200;
		}
Exemplo n.º 4
0
 public ServerRepository(ServerContext ctx)
 {
     if (ctx == null)
     {
         throw new Exception(" Given context is null.");
     }
     _ctx = ctx;
 }
        public HttpListenerConnectionContext(ServerContext server, HttpListenerContext httpContext, DateTime acceptedAt)
        {
            _server = server;
            _httpContext = httpContext;
            _acceptedAt = acceptedAt;

            _request = new HttpListenerRequestContext(httpContext.Request);
            _response = new HttpListenerResponseContext(httpContext.Response);
        }
Exemplo n.º 6
0
 /// <summary>
 /// Create a new host for this module
 /// </summary>
 /// <param name="mod">The module to host</param>
 public ModuleHost(AbstractModule mod, ServerContext context, Messenger messenger, BaseConfiguration config)
 {
     this.HostedModule = mod;
     this.ExitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
     mod.Messenger = messenger;
     mod.SetConfiguration(config);
     mod.SetContext(context);
     mod.OnFinishedStopping += env_OnFinishedStopping;
 }
Exemplo n.º 7
0
		public static async Task RandomData_Handler (ServerContext ctx)
		{
			ctx.Response.StatusCode = 200;
			ctx.Response.OutputStream.Write (Header, 0, Header.Length);
			ctx.Response.OutputStream.Flush ();

			await Task.Delay (DataDelay).ConfigureAwait (false);
			ctx.Response.OutputStream.Write (Simple.Data, 0, Simple.Data.Length);
		}
Exemplo n.º 8
0
		public static void Post_Handler (ServerContext ctx)
		{
			ctx.Expect (ctx.Request.HttpMethod, Is.EqualTo ("POST"), "#1");

			string text;
			using (var reader = new StreamReader (ctx.Request.InputStream))
				text = reader.ReadToEnd ();

			ctx.Expect (text, Is.EqualTo (Text), "#3");
			ctx.Response.StatusCode = 200;
		}
Exemplo n.º 9
0
		public static void BasicAuthentication_Handler (ServerContext ctx)
		{
			var user = ctx.ListenerContext.User;
			ctx.Expect (user, Is.Not.Null, "#1");
			ctx.Assert (user.Identity, Is.TypeOf (typeof (HttpListenerBasicIdentity)), "#2");

			var identity = (HttpListenerBasicIdentity)user.Identity;
			ctx.Expect (identity.Name, Is.EqualTo ("monkey"), "#3");
			ctx.Expect (identity.Password, Is.EqualTo ("banana"), "#4");
			ctx.Expect (identity.IsAuthenticated, Is.True, "#5");
		}
Exemplo n.º 10
0
        protected static void RefreshRoom(ServerContext server, Room room)
        {
            var roomRefreshedContent = new ClientRoomRefreshedCommand.MessageContent
              {
            Room = room,
            Users = room.Users.Select(nick => server.Users[nick]).ToList()
              };

              foreach (string user in room.Users)
            ServerModel.Server.SendMessage(user, ClientRoomRefreshedCommand.CommandId, roomRefreshedContent);
        }
        public void SetFileNameAndPathIfFileExists(ServerContext serverContext, HttpContext httpContext)
        {
            var contentType = httpContext.Response.ContentType;
            var fileFullName = serverContext.FileServerBasePath + httpContext.Request.Uri.LocalPath;

            if (fileFullName.ToUpper().IndexOf(".HTM") != -1 || fileFullName.ToUpper().IndexOf(".HTML") != -1)
            {
                contentType = new ContentType { MainContentType = EnumMainContentType.Text, SubContentType = EnumSubContentType.Html };
            }
            else if (fileFullName.ToUpper().IndexOf(".CSS") != -1)
            {
                contentType = new ContentType { MainContentType = EnumMainContentType.Text, SubContentType = EnumSubContentType.Css };
            }
            else if (fileFullName.ToUpper().IndexOf(".TXT") != -1)
            {
                contentType = new ContentType { MainContentType = EnumMainContentType.Text, SubContentType = EnumSubContentType.Plain };
            }
            else if (fileFullName.ToUpper().IndexOf(".JPG") != -1 ||
                fileFullName.ToUpper().IndexOf(".BMP") != -1 ||
                fileFullName.ToUpper().IndexOf(".JPEG") != -1)
            {
                contentType = new ContentType { MainContentType = EnumMainContentType.Image, SubContentType = EnumSubContentType.Jpeg };
            }
            else if (fileFullName.ToUpper().IndexOf(".JS") != -1)
            {
                //note this was text/javascript; I updated because it was obsoleted in favor of application/javascript
                contentType = new ContentType { MainContentType = EnumMainContentType.Application, SubContentType = EnumSubContentType.JavaScript };
            }

            if (contentType != null)
            {
                Debug.Print("Set Content Type: " + contentType);
                httpContext.Response.ContentType = contentType;
            }
            else
            {
                Debug.Print("No Matching Content Type set... " + contentType);
                return;
            }

            if (File.Exists(fileFullName))
            {
                var files = new DirectoryInfo(fileFullName.Substring(0, fileFullName.LastIndexOf('\\'))).GetFiles();
                foreach (var file in files)
                {
                    if (file.FullName == fileFullName)
                    {
                        httpContext.Response.FileLength = file.Length.ToString();
                    }
                }
                httpContext.Response.FileFullName = fileFullName;
                httpContext.Response.HttpStatusCode = new Ok();
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates a new TurnManager instance.
        /// </summary>
        /// <param name="context"></param>
        public TurnManager(ServerContext context)
        {
            this.context = context;
            this.game = context.GameProcessor;
            this.queueMngr = QueueManager.Singletone;
            this.timer = new Stopwatch();

            // Create a server timer for executing turns.
            double clockCycleDuration = (double)context.TurnDuration;
            clockCycleDuration *= 0.9; // TODO: [LOW] thislooks like an ugly hack, reconsider implementing dynamic clock frequency balancing.
            clock = new System.Timers.Timer(clockCycleDuration);
            clock.Elapsed += new System.Timers.ElapsedEventHandler(clock_Elapsed);
        }
Exemplo n.º 13
0
		public HttpConnectionContext(ServerContext server, HttpListenerContext httpContext, DateTime acceptedAt,
		                             Action onComplete)
		{
			_timer = Stopwatch.StartNew();

			_server = server;
			_httpContext = httpContext;
			_acceptedAt = acceptedAt;
			_onComplete = onComplete;

			_request = new HttpRequestContext(httpContext.Request);
			_response = new HttpResponseContext(httpContext.Response);
		}
Exemplo n.º 14
0
        /// <summary>
        /// Change server context to the specified by the <paramref name="serverContext" /> parameter.
        /// </summary>
        /// <param name="serverContext">ServerContext</param>
        /// <exception cref="ArgumentNullException">Illegal server context.</exception>
        public void ChangeServerContext(ServerContext serverContext)
        {
            if (serverContext == null)
                throw new ArgumentNullException("serverContext", "Illegal server context.");

            if (serverContextService.ServerContexts.Contains(serverContext))
            {
                serverContextService.CurrentServerContext = serverContext;

                // ServerContext is changed
                eventAggregator.GetEvent<ServerContextChangedEvent>().Publish(serverContext);
            }
        }
        /// <summary>
        /// Adds new tab for the specified ServerContext.
        /// </summary>
        /// <param name="serverContext">ServerContext.</param>
        /// <exception cref="ArgumentNullException">Illegal server context.</exception>
        public void AddServer(ServerContext serverContext)
        {
            if (serverContext == null)
                throw new ArgumentNullException("serverContext", "Illegal server context.");

            TabItemClosable tab = new TabItemClosable();
            tab.Header = serverContext.Name;
            tab.Tag = serverContext;
            tab.CanClose = true;
            tabServers.Items.Add(tab);

            RemoveDefaultTab();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Adds a server context.
        /// </summary>
        /// <param name="serverContext">ServerContext to add.</param>
        /// <exception cref="ArgumentNullException">Illegal server context.</exception>
        public void AddServerContext(ServerContext serverContext)
        {
            if (serverContext == null)
                throw new ArgumentNullException("serverContext", "Illegal server context.");

            if (serverContextService.ServerContexts.Contains(serverContext))
                throw new ArgumentException("Server context already exists.");

            serverContextService.ServerContexts.Add(serverContext);

            // ServerContext is added
            eventAggregator.GetEvent<ServerContextAddedEvent>().Publish(serverContext);
        }
Exemplo n.º 17
0
        public MasterPlayerTable(int initialSize, ServerContext context)
        {
            this.context = context;
            this.rwls = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
            this.otpLocker = new object();

            this.oneTimePad = new Dictionary<string, DateTime>(initialSize);
            this.removalList = new List<IPEndPoint>(initialSize);

            this.list = new AsteriaData.LinkedList<MasterPlayerRecord>(initialSize);
            this.epMap = new Dictionary<IPEndPoint, AsteriaData.LinkedNode<MasterPlayerRecord>>(initialSize);
            this.aIdMap = new Dictionary<int, AsteriaData.LinkedNode<MasterPlayerRecord>>(initialSize);
            this.cIdMap = new Dictionary<int, AsteriaData.LinkedNode<MasterPlayerRecord>>(initialSize);
        }
Exemplo n.º 18
0
		public static async Task LargeDownload_Handler (ServerContext ctx)
		{
			var random = new Random ();

			for (int i = 0; i < Count; i++) {
				var chunk = new byte [ChunkSize];
				random.NextBytes (chunk);

				await ctx.Response.OutputStream.WriteAsync (
					chunk, 0, chunk.Length).ConfigureAwait (false);

				if (i > 0)
					continue;

				await ctx.Response.OutputStream.FlushAsync ();
			}
		}
Exemplo n.º 19
0
		public static void Upload_Handler (ServerContext ctx)
		{
			ctx.Expect (ctx.Request.HttpMethod, Is.EqualTo ("POST"), "#1");

			long totalSize = 0;

			int ret;
			do {
				var buffer = new byte [20000];
				ret = ctx.Request.InputStream.Read (buffer, 0, buffer.Length);
				if (ret > 0)
					totalSize += ret;
			} while (ret > 0);

			ctx.Expect (totalSize, Is.EqualTo (UploadSize), "#2");
			ctx.Response.StatusCode = 200;
		}
Exemplo n.º 20
0
        public void LoadReactorScripts()
        {
            foreach (var scripttemplate in ServerContext.GlobalReactorCache.Select(i => i.Value))
            {
                var scp = ScriptManager.Load <ReactorScript>(scripttemplate.ScriptKey, scripttemplate);

                if (scp != null && scp.Reactor != null)
                {
                    if (LastKey != scripttemplate.ScriptKey && scripttemplate.CallerType != ReactorQualifer.Reactor)
                    {
                        LastKey = scripttemplate.ScriptKey;
                        scp.Reactor.Decorator = scp;
                        Scripts.Add(scp);
                    }
                    else
                    {
                        var post = ServerContext.GlobalReactorCache
                                   .FirstOrDefault(i => i.Value.ScriptKey == LastKey);

                        if (post.Value != null)
                        {
                            var ps     = ScriptManager.Load <ReactorScript>(post.Value.CallBackScriptKey, scp.Reactor);
                            var parent = Scripts.Find(i => i.Reactor.ScriptKey == scp.Reactor.CallingReactor);

                            if (parent != null)
                            {
                                scp.Reactor.Decorator = scp;

                                parent.Reactor.PostScript = ps;
                                Scripts.Add(scp);
                            }
                        }
                    }
                }
            }

            ServerContext.Log("[{0}] Reactor Scripts Loaded: {1}", Client.Aisling.Username, Scripts.Count);
        }
Exemplo n.º 21
0
        public ServerForm()
        {
            InitializeComponent();

            this.serverCred = new ServerCurrentCredential(PackageNames.Negotiate);

            this.serverContext = new ServerContext(
                serverCred,
                ContextAttrib.AcceptIntegrity |
                ContextAttrib.ReplayDetect |
                ContextAttrib.SequenceDetect |
                ContextAttrib.MutualAuth |
                ContextAttrib.Delegate |
                ContextAttrib.Confidentiality,
                true
                );

            this.server               = new CustomServer();
            this.server.Received     += server_Received;
            this.server.Disconnected += server_Disconnected;

            this.FormClosing += Form1_FormClosing;

            this.startButton.Click += startButton_Click;
            this.stopButton.Click  += stopButton_Click;

            this.encryptButton.Click     += encryptButton_Click;
            this.signButton.Click        += signButton_Click;
            this.impersonateButton.Click += impersonateButton_Click;

            this.running      = false;
            this.initializing = false;
            this.connected    = false;

            UpdateButtons();

            this.serverUsernameTextbox.Text = this.serverCred.PrincipleName;
        }
Exemplo n.º 22
0
        public override void AnnounceServer(string serverId, ServerContext context)
        {
            serverId.ThrowIfNull("serverId");
            context.ThrowIfNull("context");

            var data = new ServerData
            {
                WorkerCount = context.WorkerCount,
                Queues      = context.Queues,
                StartedAt   = DateTime.UtcNow,
            };

            using (var repository = new Repository()) {
                var servers = repository.Session.Query <RavenServer>()
                              .Where(t => t.Id == serverId)
                              .ToList();

                var queues = servers.SelectMany(t => JobHelper.FromJson <ServerData>(t.Data).Queues).ToList();
                queues.AddRange(data.Queues.Select(t => t).ToList());
                data.Queues = queues.ToArray();

                data.WorkerCount += servers.Select(t => JobHelper.FromJson <ServerData>(t.Data).WorkerCount).Sum(t => t);

                foreach (var item in servers)
                {
                    repository.Delete(item);
                }

                var server = new RavenServer
                {
                    Data          = JobHelper.ToJson(data),
                    Id            = serverId,
                    LastHeartbeat = DateTime.UtcNow
                };

                repository.Save(server);
            }
        }
        public override void AnnounceServer(string serverId, ServerContext context)
        {
            if (serverId == null)
            {
                throw new ArgumentNullException(nameof(serverId));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var data = new ServerData
            {
                WorkerCount = context.WorkerCount,
                Queues      = context.Queues,
                StartedAt   = DateTime.Now
            };

            var server = Database.Server.FindById(serverId);

            if (server == null)
            {
                server = new Entities.Server
                {
                    Id            = serverId,
                    Data          = JobHelper.ToJson(data),
                    LastHeartbeat = DateTime.Now
                };
                Database.Server.Insert(server);
            }
            else
            {
                server.LastHeartbeat = DateTime.Now;
                server.Data          = JobHelper.ToJson(data);
                Database.Server.Update(server);
            }
        }
Exemplo n.º 24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            MiniPeerConfiguration config = null;

            // load config file
            if (File.Exists(ConfigFileName))
            {
                config = JsonConvert.DeserializeObject <MiniPeerConfiguration>(File.ReadAllText(ConfigFileName));
            }
            else
            {
                File.WriteAllText(ConfigFileName, JsonConvert.SerializeObject(new MiniPeerConfiguration()));
            }

            var serverContext = new ServerContext(config);

            app.Map("/ws", a => WebSocketHandler.Map(a, serverContext));

            app.UseOwin(x => x.UseNancy(options => options.PassThroughWhenStatusCodesAre(
                                            HttpStatusCode.NotFound,
                                            HttpStatusCode.InternalServerError
                                            )));
        }
Exemplo n.º 25
0
        private void UpdateComponents(TimeSpan elapsedTime)
        {
            try
            {
                var components = ServerComponents.Select(i => i.Value);

                foreach (var component in components)
                {
                    try
                    {
                        component.Update(elapsedTime);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
            catch (Exception e)
            {
                ServerContext.Error(e);
            }
        }
Exemplo n.º 26
0
        public static bool Update(Action operation)
        {
            if (operation == null)
            {
                return(false);
            }

            try
            {
                operation.Invoke();
            }
            catch (Exception exception)
            {
                if (!exception.Message.Contains("Collection"))
                {
                    ServerContext.Error(exception);
                }

                return(false);
            }

            return(true);
        }
Exemplo n.º 27
0
        public void AnnounceServer(string serverId, ServerContext context)
        {
            if (serverId == null)
            {
                throw new ArgumentNullException("serverId");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var data = new ServerDataDto
            {
                WorkerCount = context.WorkerCount,
                Queues      = context.Queues,
                StartedAt   = _database.GetServerTimeUtc(),
            };

            _database.Server.Update(Query <ServerDto> .EQ(_ => _.Id, serverId),
                                    Update.Combine(Update <ServerDto> .Set(_ => _.Data, JobHelper.ToJson(data)), Update <ServerDto> .Set(_ => _.LastHeartbeat, _database.GetServerTimeUtc())),
                                    UpdateFlags.Upsert);
        }
Exemplo n.º 28
0
        private void LoadSpellScript(string spellscriptstr, bool primary = false)
        {
            try
            {
                if (ServerContext.GlobalSpellTemplateCache.ContainsKey(spellscriptstr))
                {
                    var script = ScriptManager.Load <SpellScript>(spellscriptstr,
                                                                  Spell.Create(1, ServerContext.GlobalSpellTemplateCache[spellscriptstr]));


                    if (script != null)
                    {
                        script.IsScriptDefault = primary;
                        SpellScripts.Add(script);
                    }
                }
            }
            catch (Exception e)
            {
                ServerContext.Report(e);
                //ignore
            }
        }
        public void AddSubCategory()
        {
            this.CreatedStandardprice.Parent_id = SelectedCategory.id;
            this.CreatedStandardprice.CorrespondingCategoryString = SelectedCategory.name;

            try
            {
                using (var ctx = new ServerContext())
                {
                    this.CreatedStandardprice.name          = this.SubCategoryName;
                    this.CreatedStandardprice.standardprice = this.Price;
                    ctx.Standardprices.Add(this.CreatedStandardprice);
                    ctx.SaveChanges();
                }
                this.AllSubCategories.Add(CreatedStandardprice);
                this.ShownSubCategories.Add(CreatedStandardprice);
                this.CreatedStandardprice = new Standardprice();
            }
            catch (System.Data.DataException)
            {
                PopupService.PopupMessage(Application.Current.FindResource("CouldNotConnectToDatabase").ToString(), Application.Current.FindResource("Error").ToString());
            }
        }
Exemplo n.º 30
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                // поиск пользователя в бд
                ServerUser serverUser = null;
                using (ServerContext db = new ServerContext())
                {
                    serverUser = db.ServerUsers.FirstOrDefault(u => u.Email == model.Name && u.Password == model.Password);
                }
                if (serverUser != null)
                {
                    FormsAuthentication.SetAuthCookie(model.Name, true);
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Неверный логин или пароль");
                }
            }

            return(View(model));
        }
Exemplo n.º 31
0
        private async Task OnUserJoined(SocketGuildUser user)
        {
            Server server;

            if (!this.Client.Servers.ContainsKey(user.Guild.Id) || (server = this.Client.Servers[user.Guild.Id]) == null)
            {
                return;
            }

            if (server.Config.VerifyOnWelcome)
            {
                await Task.Delay(3000);

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);

                UserData userData = dbContext.GetOrAddUser(server.Id, user.Id);
                await VerifyUsersPm(server, new List <UserData> {
                    userData
                });

                dbContext.Dispose();
            }
        }
Exemplo n.º 32
0
        protected override void HandleClient(ServerContext context, Client target, int duration, bool ip, string reason)
        {
            if (target.Entity == null)
            {
                Console.WriteLine($@"    {Strings.Player.offline}");

                return;
            }

            // TODO: Refactor the global/console messages into ModeratorActionCommand
            var name = target.Entity.Name;

            if (string.IsNullOrEmpty(Mute.FindMuteReason(target.User.Id, "")))
            {
                Mute.Add(target, duration, reason, Strings.Commands.muteuser, ip ? target.GetIp() : "");
                PacketSender.SendGlobalMsg(Strings.Account.muted.ToString(name));
                Console.WriteLine($@"    {Strings.Account.muted.ToString( name )}");
            }
            else
            {
                Console.WriteLine($@"    {Strings.Account.alreadymuted.ToString( name )}");
            }
        }
Exemplo n.º 33
0
        public Rx GetRx()
        {
            try
            {
                var context    = new ServerContext("https://proxyplayground.medicineontime.com", "odata", "Pete.Jenney", "$!Secure2017");
                var connection = new Test1(context);

                var scrip = connection.Get <NextRx>("Rxes", "?$filter=RxSystemId eq 'Q541321'").Result;
                if (scrip == null)
                {
                    Assert.Fail("No data found");
                }

                return(scrip.value.First());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail(ex.Message);
            }

            return(null);
        }
Exemplo n.º 34
0
        public IEnumerable <Rx> GetRxList()
        {
            try
            {
                var context    = new ServerContext("https://proxyplayground.medicineontime.com", "odata", "Pete.Jenney", "$!Secure2017");
                var connection = new Test1(context);

                var scrips = connection.Get <NextRx>("Rxes", $"?$filter=Refills eq 5").Result;
                if (scrips == null)
                {
                    Assert.Fail("Failed to get data");
                }

                return(scrips.value);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail(ex.Message);
            }

            return(null);
        }
        private async void AreaCreateWizard_Load(object sender, EventArgs e)
        {
            var title = Text;

            void SetControls(bool val)
            {
                foreach (Control control in Controls)
                {
                    control.Enabled = val;
                }
            }

            Text += "Loading Content...";

            SetControls(false);
            await Task.Run(() => ServerContext.LoadAndCacheStorage(true));

            SetControls(true);
            Text = title;

            button2.Enabled = true;
            button4.Enabled = false;
        }
Exemplo n.º 36
0
        private void server_Disconnected()
        {
            this.running      = true;
            this.initializing = true;
            this.connected    = false;

            this.serverContext.Dispose();
            this.serverContext = new ServerContext(
                serverCred,
                ContextAttrib.AcceptIntegrity |
                ContextAttrib.ReplayDetect |
                ContextAttrib.SequenceDetect |
                ContextAttrib.MutualAuth |
                ContextAttrib.Delegate |
                ContextAttrib.Confidentiality
                );

            this.BeginInvoke((Action) delegate()
            {
                UpdateButtons();
                this.clientUsernameTextBox.Text = "";
            });
        }
Exemplo n.º 37
0
        public void RemoveUser(string userIndex, string userNames)
        {
            try
            {
                var arr         = userIndex.Split(',');
                var userNameArr = userNames.Split(',');
                //for (var i = arr.Length - 1; i > -1; i--)
                //{
                //    Dbop.Delete(int.Parse(arr[i]));
                //    Dbop.DeleteHash(userNameArr[i]);
                //}

                //删除用户绑定
                lock (userLocker)
                {
                    if (ServerContext.ServerConfig.BoundConfig.UserPortBounds.ContainsKey(userIndex))
                    {
                        ServerContext.ServerConfig.BoundConfig.UserPortBounds.Remove(userIndex);
                    }
                }
                //刷新绑定列表
                ServerContext.UpdatePortMap();
                ServerContext.ServerConfig.SaveChanges(ServerContext.ServerConfigPath);
                for (var i = arr.Length - 1; i > -1; i--)
                {
                    var userId  = int.Parse(arr[i]);
                    var userDto = Dbop.Get(userNameArr[i]).ToObject <UserDTO>();
                    Dbop.Delete(userId);//litedb不起作用
                    Dbop.DeleteHash(userNameArr[i]);
                    ServerContext.CloseAllSourceByClient(int.Parse(userDto.userId));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("删除用户出错:" + ex.Message);
            }
        }
Exemplo n.º 38
0
        /// <summary> Verifies a user based on a hashCode string and returns true if successful. </summary>
        private async Task VerifyUserHash(guid userId, string hashCode)
        {
            if (!this.HashedValues.ContainsKey(hashCode) || this.HashedValues[hashCode].UserId != userId || !this.Client.Servers.ContainsKey(this.HashedValues[hashCode].ServerId))
            {
                if (this.Client.GlobalConfig.LogDebug)
                {
                    if (!this.HashedValues.ContainsKey(hashCode))
                    {
                        Console.WriteLine("Verification: Received PM `${hashCode}` - not in the dictionary.");
                    }
                    else if (this.HashedValues[hashCode].UserId != userId)
                    {
                        Console.WriteLine("Verification: Found a hashCode, but the userid does not fit.");
                    }
                    else if (!this.Client.Servers.ContainsKey(this.HashedValues[hashCode].ServerId))
                    {
                        Console.WriteLine("Verification: Server for the hashCode does not exist.");
                    }
                }

                return;
            }

            Server server = this.Client.Servers[this.HashedValues[hashCode].ServerId];

            ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
            UserData      userData  = dbContext.GetOrAddUser(server.Id, userId);

            if (await VerifyUsers(server, new List <UserData> {
                userData
            }))
            {
                dbContext.SaveChanges();
            }

            dbContext.Dispose();
        }
Exemplo n.º 39
0
        protected override void HandleTarget(ServerContext context, ParserResult result, User target)
        {
            if (target == null)
            {
                Console.WriteLine($@"    {Strings.Account.notfound}");

                return;
            }

            if (target.Power == null)
            {
                throw new ArgumentNullException(nameof(target.Power));
            }

            var role = result.Find(Role);

            if (role == "users.query")
            {
                target.Power.ApiRoles.UserQuery  = false;
                target.Power.ApiRoles.UserManage = false;
            }
            else if (role == "users.manage")
            {
                target.Power.ApiRoles.UserManage = false;
            }
            else
            {
                //Role Not Found
                Console.WriteLine(Strings.Commandoutput.apirolenotfound.ToString(role));

                return;
            }

            DbInterface.SavePlayerDatabaseAsync();

            Console.WriteLine(Strings.Commandoutput.apirolerevoked.ToString(target.Name, role));
        }
Exemplo n.º 40
0
        public ServerForm()
        {
            InitializeComponent();

            this.serverCred = new ServerCredential( PackageNames.Negotiate );

            this.serverContext = new ServerContext(
                serverCred,
                ContextAttrib.AcceptIntegrity |
                ContextAttrib.ReplayDetect |
                ContextAttrib.SequenceDetect |
                ContextAttrib.MutualAuth |
                ContextAttrib.Delegate |
                ContextAttrib.Confidentiality
            );

            this.server = new CustomServer();
            this.server.Received += server_Received;
            this.server.Disconnected += server_Disconnected;

            this.FormClosing += Form1_FormClosing;

            this.startButton.Click += startButton_Click;
            this.stopButton.Click += stopButton_Click;

            this.encryptButton.Click += encryptButton_Click;
            this.signButton.Click += signButton_Click;
            this.impersonateButton.Click += impersonateButton_Click;

            this.running = false;
            this.initializing = false;
            this.connected = false;

            UpdateButtons();

            this.serverUsernameTextbox.Text = this.serverCred.PrincipleName;
        }
Exemplo n.º 41
0
        public override void AnnounceServer(string serverId, ServerContext context)
        {
            if (serverId == null)
            {
                throw new ArgumentNullException(nameof(serverId));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // TODO: move to stored procedure
            Entities.Server server = Storage.Client.CreateDocumentQuery <Entities.Server>(Storage.Collections.ServerDocumentCollectionUri, QueryOptions)
                                     .Where(s => s.ServerId == serverId)
                                     .AsEnumerable()
                                     .FirstOrDefault();

            if (server != null)
            {
                server.LastHeartbeat = DateTime.UtcNow;
                server.Workers       = context.WorkerCount;
                server.Queues        = context.Queues;
            }
            else
            {
                server = new Entities.Server
                {
                    ServerId      = serverId,
                    Workers       = context.WorkerCount,
                    Queues        = context.Queues,
                    CreatedOn     = DateTime.UtcNow,
                    LastHeartbeat = DateTime.UtcNow
                };
            }

            Storage.Client.UpsertDocumentWithRetriesAsync(Storage.Collections.ServerDocumentCollectionUri, server).GetAwaiter().GetResult();
        }
Exemplo n.º 42
0
        protected override void ProcessAsTls1()
        {
            ServerContext context = (ServerContext)this.Context;

            // Select the private key information
            RSA rsa = (RSA)context.SslStream.PrivateKeyCertSelectionDelegate(
                new SX509.X509CertificateMono(context.ServerSettings.Certificates[0].RawData),
                null);

            RSAParameters rsaParams = rsa.ExportParameters(false);

            // Write Modulus
            this.WriteInt24(rsaParams.Modulus.Length);
            this.Write(rsaParams.Modulus, 0, rsaParams.Modulus.Length);

            // Write exponent
            this.WriteInt24(rsaParams.Exponent.Length);
            this.Write(rsaParams.Exponent, 0, rsaParams.Exponent.Length);

            // Write signed params
            byte[] signature = this.createSignature(rsa, this.ToArray());
            this.WriteInt24(signature.Length);
            this.Write(signature);
        }
Exemplo n.º 43
0
        public override void AnnounceServer(string serverId, ServerContext context)
        {
            if (serverId == null)
            {
                throw new ArgumentNullException(nameof(serverId));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Documents.Server server = new Documents.Server
            {
                Id            = $"{serverId}:{DocumentTypes.Server}".GenerateHash(),
                ServerId      = serverId,
                Workers       = context.WorkerCount,
                Queues        = context.Queues,
                CreatedOn     = DateTime.UtcNow,
                LastHeartbeat = DateTime.UtcNow
            };
            Task <ItemResponse <Documents.Server> > task = Storage.Container.UpsertItemWithRetriesAsync(server, new PartitionKey((int)DocumentTypes.Server));

            task.Wait();
        }
Exemplo n.º 44
0
        private void LoadSkillScript(string skillscriptstr, bool primary = false)
        {
            try
            {
                if (ServerContext.GlobalSkillTemplateCache.ContainsKey(skillscriptstr))
                {
                    var script = ScriptManager.Load <SkillScript>(skillscriptstr,
                                                                  Skill.Create(1, ServerContext.GlobalSkillTemplateCache[skillscriptstr]));


                    if (script != null)
                    {
                        script.Skill.NextAvailableUse = DateTime.UtcNow;
                        script.IsScriptDefault        = primary;
                        SkillScripts.Add(script);
                    }
                }
            }
            catch (Exception e)
            {
                ServerContext.Report(e);
                //ignore
            }
        }
Exemplo n.º 45
0
        /// <summary>
        ///     Login Client - Save Character Template.
        /// </summary>
        protected override void Format04Handler(LoginClient client, ClientFormat04 format)
        {
            //make sure the first step was done first.
            if (client.CreateInfo == null)
            {
                ClientDisconnected(client);
                return;
            }

            //create aisling from default template.
            var template = Aisling.Create();

            template.Display   = (BodySprite)(format.Gender * 16);
            template.Username  = client.CreateInfo.AislingUsername;
            template.Password  = client.CreateInfo.AislingPassword;
            template.Gender    = (Gender)format.Gender;
            template.HairColor = format.HairColor;
            template.HairStyle = format.HairStyle;

            ServerContext.Log("New character Created: " + template.Username);

            StorageManager.AislingBucket.Save(template);
            client.SendMessageBox(0x00, "\0");
        }
Exemplo n.º 46
0
        /// <summary>
        ///     Get user account name by searching user profile by user display name
        /// </summary>
        /// <param name="displayName"></param>
        /// <param name="currentWeb"></param>
        /// <param name="site"></param>
        /// <returns></returns>
        public string getUserAccountName(string displayName, SPWeb currentWeb, SPSite site)
        {
            string acctName = "";

            try
            {
                //SPSite site = SPContext.Current.Site;
                ServerContext      ospServerContext      = ServerContext.GetContext(site);
                UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);

                if (ospUserProfileManager != null)
                {
                    upFieldName  = new List <string>();
                    upFieldValue = new List <string>();

                    //Search through all user profile property fields
                    foreach (UserProfile user in ospUserProfileManager)
                    {
                        if (user.DisplayName.ToLower() == displayName.ToLower())
                        {
                            return(user.MultiloginAccounts[0]); //Search user has been found
                        }
                    }
                }
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb);
                objErr.logSysErrorEmail(APP_NAME, err, "Error at getUserAccountName function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
            }

            return(acctName);
        }
Exemplo n.º 47
0
        /// <summary>
        ///     Call checkpoint handler
        /// </summary>
        /// <param name="checkpoint">Checkpoint item</param>
        /// <returns>Success or fail code based on handler result</returns>
        private int PassCheckpoint(CheckpointMenuItem checkpoint)
        {
            // find handler
            if (_checkpointHandlers.ContainsKey(checkpoint.Text) == false)
            {
                ServerContext.Log("No Callback for checkpoint: {0}", checkpoint.Text);
                return(Constants.CheckpointOnFail);
            }

            var handler = _checkpointHandlers[checkpoint.Text];
            var args    = new CheckpointHandlerArgs
            {
                Value  = checkpoint.Value,
                Amount = checkpoint.Amount,
                Result = false
            };

            // call handler
            handler(Client, args);

            return(args.Result
                ? Constants.CheckpointOnSuccess
                : Constants.CheckpointOnFail);
        }
Exemplo n.º 48
0
        private void CreateAllTvServerConnections()
        {
            MPExtendedProviderSettings setting = _settings.Settings;

            if (string.IsNullOrWhiteSpace(setting.TvServerHost))
            {
                return;
            }

            // Needed for checking setting changes
            _serverNames = setting.TvServerHost;

            string[] serverNames = setting.TvServerHost.Split(';');
            _tvServers = new ServerContext[serverNames.Length];

            for (int serverIndex = 0; serverIndex < serverNames.Length; serverIndex++)
            {
                try
                {
                    string        serverName = serverNames[serverIndex].Trim();
                    ServerContext tvServer   = new ServerContext
                    {
                        ServerName   = serverName,
                        ConnectionOk = false,
                        Username     = setting.Username,
                        Password     = setting.Password
                    };
                    _tvServers[serverIndex] = tvServer;
                    tvServer.CreateChannel();
                }
                catch (Exception ex)
                {
                    NotifyException(ex, RES_TV_CONNECTION_ERROR_TEXT, serverIndex);
                }
            }
        }
Exemplo n.º 49
0
        public override void AnnounceServer(string serverId, ServerContext context)
        {
            var transaction = Redis.CreateTransaction();

            transaction.SetAddAsync(RedisStorage.Prefix + "servers", serverId);

            transaction.HashSetAsync(
                string.Format(RedisStorage.Prefix + "server:{0}", serverId),
                new Dictionary <string, string>
            {
                { "WorkerCount", context.WorkerCount.ToString(CultureInfo.InvariantCulture) },
                { "StartedAt", JobHelper.SerializeDateTime(DateTime.UtcNow) },
            }.ToHashEntries());

            foreach (var queue in context.Queues)
            {
                var queue1 = queue;
                transaction.ListRightPushAsync(
                    string.Format(RedisStorage.Prefix + "server:{0}:queues", serverId),
                    queue1);
            }

            transaction.Execute();
        }
Exemplo n.º 50
0
        public override void AnnounceServer(string serverId, ServerContext context)
        {
            if (serverId == null)
            {
                throw new ArgumentNullException(nameof(serverId));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var set = new BsonDocument("$set", new BsonDocument
            {
                [nameof(ServerDto.WorkerCount)]   = context.WorkerCount,
                [nameof(ServerDto.Queues)]        = new BsonArray(context.Queues),
                [nameof(ServerDto.StartedAt)]     = DateTime.UtcNow,
                [nameof(ServerDto.LastHeartbeat)] = DateTime.UtcNow
            });

            _dbContext.Server.UpdateOne(new BsonDocument("_id", serverId), set, new UpdateOptions {
                IsUpsert = true
            });
        }
Exemplo n.º 51
0
		public static void DefaultHandler_Version_1_0 (ServerContext ctx)
		{
			var request = ctx.Request;

			ctx.Expect (request.AcceptTypes, Is.Null, "#1");
			ctx.Expect (request.ContentLength64, Is.EqualTo (0), "#2");
			ctx.Expect (request.ContentType, Is.Null, "#3");
			ctx.Expect (request.Cookies.Count, Is.EqualTo (0), "#4");
			ctx.Expect (request.HasEntityBody, Is.False, "#5");

			/*
			 * CFNetwork seems to always send 'Connection' and 'User-Agent'.
			 */
			foreach (var obj in request.Headers) {
				if (obj.Equals ("Host"))
					continue;
				else if (obj.Equals ("Connection"))
					continue;
				else if (obj.Equals ("User-Agent"))
					continue;
				ctx.Expect (false, "#6");
			}
			ctx.Expect (request.Headers ["Host"], Is.EqualTo (Server.Host), "#6a");
			ctx.Expect (request.HttpMethod, Is.EqualTo ("GET"), "#7");
			ctx.Expect (request.IsAuthenticated, Is.False, "#8");
			ctx.Expect (request.IsLocal, Is.EqualTo (Server.IsLocal), "#9");
			ctx.Expect (request.IsSecureConnection, Is.False, "#10");
			ctx.Expect (request.IsWebSocketRequest, Is.False, "#11");
			ctx.Expect (request.KeepAlive, Is.False, "#12");
			ctx.Expect (request.ProtocolVersion, Is.EqualTo (HttpVersion.Version10), "#13");
			ctx.Expect (request.ServiceName, Is.Null, "#14");
			ctx.Expect (request.UrlReferrer, Is.Null, "#15");
			// FIXME: CFNetwork seems to set the UserAgent automatically.
			// Assert.IsNull (request.UserAgent, "#16");
			ctx.Expect (request.UserLanguages, Is.Null, "#17");

			ctx.Response.StatusCode = 200;
		}
Exemplo n.º 52
0
 public CommandsService(ServerContext context = null)
 {
     _context = context ?? new ServerContext();
     _resolver = new CommandResolver(_context);
     _runner = new CommandRunner(_context);
 }
        private void CreateAllTvServerConnections()
        {
            MPExtendedProviderSettings setting = ServiceRegistration.Get<ISettingsManager>().Load<MPExtendedProviderSettings>();
              if (setting.TvServerHost == null)
            return;

              string[] serverNames = setting.TvServerHost.Split(';');
              _tvServers = new ServerContext[serverNames.Length];

              for (int serverIndex = 0; serverIndex < serverNames.Length; serverIndex++)
              {
            try
            {
              string serverName = serverNames[serverIndex];
              ServerContext tvServer = new ServerContext
                                     {
                                       ServerName = serverName,
                                       ConnectionOk = false,
                                       Username = setting.Username,
                                       Password = setting.Password
                                     };
              _tvServers[serverIndex] = tvServer;
              tvServer.CreateChannel();
            }
            catch (Exception ex)
            {
              NotifyException(ex, RES_TV_CONNECTION_ERROR_TEXT, serverIndex);
            }
              }
        }
Exemplo n.º 54
0
        /// <summary>
        /// Removes <paramref name="serverContext" /> from the list of servers.
        /// </summary>
        /// <param name="serverContext">ServerContext</param>
        /// <exception cref="ArgumentNullException">Illegal server context.</exception>
        public void RemoveServerContext(ServerContext serverContext)
        {
            if (serverContext == null)
                throw new ArgumentNullException("serverContext", "Illegal server context.");

            if (serverContextService.ServerContexts.Contains(serverContext))
            {
                serverContextService.ServerContexts.Remove(serverContext);

                // ServerContext is removed
                eventAggregator.GetEvent<ServerContextRemovedEvent>().Publish(serverContext);
            }

            if (serverContextService.ServerContexts.Count == 0)
            {
                serverContextService.CurrentServerContext = null;
                eventAggregator.GetEvent<ServerContextClearedEvent>().Publish(null);

                // Load DefaultModule
                eventAggregator.GetEvent<ModuleChangeEvent>().Publish(ModuleNames.DefaultModule);
            }
        }
        private void InitializeTestEnv()
        {
            ServerContext sc = new ServerContext("Server 1");
            sc.Modules = new List<string>() { ModuleNames.Documents, ModuleNames.Security, ModuleNames.Users };
            eventAggregator.GetEvent<ServerContextAddEvent>().Publish(sc);

            sc = new ServerContext("Server 2");
            sc.Modules = new List<string>() { ModuleNames.Documents, ModuleNames.Security, ModuleNames.Users };
            eventAggregator.GetEvent<ServerContextAddEvent>().Publish(sc);

            sc = new ServerContext("Server 3");
            sc.Modules = new List<string>() { ModuleNames.Documents, ModuleNames.Security };
            eventAggregator.GetEvent<ServerContextAddEvent>().Publish(sc);

            sc = new ServerContext("Server 4");
            sc.Modules = new List<string>() { ModuleNames.Documents };
            eventAggregator.GetEvent<ServerContextAddEvent>().Publish(sc);
        }
        /// <summary>
        /// Removes a tab for the specified ServerContext.
        /// </summary>
        /// <param name="serverContext">ServerContext.</param>
        /// <exception cref="ArgumentNullException">Illegal server context.</exception>
        public void RemoveServer(ServerContext serverContext)
        {
            if (serverContext == null)
                throw new ArgumentNullException("serverContext", "Illegal server context.");

            foreach (TabItem tabItem in tabServers.Items)
            {
                if (tabItem.Tag != null && (ServerContext)tabItem.Tag == serverContext)
                {
                    tabServers.Items.Remove(tabItem);
                    break;
                }
            }

            // All tabs were removed
            if (tabServers.Items.Count == 0)
            {
                AddDefaultTab();
            }
        }
Exemplo n.º 57
0
		public static void SimpleHtml_Handler (ServerContext ctx)
		{
			ctx.Response.StatusCode = 200;
			using (var writer = new StreamWriter (ctx.Response.OutputStream))
				writer.Write (Text);
		}
 public void SendFile(ServerContext serverContext, HttpContext httpContext)
 {
     SDCardManager.SendFile(httpContext.Response.FileFullName, httpContext.Socket);
 }
        public bool TryGetDirectoryResultIfDirectoryExists(ServerContext serverContext, HttpContext httpContext)
        {
            var directoryPath = serverContext.FileServerBasePath + httpContext.Request.Uri.LocalPath;

            Debug.Print(directoryPath);
            DirectoryInfo rootDirectory = new DirectoryInfo(directoryPath);
            if (rootDirectory.Exists)
            {
                DirectoryInfo[] directories = rootDirectory.GetDirectories();
                FileInfo[] files = rootDirectory.GetFiles();
                httpContext.Response.Data = new DirectoryListBuilder().GenerateSimpleDirectoryList(httpContext.Request.Uri.RawPath, directories, files, serverContext.HostName);
                httpContext.Response.ContentType = new ContentType { MainContentType = EnumMainContentType.Text, SubContentType = EnumSubContentType.Html };
                return true;
            }

            return false;
        }
Exemplo n.º 60
0
		public static void RandomData_Handler (ServerContext ctx)
		{
			ctx.Response.StatusCode = 200;
			ctx.Response.OutputStream.Write (Data, 0, Data.Length);
			ctx.Response.Close ();
		}