ict.ken.be

 

Posts in Category: .Net

Checklist for new nuget creation 

Categories: .Net

We use this checklist whenever we need to setup a new nuget package, that way it will include tests, coverage, labelling and deployment.

  • Create repository on server: hg init c:\Respository\Nugets\ken.X
  • Clone repository to local machine using TortoiseHg
  • Create new Project: Templates - Windows - Class Library - Create directory for Solution - ken.X
  • Close solution and move everything up one directory (cause of clone) - ken.X.sln
  • Add ken.Tools nuget package to solution
  • Create default hg ignore file with *.suo *.user bin debug packages/ tools/
  • Add new Class Library Project for testing: ken.X.Tests + add ken.XUnit
  • Solution - Configuration Manager - New - 'Publish' copy from Release and create project configurations
  • Update so output directory for Publish is release folder in ken.X.csproj
  • Update so output directory for Publish is release folder in ken.X.Tests.csproj
  • Add Import Project for build.config in ken.X.Tests.csproj (<Import Project="..\tools\build.config" />)
  • Update assembly information for ken.X.Tests
  • Update assembly information for ken.X and add InternalsVisible for ken.X.Tests
  • Add nuspec file to ken.X
  • Rebuild the test project with publish configuration to deploy the nuget.

ASP.Net Don't do that, do this! 

Categories: .Net

By Damian Edwards

  • Avoid control adapters use css media queries instead
  • Avoid style properties on controls use css stylesheets
  • Avoid page & control callbacks use updatepanel, ajax, webapi, ...
  • Avoid capability detection use client-side feature detection such as Modernizr
  • Avoid request validation use :
    Validate well-formedness of data on the way in (is this submitted value using the correct scheme)
    Encode data on the way out (@foo, <%:foo%>, JavaScriptStringEncode, UrlEncode, ...)
    Do not us <%=, <%# and us @foo.HtmlString() when needed
  • Avoid cookieless forms auth & session use require cookies and secure ssl cookies
  • Make sure EnableViewStateMac = true (must be always on even when not using viewstate)
  • Do not use Medium Trust or any other trust level as a security boundry, place untrusted applications into their own application pools, run each application pool under its own unique identity. http://support.microsoft.com/kb/2698981
  • Do not use <appSettings> to disable our security (only on webfarm roll out) http://msdn.microsoft.com/en-us/library/hh975440.aspx
  • Do not use UrlPathEncode use UrlEncode and sanitize urls with System.Uri
  • Use native IIS modules if you need to hook into PreSendRequestHeaders & PreSendRequestContent, do not use them from within managed IHttpModule instances
  • Do not use async void for page lifecycle events, use Page.RegisterAsyncTask() and set <httpRuntime targetFramework="4.5" /> if using Task
  • Avoid timers, ThreadPool.QUWI as we might tear the AppDomain out from under you.
    Moving to a Windows Service or Worker Role for maximum reliability.
    Using WebBackgrounder if the work needs to be done in-proc: http://nuget.org/packages/WebBackgrounder
  • Avoid reading Request.Form/InputStream before the HandlerExecute event, instead deffer to HandlerExecute.
    Use Request.GetBufferlessInputStream(), Request.Form and InputStream unavailable
    Use GetBufferedInputStream() to get a copy, Request.Form and InputStream available
  • Response.Redirect(string) calls Response.End(), which aborts the current thread in synchronous requests and halts code execution. For asynchronous handlers, Response.End() does not abort the current thread, so code execution continues. If you need to redirect the response, use the method appropriate for the framework you're using. For example, in MVC return a RedirectResult instead of calling Response.Redirect.
  • Do not use EnableViewState but set ViewStateMode="Disabled" at the page directive level and set ViewStateMode="Enabled" only on controls that require state
  • Do not use SqlMembershipProvider, use UniversalProviders which work with all databases that Entity Framework supports including SQL, Azure SQL, SQL Compact, MySQL and more...
  • Avoid long-running requests because asp.net will forcibly release the session object lock at a potentially inopportune time. If needed use WebSockets as it has much lower per-request memory overhead.

AOP in .Net 

Categories: .Net

There are plenty of aop frameworks for .Net but it seems that most of them are not that stable. If you really want to go AOP all the way, are willing to pay the money and can except that you get outgoing pings  on compilations, then you should go for PostSharp (post-compilation). 

I think dynamic proxy of Castle (runtime) is a very nice alternative and not that much slower actually.

https://github.com/KenVanGilbergen/ken.Spikes.Aspects

edit: Just added some testing with SheepAspect, works very nice.

SignalR - Notes 

Categories: .Net Javascript

Real-time Web & Push Services with Hubs
by Christian Weyer (christian.weyer@thinktecture.com)
Developers of SignalR on https://jabbr.net

Push Services pattern (models a service that) 

  • accepts incoming connections from callers
  • is able to push data down to callers
  • abstracts from communication nitty-gritty details
  • consumers send to push service
  • push service notifies consumers
  • external events (Db, Message Queue, ...) trigger push service

HTTP is the protocol

  • Periodic Polling
  • Long Polling (http streaming/comet) -> server only responds when there is data
  • Forever Frame (connection within an iframe)
  • Server-Sent Events (SSE)
  • Web Sockets (only Windows 8/Server 2012, network considerations/blockings)

Hubs

  • public methods are callable from the outside
  • send messages to clients by invoking client-side methods
  • [HubName("chat")]
  • Context holds connection- and request-specific information
  • ConnectionId, Request, Headers, RequestCookies, QueryString, User
  • First register the hubs and then add your other routes.
  • Target method with parameters is dynamically 'injected' into code path, serialized, and embedded into protocol response
  • Groups are not persisted on the server
  • We need to keep track of what connections are in chat groups
  • No automatic group count 
Clients.Caller.newMessage(message);
Clients.Client(Context.ConnectionId).newMessage(message);
Clients.All.newMessage(message);
Clients.Others.newMessage(message);
Clients.AllExcept(Context.ConnectionId).newMessage(message);

Groups.Add(Context.ConnectionId, room);
Clients.Group(room).newMessage(msg);

public override Task OnConnected() {}
public override Task OnDisconnected() {}
public override Task OnReconnected() {}

// Sending data from outside a hub, retrieve hub context via dependency resolver
private void SendMonitorData(string eventType, string connection)
{
var context = GlobalHost.ConnectionManager.GetHubContext<MonitorHub>();
context.Clients.All.newEvent(eventType, connection);
}

Clients

  • .NET4.0+, WinRT, Windows Phone 8, Silverlight 5, jQuery, C++, iOS native, iOS via Mono, Android via Mono
  • /signalr/hubs is the dynamic proxy contract
  • use signalr.exe ghp /url:http://localhost:31373 tool to create a static proxy

Javascript with proxy

 $.connection.hub.logging = true;
chat = $.connection.chat
$.connection.hub.start({ transport:'longPolling' });
$.connection.hub.connectionSlow = onConnectionSlow;

Javascript without proxy

var connection = $.hubConnection();
var proxy = connection.createHubProxy('chat');
proxy.on('newMessage', onNewMessage);
connection.start();
proxy.invoke('sendMessage', $('#message').val());

.Net

var hubConnection = new HubConnection("http://localhost/ps");
var chat = hubConnection.CreateHubProxy("chat");
chat.On<string>("newMessage", msg => messages.Invoke(new Action(() => messages.Items.Add(msg));
hubConnection.Start().Wait();
// Opened, Closed, Error, Received, Reconnected, Reconnecting, StateChanged

Hosting

OWIN (Open Web Server Interface for .Net) - http://owin.org
Katana project - http://katanaproject.codeplex.com

  • Application delegate (AppFunc) var AppFunc = Func<IDictionary<string, object>, Task>;
  • Environment dictionary
  • ASP.Net hosting sits on top of OWIN
  • Self-hosting
  • Microsoft.Owin.Hosting aka Katana
  • Microsoft.Owin.Host.HttpListener
// process user needs http.sys permissions on the url namespace
public void Configuration(IAppBuilder app)
{
var a = Assembly.LoadFrom("Services.dll");
app.MapHubs(new HubConfiguration { EnableCrossDomain = true });
}

using(WebApplication.Start<Startup>("http://localhost:6789")
{
Console.WriteLine("Hubs running...");
Console.ReadLine();
}

// jQuery client needs to explicitly set connection url
$.connection.hub.url = "http://localhost:6789/signalr";

Azure

  • Which server instance handles the client request?
  • Which instance pushes?

Other aspects

  • Use SignalR message bus
  • SignalR extensible architecture
  • Persistent connections
  • Scale-Out
  • WebApi Integration
  • Security

Removing X-Powered-By ASP.Net and other version headers 

Categories: .Net IIS

Most likely you do not want these headers to be displayed in your responses:

  • Server Microsoft-IIS/7.5
  • X-AspNetMvc-Version 3.0
  • X-AspNet-Version 4.0.303319
  • X-Powered-By ASP.NET

Removing X-AspNet-Version

In web.config add this:

<system.web>
<httpRuntime enableVersionHeader="false"/>

Removing X-AspNetMvc-Version

In Global.asax.cs add this line:

protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
}

Removing or changing Server

In Global.asax.cs add this:

protected void Application_PreSendRequestHeaders()
{
//Response.Headers.Remove("Server");
Response.Headers.Set("Server","FooServer");
Response.Headers.Remove("X-AspNet-Version"); //alternative to above solution
Response.Headers.Remove("X-AspNetMvc-Version"); //alternative to above solution
}

Removing or changing X-Powered-By

IIS 7 - You can also remove the X-Powered-By header by including these lines to the <system.webServer> element:

<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>

or manually go to IIS7 Management Console and open HTTP Response Headers

Page 2 of 5 << < 1 2 3 4 5 > >>