/// <summary> /// This method supports the framework directly and should not be used from your code /// </summary> /// <param name="handler">The handler.</param> /// <param name="context">The context.</param> /// <returns></returns> public static void Impl(IETag handler, IContext context) { if (!string.IsNullOrWhiteSpace(handler.OutputETag)) { context.Response.SetETag(handler.OutputETag); } }
/// <summary> /// Creates an instance within the specified context. /// </summary> /// <param name="context">The context.</param> /// <returns>The created instance.</returns> public object Create(IContext context) { Type mockType = typeof(Mock<>).MakeGenericType(context.Request.Service); var constructorInfo = mockType.GetConstructor(new Type[0]); var mock = (Mock)constructorInfo.Invoke(new object[0]); return mock.Object; }
internal void ProcessRequest(IContext context) { try { switch (context.Request.HttpMethod) { case "GET": if (PublicFileHandler.TryHandleAsFile(context.Request, context.Response)) { break; } GetHandler.HandleRequest(context); break; case "POST": PostHandler.HandleRequest(context); break; } } catch (HttpException httpException) { context.Response.StatusCode = httpException.ErrorCode; context.Response.StatusDescription = httpException.Message; } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal server error."; } }
public IEnumerable<INodeFactory> ResolvePath(IContext context, string path) { // string driveName; // var isAbsolute = context.SessionState.Path.IsPSAbsolute(path, out driveName); // if (isAbsolute) // { // string fileSystemDriveName = driveName.TrimStart('x'); // path = Regex.Replace(path, "^" + Regex.Escape( driveName + ":" ), fileSystemDriveName + ":"); // } FileSystemInfo fileSystemInfo = null; if (Microsoft.KtmIntegration.TransactedFile.Exists(path)) { fileSystemInfo = new FileInfo( path ); } else if (Microsoft.KtmIntegration.TransactedDirectory.Exists(path)) { fileSystemInfo = new DirectoryInfo(path); } else { return null; } return new[]{new TxFNodeFactory( fileSystemInfo )}; }
public virtual void WriteIndexEntry(IContext context, ByteArrayBuffer reader, object obj) { MappedIDPair mappedIDs = (MappedIDPair)obj; _origHandler.WriteIndexEntry(context, reader, mappedIDs.Orig()); _mappedHandler.WriteIndexEntry(context, reader, mappedIDs.Mapped()); }
public void Execute(IContext context) { if (Items != null) { foreach (object item in Items as System.Collections.IEnumerable) { try { Template.DataContext = item; Action section = null; if (context.Sections.TryGetValue(Section, out section)) { section(); } else { throw new RazorException("{0} section not found", Section); } } finally { Template.DataContext = context.Model; } } } }
/// <summary> /// Gets the logger. /// </summary> /// <param name="ctx">The context.</param> /// <returns>The logger for the given context.</returns> private static ILog GetLogger(IContext ctx) { var filterContext = ctx.Request.ParentRequest.Parameters.OfType<FilterContextParameter>().SingleOrDefault(); return LogManager.GetLogger(filterContext == null ? ctx.Request.Target.Member.DeclaringType : filterContext.ActionDescriptor.ControllerDescriptor.ControllerType); }
internal ListenerRequest(HttpListenerRequest innerRequest, IContext context) { if (innerRequest == null) throw new ArgumentNullException("innerRequest"); if (context == null) throw new ArgumentNullException("context"); InnerRequest = innerRequest; _context = context; }
/// <summary> /// Generates a message saying that the constructor is ambiguous. /// </summary> /// <param name="context">The context.</param> /// <param name="bestDirectives">The best constructor directives.</param> /// <returns>The exception message.</returns> public static string ConstructorsAmbiguous(IContext context, IGrouping<int, ConstructorInjectionDirective> bestDirectives) { using (var sw = new StringWriter()) { sw.WriteLine("Error activating {0} using {1}", context.Request.Service.Format(), context.Binding.Format(context)); sw.WriteLine("Several constructors have the same priority. Please specify the constructor using ToConstructor syntax or add an Inject attribute."); sw.WriteLine(); sw.WriteLine("Constructors:"); foreach (var constructorInjectionDirective in bestDirectives) { FormatConstructor(constructorInjectionDirective.Constructor, sw); } sw.WriteLine(); sw.WriteLine("Activation path:"); sw.WriteLine(context.Request.FormatActivationPath()); sw.WriteLine("Suggestions:"); sw.WriteLine(" 1) Ensure that the implementation type has a public constructor."); sw.WriteLine(" 2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead."); return sw.ToString(); } }
public override void Render(HttpContextBase httpContext, IContext requestContext) { if (httpContext.Session != null) foreach (object key in httpContext.Session.Keys) { if (requestContext.Contains(key)) throw new ApplicationException(String.Format("{0} is present on both the Session and the Request.", key)); requestContext.Add(key.ToString(), httpContext.Session[key.ToString()]); } try { var templateTuple = manager.RenderTemplate(requestContext.Response.RenderTarget, (IDictionary<string, object>)requestContext); manager = templateTuple.Item1; TextReader reader = templateTuple.Item2; char[] buffer = new char[4096]; int count = 0; while ((count = reader.ReadBlock(buffer, 0, 4096)) > 0) httpContext.Response.Write(buffer, 0, count); } catch (Exception ex) { httpContext.Response.StatusCode = 500; httpContext.Response.Write(RenderException(requestContext.Response.RenderTarget, ex, true)); } }
public static void Render(object item, int count, bool isExpanded, IDrawingToolkit tk, IContext context, Area backgroundArea, Area cellArea, CellState state) { if (item is EventType) { RenderAnalysisCategory (item as EventType, count, isExpanded, tk, context, backgroundArea, cellArea); } else if (item is SubstitutionEvent) { SubstitutionEvent s = item as SubstitutionEvent; RenderSubstitution (s.Color, s.EventTime, s.In, s.Out, s.Selected, isExpanded, tk, context, backgroundArea, cellArea, state); } else if (item is TimelineEvent) { TimelineEvent p = item as TimelineEvent; RenderPlay (p.Color, p.Miniature, p.Players, p.Selected, p.Description, count, isExpanded, tk, context, backgroundArea, cellArea, state); } else if (item is Player) { RenderPlayer (item as Player, count, isExpanded, tk, context, backgroundArea, cellArea); } else if (item is Playlist) { RenderPlaylist (item as Playlist, count, isExpanded, tk, context, backgroundArea, cellArea); } else if (item is PlaylistPlayElement) { PlaylistPlayElement p = item as PlaylistPlayElement; RenderPlay (p.Play.EventType.Color, p.Miniature, null, p.Selected, p.Description, count, isExpanded, tk, context, backgroundArea, cellArea, state); } else if (item is IPlaylistElement) { IPlaylistElement p = item as IPlaylistElement; RenderPlay (Config.Style.PaletteActive, p.Miniature, null, p.Selected, p.Description, count, isExpanded, tk, context, backgroundArea, cellArea, state); } else { Log.Error ("No renderer for type " + item.GetType ()); } }
/// <summary> /// Processes the request. /// </summary> /// <param name="context">The context.</param> /// <param name="requestContext"></param> public void ProcessRequest(HttpContextBase context, IContext requestContext) { // if transfer is requested, no rendering should be done if (requestContext.TransferRequested) return; string renderTarget; if (requestContext.Response.RenderTargets == null || (!requestContext.Response.RenderTargets.TryGetValue(renderType, out renderTarget) && requestContext.Response.RenderTargets.Count == 0)) { if (requestContext.Response.CurrentReturnType == Bistro.Controllers.ReturnType.Template) throw new ApplicationException("No template specified"); return; } // if the requested render type doesn't have a corresponding target supplied, // default to the first non-empty target available. if (String.IsNullOrEmpty(renderTarget)) renderTarget = requestContext.Response.RenderTargets.First(kvp => !String.IsNullOrEmpty(kvp.Value)).Value; var attrs = (TemplateMappingAttribute[])GetType().GetCustomAttributes(typeof(TemplateMappingAttribute), true); foreach (TemplateMappingAttribute attr in attrs) if (renderTarget.EndsWith(attr.Extension)) { ((Bistro.Http.Module)context.Handler).GetTemplateEngine(EngineType).Render(context, requestContext, renderTarget); return; } }
/*----------------------------------------------------------------------------------------*/ #region Protected Methods /// <summary> /// Resolves the dependency. /// </summary> /// <param name="outerContext">The context in which the dependency was requested.</param> /// <param name="innerContext">The context in which the dependency should be resolved.</param> /// <returns>An object that satisfies the dependency.</returns> protected override object ResolveInstance(IContext outerContext, IContext innerContext) { var selector = outerContext.Binding.Components.BindingSelector; IBinding binding = selector.SelectBinding(innerContext.Service, innerContext); return (binding == null) ? null : binding.Provider; }
public static List<IProject> GetAll(IContext context) { Context ctx = context as Context; if (ctx == null) throw new Exception(typeof(Context).FullName + " expected."); SqlCommand command = new SqlCommand("select * from Project", ctx.Connection); var adapter = new SqlDataAdapter(command); var dataSet = new DataSet(); adapter.Fill(dataSet); var dataTable = dataSet.Tables[0]; List<IProject> projects = new List<IProject>(); foreach (DataRow row in dataTable.Rows) { projects.Add( new Project { ProjectID = Guid.Parse(row["id_project"].ToString()), Name = row["name"].ToString(), Description = row["description"].ToString(), Status = row["status"].ToString(), UserID = Guid.Parse(row["id_user"].ToString()), GitHub_url = row["github_url"].ToString(), Date_start = DateTime.Parse(row["date_start"].ToString()), Date_end = DateTime.Parse(row["date_end"].ToString()) } ); } return projects; }
public override void DrawWithContext(IContext context, double offsetX, double offsetY) { Color backupColor = TextColor; if (IsDefault ()) TextColor = placeholderColor; if (!hidden) base.DrawWithContext (context, offsetX, offsetY); else { string TextBackup = Text; if (Text == placeholder) Text = placeholder; else Text = GetHiddenText (); base.DrawWithContext (context, offsetX, offsetY); Text = TextBackup; } if (Active) { double textWidth = 0; if (cursorPos > 0 && Text.Length != 0) { textWidth = context.GetTextDimensions (hidden? GetHiddenText().Substring(0, cursorPos) : Text.Substring (0, cursorPos), Width, Height).X; } context.DrawLine (new Vector2 (textWidth + offsetX + X + 1, Y + offsetY), new Vector2 (textWidth + offsetX + X + 1, offsetY + Y + Height), new Color (0, 0, 0), 1); } if (IsDefault ()) TextColor = backupColor; }
public override IEnumerable<INodeFactory> GetNodeChildren(IContext context) { foreach (ProjectItem item in _project.ProjectItems) { if (item is Project) { yield return new ProjectCodeModelNodeFactory(item as Project); } var projectItem = item as ProjectItem; if (null != projectItem.SubProject) { yield return new ProjectCodeModelNodeFactory(projectItem.SubProject); } if (null != item.FileCodeModel) { yield return new ProjectItemCodeModelNodeFactory(item); } if (item.Kind == Constants.vsProjectItemKindPhysicalFolder) { yield return new ProjectFolderCodeModelItemNodeFactory(item); } } }
public object Process(object target, IContext context) { IFtpLibrary retval = new FtpLibrary(); if (!string.IsNullOrEmpty(_config.CustomFtpLibraryAssemblyName) && target.GetType().GetInterfaces().Contains(typeof(IFtpLibrary))) { var assemblyFileName = _config.CustomFtpLibraryAssemblyName; if (!assemblyFileName.ToLower().EndsWith(".dll")) { assemblyFileName += ".dll"; } Assembly asm = Assembly.LoadFrom(assemblyFileName); Type pluginType = asm != null ? asm.GetTypes().Where(IsFtpLib).FirstOrDefault() : null; if (pluginType != null) { retval = (IFtpLibrary) Activator.CreateInstance(pluginType); } } return retval; }
public override void Click(double x, double y, IContext context) { if (ContainsPoint(x, y)) { if (OnClick != null) { OnClick(); } Active = true; } else { Active = false; } if (Active == false && Text.Length == 0) Text = placeholder; if (ContainsPoint (x, y)) { if (Active == true && string.Compare (Text, placeholder) == 0) Text = ""; for(int i = 0; i <= Text.Length; i++) { if(context.GetTextDimensions (hidden? GetHiddenText().Substring(0, i) : Text.Substring(0, i), Width, Height).X > x - this.X) { cursorPos = i-1; break; } if (i == Text.Length) cursorPos = i; } } }
public override void Activate( IContext context, InstanceReference reference ) { var messageBroker = context.Kernel.Components.Get<IMessageBroker>(); List<PublicationDirective> publications = context.Plan.GetAll<PublicationDirective>().ToList(); // I don't think this is needed in Ninject2 //if (publications.Count > 0) // context.ShouldTrackInstance = true; foreach ( PublicationDirective publication in publications ) { IMessageChannel channel = messageBroker.GetChannel( publication.Channel ); channel.AddPublication( reference.Instance, publication.Event ); } List<SubscriptionDirective> subscriptions = context.Plan.GetAll<SubscriptionDirective>().ToList(); // I don't think this is needed in Ninject2 //if (subscriptions.Count > 0) // context.ShouldTrackInstance = true; foreach ( SubscriptionDirective subscription in subscriptions ) { IMessageChannel channel = messageBroker.GetChannel( subscription.Channel ); channel.AddSubscription( reference.Instance, subscription.Injector, subscription.Thread ); } }
/// <summary> /// Wraps interfaces in a Castle dynamic proxy /// </summary> /// <param name="target">The target.</param> /// <param name="context">The context.</param> /// <returns></returns> public object Process(object target, IContext context) { QueryTargetType(target.GetType()); var interceptors = context.GetAllInstances<IInterceptor>(); return new ProxyGenerator().CreateInterfaceProxyWithTargetInterface(_targetInterface, target, interceptors.ToArray()); }
public AddExpenseViewModel(IContext context) { _context = context; InitializeCommands(); InitilializeCategories(); }
public void FixtureSetUp() { _stateData = new Hashtable(); _context = MockRepository.GenerateStub<IContext>(); _context.Stub(x => x.HttpContext).Return(MockRepository.GenerateStub<HttpContextBase>()); _context.HttpContext.Stub(x => x.Session).Return(MockRepository.GenerateMock<HttpSessionStateBase>()); _context.HttpContext.Session.Stub(x => x.SyncRoot).Return(new object()); _context.HttpContext.Session.Stub(x => x.Clear()).WhenCalled(invocation => _stateData.Clear()); _context.HttpContext.Session.Stub(x => x.Remove(Arg<string>.Is.Anything)).WhenCalled(invocation => { var key = invocation.Arguments[0]; _stateData.Remove(key); }); _context.HttpContext.Session.Stub(x => x[Arg<string>.Is.Anything]) .Return("") .WhenCalled(invocation => { var key = invocation.Arguments[0]; invocation.ReturnValue = _stateData[key]; }); _context.HttpContext.Session.Stub(x => x[Arg<string>.Is.Anything] = Arg<object>.Is.Anything) .WhenCalled(invocation => { var key = invocation.Arguments[0]; var value = invocation.Arguments[1]; _stateData[key] = value; }); //_context.HttpContext.Session.Expect(x => x[Utils.BuildFullKey<string>(null)]) // .Return("Blah") // .Do(invocation => invocation.ReturnValue = "DEF"); //_context.HttpContext.Session[Utils.BuildFullKey<string>(null)] = _stateData[Utils.BuildFullKey<string>(null)]; //_context.HttpContext.Session["test_key".BuildFullKey<string>()] = _stateData["test_key".BuildFullKey<string>()]; }
public static UserSession Find(string sid, IContext ctx) { Services.Log("UserSession.Find({0})", sid); long ver = 0; Buffer b = KeyValueStore.FindBuffer(sid, out ver); UserSession ret = null; if (b == null) { return null; } ret = Helpers.MarshalToObject<UserSession>(b); ret.lastVersion = ver; IPAddress addr = ctx.PeerAddress; if (ret.peerAddress.ToString() != addr.ToString()) { Console.WriteLine("Session {2} bound IP address changed: {0} to {1}", ret.peerAddress, addr, ret.sid); ret.Invalidate(ctx); return null; } if (ret.expiryTimeTicks < DateTime.Now.Ticks) { Console.WriteLine("Session {0} expired", ret.sid); ret.Invalidate(ctx); return null; } return ret; }
public void Dispose() { if (_Context != null) _Context.Dispose(); _Context = null; }
public StringResult Page(XrcUrl url, object parameters = null, IContext callerContext = null) { try { var parentRequest = callerContext == null ? null : callerContext.Request; var parentResponse = callerContext == null ? null : callerContext.Response; using (var stream = new MemoryStream()) { var request = new XrcRequest(url, parentRequest: parentRequest); var response = new XrcResponse(stream, parentResponse: parentResponse); var context = new Context(request, response); context.CallerContext = callerContext; AddParameters(context, parameters); ProcessRequest(context); context.CheckResponse(); response.Flush(); stream.Seek(0, SeekOrigin.Begin); using (StreamReader reader = new StreamReader(stream, response.ContentEncoding)) { return new StringResult(reader.ReadToEnd(), response.ContentEncoding, response.ContentType); } } } catch (Exception ex) { throw new PageException(url.AppRelaviteUrl, ex); } }
private static bool TryHandleAsStaticContent(IContext context) { var absolutePath = context.Request.Url.AbsolutePath; string file; if (SimpleWeb.Configuration.PublicFileMappings.ContainsKey(absolutePath)) { file = SimpleWeb.Environment.PathUtility.MapPath(SimpleWeb.Configuration.PublicFileMappings[absolutePath]); } else if ( SimpleWeb.Configuration.PublicFolders.Any( folder => absolutePath.StartsWith(folder + "/", StringComparison.OrdinalIgnoreCase))) { file = SimpleWeb.Environment.PathUtility.MapPath(absolutePath); } else { return false; } if (!File.Exists(file)) return false; context.Response.Status = Status.OK; context.Response.SetContentType(GetContentType(file, context.Request.GetAccept())); context.Response.SetContentLength(new FileInfo(file).Length); context.Response.WriteFunction = (stream) => { using (var fileStream = File.OpenRead(file)) { fileStream.CopyTo(stream); return TaskHelper.Completed(); } }; return true; }
public static IObservable<String> Title(IContext context, String url) { return _webRequest .Request(url, x => x) .Select(GetTitle) ; }
public virtual IPreparedComparison PrepareComparison(IContext context, object source ) { MappedIDPair sourceIDPair = (MappedIDPair)source; int sourceID = sourceIDPair.Orig(); return new _IPreparedComparison_50(sourceID); }
public TexturedExtensibleRectangle(IContext context, Vector2I size, Texture texture, int fixedBorderRadius) { DeviceContext = context.DirectX.DeviceContext; _shader = context.Shaders.Get<TextureShader>(); _texture = texture; _fixedBorderRadius = fixedBorderRadius; const int vertexCount = 16; _vertices = new VertexDefinition.PositionTexture[vertexCount]; VertexBuffer = Buffer.Create(context.DirectX.Device, _vertices, new BufferDescription { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<VertexDefinition.PositionTexture>() * vertexCount, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }); IndexCount = 54; uint[] indices = new uint[IndexCount]; for(uint i=0; i< 3; i++) for (uint j = 0; j < 3; j++) { indices[(i * 3 + j) * 6] = (i + 1) * 4 + j + 1; indices[(i * 3 + j) * 6 + 1] = i * 4 + j + 1; indices[(i * 3 + j) * 6 + 2] = i * 4 + j; indices[(i * 3 + j) * 6 + 3] = (i + 1) * 4 + j; indices[(i * 3 + j) * 6 + 4] = (i + 1) * 4 + j + 1; indices[(i * 3 + j) * 6 + 5] = i * 4 + j; } IndexBuffer = Buffer.Create(context.DirectX.Device, BindFlags.IndexBuffer, indices); Size = size; }
public void before() { context = new Context(); injector = context.injector; injector.Map<IDirectCommandMap>().ToType<DirectCommandMap>(); subject = injector.GetInstance<IDirectCommandMap>() as DirectCommandMap; }
public object Apply(IContext context, IList <object> arguments, IDictionary <string, object> namedArguments) { this.Name = (string)arguments[0]; this.Length = this.Name.Length; return(this.Length); }
public ObjectProperties(IContext context, object obj) { this.context = context; this.obj = obj; this.ClassMap = context.DomainMap.MustGetClassMap(obj.GetType()); }
protected override ICollector <GameEntity> GetTrigger(IContext <GameEntity> context) { return(context.CreateCollector(new TriggerOnEvent <GameEntity>(GameMatcher.CharacterVelocity, GroupEvent.Added))); }
/// <summary> /// Creates all map specific <see cref="MonsterDefinition"/>s and adds them to the gameConfiguration. /// </summary> /// <param name="context">The persistence context.</param> /// <param name="gameConfiguration">The game configuration.</param> /// <remarks> /// Can be extracted from Monsters.txt by Regex: (?m)^(\d+)\t1\t"(.*?)"\t*?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+)\t?(\d+).*?$ /// <![CDATA[Replace by: {\r\n var monster = context.CreateNew<MonsterDefinition>();\r\n gameConfiguration.Monsters.Add(monster);\r\n monster.Number = $1;\r\n monster.Designation = "$2";\r\n monster.MoveRange = $12;\r\n monster.AttackRange = $14;\r\n monster.ViewRange = $15;\r\n monster.MoveDelay = new TimeSpan\($16 * TimeSpan.TicksPerMillisecond\);\r\n monster.AttackDelay = new TimeSpan\($17 * TimeSpan.TicksPerMillisecond\);\r\n monster.RespawnDelay = new TimeSpan\($18 * TimeSpan.TicksPerSecond\);\r\n monster.Attribute = $19;\r\n monster.NumberOfMaximumItemDrops = 1;\r\n new Dictionary<AttributeDefinition, float>\r\n {\r\n { Stats.Level, $3 },\r\n { Stats.MaximumHealth, $4 },\r\n { Stats.MinimumPhysBaseDmg, $6 },\r\n { Stats.MaximumPhysBaseDmg, $7 },\r\n { Stats.DefenseBase, $8 },\r\n { Stats.AttackRatePvm, $10 },\r\n { Stats.DefenseRatePvm, $11 },\r\n { Stats.WindResistance, $23 },\r\n { Stats.PoisonResistance, $24 },\r\n { Stats.IceResistance, $25 },\r\n { Stats.WaterResistance, $26 },\r\n { Stats.FireResistance, $27 },\r\n }.Select(kvp =>\r\n {\r\n var attribute = persistenceContextProvider.CreateNew<MonsterAttribute>();\r\n attribute.AttributeDefinition = gameConfiguration.Attributes.First(a => a == kvp.Key);\r\n attribute.Value = kvp.Value;\r\n return attribute;\r\n }).ToList().ForEach(monster.Attributes.Add);\r\n }\r\n]]> /// </remarks> protected abstract void CreateMonsters(IContext context, GameConfiguration gameConfiguration);
/// <summary> /// Creates all monster spawn areas. /// </summary> /// <param name="context">The persistence context.</param> /// <param name="mapDefinition">The game map definition.</param> /// <param name="gameConfiguration">The game configuration.</param> /// <returns> /// The spawn areas of the game map. /// </returns> /// <remarks> /// Can be extracted from MonsterSetBase.txt by Regex: /// Search (single): (?m)^(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+((-|)\d+).*?$ /// Replace by (single): <![CDATA[yield return this.CreateMonsterSpawn(context, mapDefinition, npcDictionary[$1], 1, $6, SpawnTrigger.Automatic, $4, $4, $5, $5);]]> /// Search (multiple): (?m)^(\d+)\t*?(\d+)\t+?(\d+)\t+?(\d+)\t+?(\d+)\t+?(\d+)\t+?(\d+)\t+?(-*\d+)\t+?(\d+).*?$ /// Replace by (multiple): <![CDATA[yield return this.CreateMonsterSpawn(context, mapDefinition, npcDictionary[$1], $9, 0, SpawnTrigger.Automatic, $4, $6, $5, $7);]]> /// </remarks> protected abstract IEnumerable <MonsterSpawnArea> CreateSpawns(IContext context, GameMapDefinition mapDefinition, GameConfiguration gameConfiguration);
/// <summary> /// This constructor creates an instance and takes over the context assigned to it. /// </summary> /// <param name="context">Context assigned to the controller.</param> public AlbumController(IContext context) : base(context) { }
public SessionController(IContext context) { _context = context; }
public override object Evaluate(IContext context) { return(this.Apply(this.Expression.Evaluate(context), context)); }
public virtual void OnDetachFromContext(IContext context) { UnregisterEvents(); EntityManager = null; EventManager = null; }
public UtcNowTransform(IContext context) : base(context) { }
public void Close(IContext context) { }
public void Query(IContext context) { throw new NotSupportedException(); }
public void Query(IContext context) { }
public void Open(IContext context) { context.State = new OpenState(); }
/// <summary> /// Activates the <see cref="DbSet{T}"/>. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The reference to the <see cref="DbSet{T}"/>.</param> protected abstract void ActivateDbSet(IContext context, InstanceReference reference);
public void Close(IContext context) { context.State = new CloseState(); }
/// <summary> /// Raised by the provider when a new request is received from the user. /// </summary> /// <param name="asyncResult"></param> private void GetContextHandler(IAsyncResult asyncResult) { long requestReceivedEventArgsId = -1; if (Provider.IsListening) { bool providerIsStable = true; IContext context = null; try { try { context = Provider.EndGetContext(asyncResult); } catch (HttpListenerException ex) { // These are just discarded, they're usually disconnections by the user made before we can process the request Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); } catch (ObjectDisposedException ex) { // These are usually thrown during program shutdown, after the provider has gone away but while requests are outstanding Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); providerIsStable = false; } catch (Exception ex) { Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); OnExceptionCaught(new EventArgs <Exception>(ex)); providerIsStable = false; } try { if (providerIsStable) { Provider.BeginGetContext(GetContextHandler); } } catch (HttpListenerException ex) { // These can be thrown if the server is taken offline between the EndGetContext above and this BeginGetContext Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); context = null; } catch (ObjectDisposedException ex) { // These are usually thrown during program shutdown for the same reasons that EndGetContext can throw them Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); context = null; } catch (InvalidOperationException ex) { // These are thrown when the provider is taken offline between the check above for Provider.IsListening and // the call to BeginGetContext Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); context = null; } catch (Exception ex) { Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); OnExceptionCaught(new EventArgs <Exception>(ex)); context = null; } if (context != null) { try { var requestArgs = new RequestReceivedEventArgs(context.Request, context.Response, Root); requestReceivedEventArgsId = requestArgs.UniqueId; if (IsRestricted(requestArgs)) { context.Response.StatusCode = HttpStatusCode.Forbidden; } else if (Authenticated(context, requestArgs)) { var startTime = Provider.UtcNow; OnBeforeRequestReceived(requestArgs); OnRequestReceived(requestArgs); OnAfterRequestReceived(requestArgs); if (!requestArgs.Handled) { context.Response.StatusCode = HttpStatusCode.NotFound; } var fullClientAddress = String.Format("{0}:{1}", requestArgs.ClientAddress, context.Request.RemoteEndPoint.Port); var responseArgs = new ResponseSentEventArgs(requestArgs.PathAndFile, fullClientAddress, requestArgs.ClientAddress, context.Response.ContentLength, requestArgs.Classification, context.Request, (int)context.Response.StatusCode, (int)(Provider.UtcNow - startTime).TotalMilliseconds, context.BasicUserName); OnResponseSent(responseArgs); } } catch (HttpListenerException ex) { // These are usually thrown when the browser disconnects while the event handler tries to send data to it. You can get a lot // of these, we just discard them to prevent them spamming logs or the display with messages we can't do anything about. Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); } catch (Exception ex) { Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); OnExceptionCaught(new EventArgs <Exception>(new RequestException(context.Request, ex))); } try { context.Response.Close(); } catch (Exception ex) { // We can get a lot of exceptions from closing the stream if the client browser has disconnected, it's exception spam. Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); } } } finally { try { if (context != null && context.Response != null) { context.Response.Dispose(); } } catch (Exception ex) { Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception while disposing of response: {0}", ex.ToString())); } } try { if (requestReceivedEventArgsId != -1) { OnRequestFinished(new EventArgs <long>(requestReceivedEventArgsId)); } } catch (Exception ex) { var log = Factory.Singleton.ResolveSingleton <ILog>(); log.WriteLine("Caught exception in RequestFinished event handler: {0}", ex); } } }
/// <summary> /// Authenticates the request from the browser. /// </summary> /// <param name="context"></param> /// <param name="requestArgs"></param> /// <returns></returns> private bool Authenticated(IContext context, RequestReceivedEventArgs requestArgs) { bool result = false; var authenticationScheme = AuthenticationScheme; var isAdministratorPath = IsAdministratorPath(requestArgs); if (isAdministratorPath) { authenticationScheme = AuthenticationSchemes.Basic; } switch (authenticationScheme) { case AuthenticationSchemes.None: case AuthenticationSchemes.Anonymous: if (isAdministratorPath) { throw new InvalidOperationException("Anonymous access to administrator paths is not supported"); } result = true; break; case AuthenticationSchemes.Basic: bool useCache = CacheCredentials; if (useCache && context.BasicUserName != null) { CachedCredential cachedCredential; if (_AuthenticatedUserCache.TryGetValue(context.BasicUserName, out cachedCredential)) { result = context.BasicPassword == cachedCredential.Password; if (result) { result = !isAdministratorPath || cachedCredential.IsAdministrator; } } } if (!result) { var args = new AuthenticationRequiredEventArgs(context.BasicUserName, context.BasicPassword); OnAuthenticationRequired(args); result = args.IsAuthenticated && (!isAdministratorPath || args.IsAdministrator); if (result) { if (useCache && args.User != null) { var cachedCredential = new CachedCredential() { IsAdministrator = args.IsAdministrator, Password = context.BasicPassword, }; _AuthenticatedUserCache.Add(context.BasicUserName, cachedCredential); } } else { var failedLogin = _FailedLoginAttempts.GetAndRefreshOrCreate(context.Request.RemoteEndPoint.Address, (unused) => new FailedLogin()); var sameCredentials = context.BasicUserName == failedLogin.User && context.BasicPassword == failedLogin.Password; failedLogin.User = context.BasicUserName; failedLogin.Password = context.BasicPassword; if (!sameCredentials) { if (failedLogin.Attempts < int.MaxValue) { ++failedLogin.Attempts; } if (failedLogin.Attempts > 2) { var pauseMilliseconds = (Math.Min(failedLogin.Attempts, 14) - 2) * 5000; Thread.Sleep(pauseMilliseconds); } } context.Response.StatusCode = HttpStatusCode.Unauthorized; context.Response.AddHeader("WWW-Authenticate", String.Format(@"Basic Realm=""{0}""", Provider.ListenerRealm)); } } if (result) { requestArgs.UserName = context.BasicUserName; } break; default: throw new NotImplementedException(); } return(result); }
public UniformBufferSugar(IContext glContext) { buffer = glContext.Create.Buffer(BufferTarget.Uniform, PtrHelper.SizeOf <T>(), BufferUsageHint.DynamicDraw); }
public void Bind(IContext glContext, int index) { glContext.Bindings.Buffers.UniformIndexed[index].Set(buffer); }
public static GitVersionRunner Init(IContext context) { return(new GitVersionRunner(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools, context.Log)); }
public AccountController(IContext context) { _context = context; }
public HandleGroundedJumpStateSystem(IContext <GameEntity> context) : base(context) { }
protected override ICollector <GameEntity> GetTrigger(IContext <GameEntity> context) { return(context.CreateCollector(GameMatcher.Position)); }
/*----------------------------------------------------------------------------------------*/ /// <summary> /// Retrieves an instance of the specified type from the kernel, within an existing context. /// </summary> /// <param name="type">The type to retrieve.</param> /// <param name="context">The context under which to resolve the type's binding.</param> /// <returns>An instance of the requested type.</returns> public object Get(Type type, IContext context) { return DoResolve(type, context); }
public object Apply(IContext context, IList <object> arguments, IDictionary <string, object> namedArguments) { return((int)arguments[0] + (int)arguments[1]); }
/*----------------------------------------------------------------------------------------*/ /// <summary> /// Retrieves an instance of the specified type from the kernel, within an existing context. /// </summary> /// <typeparam name="T">The type to retrieve.</typeparam> /// <param name="context">The context under which to resolve the type's binding.</param> /// <returns>An instance of the requested type.</returns> public T Get<T>(IContext context) { return (T)DoResolve(typeof(T), context); }
public object Apply(IContext context, IList <object> arguments, IDictionary <string, object> namedArguments) { this.X = (int)arguments[0]; this.Y = (int)arguments[1]; return(null); }
/*----------------------------------------------------------------------------------------*/ /// <summary> /// Injects an existing instance of a service. /// </summary> /// <param name="instance">The existing instance to inject.</param> /// <param name="context">The context in which the instance should be injected.</param> protected abstract void DoInject(object instance, IContext context);
public object Apply(IContext context, IList <object> arguments, IDictionary <string, object> namedArguments) { this.WasInvoked = true; return(null); }