If you ever find yourself in need of comparing hour, minutes and seconds in a database table stored as integers to say the hour and minute of the day, you can do something like this very simple.
static void Main(string[] args)
{
bool timeOfTheDayEqual= false;
int hours = 8;
int minutes = 52;
TimeSpan scheduledStartTime = new TimeSpan(hours, minutes, 0);
TimeSpan timeNow = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0);
if (timeNow == scheduledStartTime)
{
timeOfTheDayEqual = true;
}
Console.Write(timeOfTheDayEqual);
Console.ReadKey();
}
This comparison of the TimeSpan values will always be accurate.
Wednesday, April 29, 2015
Saturday, April 18, 2015
How to create your own Katana middleware component - at the metal
//using a C like typedef alias for the Func() inside the class file
using AppFunc = Func<IDictionary<string,object>,Task>();
In the Configuration method of Statup, use my OWIN Katana component
public void Configuration(IAppBuilder app)
{
app.Use<MyOwinComponent>();
}
// My lowest level OWIN component
public class MyOwinComponent
{
//Required to pass processing on to the next OWIN component
AppFunc _next;
public MyOwinComponent(AppFunc next)
{
_next = next;
}
// If not using await, remove the async keyword
//This method should match the AppFunc signature
public async Task Invoke(IDictionary<string,object> environment)
{
var response = environment["owin.ResponseBody"] as Stream;
using( var writer = new StreamWriter(response))
{
return await writer.WriteAsync("Hello from my Owin Component!");
}
//Example await next component and pass along the dictionary
// await _next(environment);
}
}
We can also add syntactic sugar to this so we can specify in configuration method as
app.UseMyOwinComponent();
by creating an extension method like so
public static class AppBuilderExtensions
{
public static void UseMyOwinComponent(this IAppBuilder app)
{
app.Use<MyOwinComponent>();
}
}
******************************************************************
NOTE: Katana provides higher abstractions using app.Run or app.Use with its overloaded functions to write our middleware components, and we should actually use that.
For instance, using just a lambda expression
app.Use( async (environment, next) =>
{
Console.Write("Requesting: " + environment.Request.Path);
await next();
Console.Write("Response: " + environment.Response.StatusCode);
}
app.UseMyOwinComponent();
How to create a Katana WebServer in a console application
Create a new Console app and add these 2 packages:
install-package Microsoft.Owin.Hosting
install-package Microsoft.Owin.Host.HttpListener
Add a class called Startup and a configuration method that takes an IAppBuilder interface. IAppBuilder is in the Owin namespace.
public class Startup
{
public void Configuration(IAppBuilder app)
{
//Add other features from other Katana components through
//the Use extension method. For instance, this below method
// asfter installing the Microsoft.Owin.Diagnostics package
// can be used instead of app.Run() to start a Web server
//with a Welcome Page.
//app.UseWelcomePage();
//Process all requests. Returns a task and is a wrapper to calling AppFunc.
// app.Run can be used to dynamically add your middleware as done here.
app.Run(ctx =>
{
return ctx.Response.WriteAsync("Hello Katana!");
});
}
}
The IAppBuilder interface has methods that allows us to configure and respond to HTTP requests. As we add additional Katana components (nuget packages), we may see additional extension methods that we can use to turn on to use additional Katana features.
Run() takes an OwinContext which has an Environment property, and returns a Task. This property is a Dictionary<string,object> and has all the information about the request - the Http Headers, cookies, the URL path, the Verb that was used etc. This is the core abstraction of OWIN and makes it very simple to add Owin components and middleware as needed in the request processing pipeline. Does away with all the bells and whistles with the conventional ASP.NET and System.Web assembly processing pipeline.
To start the web server on say port 8080, use a Katana component called WebApp to run this Startup class as below:
public static Main(string[] args)
{
string url = "http://localhost:8080";
using (WebApp.Start<Startup>(uri)
{
Console.WriteLine("Web Server started....");
Console.ReadKey();
Console.WriteLine("Web Server ended...");
}
}
Reference: This example has been taken from the Scott Allen Pluralsight course on OWIN.
install-package Microsoft.Owin.Hosting
install-package Microsoft.Owin.Host.HttpListener
Add a class called Startup and a configuration method that takes an IAppBuilder interface. IAppBuilder is in the Owin namespace.
public class Startup
{
public void Configuration(IAppBuilder app)
{
//Add other features from other Katana components through
//the Use extension method. For instance, this below method
// asfter installing the Microsoft.Owin.Diagnostics package
// can be used instead of app.Run() to start a Web server
//with a Welcome Page.
//app.UseWelcomePage();
//Process all requests. Returns a task and is a wrapper to calling AppFunc.
// app.Run can be used to dynamically add your middleware as done here.
app.Run(ctx =>
{
return ctx.Response.WriteAsync("Hello Katana!");
});
}
}
The IAppBuilder interface has methods that allows us to configure and respond to HTTP requests. As we add additional Katana components (nuget packages), we may see additional extension methods that we can use to turn on to use additional Katana features.
Run() takes an OwinContext which has an Environment property, and returns a Task. This property is a Dictionary<string,object> and has all the information about the request - the Http Headers, cookies, the URL path, the Verb that was used etc. This is the core abstraction of OWIN and makes it very simple to add Owin components and middleware as needed in the request processing pipeline. Does away with all the bells and whistles with the conventional ASP.NET and System.Web assembly processing pipeline.
To start the web server on say port 8080, use a Katana component called WebApp to run this Startup class as below:
public static Main(string[] args)
{
string url = "http://localhost:8080";
using (WebApp.Start<Startup>(uri)
{
Console.WriteLine("Web Server started....");
Console.ReadKey();
Console.WriteLine("Web Server ended...");
}
}
Reference: This example has been taken from the Scott Allen Pluralsight course on OWIN.
Katana and OWIN Middleware
Katana is the Microsoft implementation of OWIN that appeared with Visual Studio 2013 (MVC 5).
Prior to Katana, ASP.NET has been built on top of IIS (inetinfo.exe) that provides the hosting and infrastructure features for Web applications. It runs with the SYSTEM account on the Web Server. IIS itself has been around longer than ASP.NET. To make it work with ASP.NET it uses aspnet_isapi.DLL that communicates with an ASP.NET worker process using named pipes.
IIS 7+ uses aspnet_wp.exe which runs with the ASPNET account and which is responsible for hosting the different application domains for ASP.NET.
Over the years ASP.NET and IIS have evolved to provide a wide range of features from authentication to hashing, encryption, compression, caching, configuration, web sockets, logging, diagnostics etc. Even within a specific feature like diagnostics there are multiple methods like logging, request monitoring, tracing et al. NOT EVERYONE needs all these features - and that is the whole idea behind the OWIN middleware framework and Katana.
As HTML5 standards continues to mature, we are seeing a shift in Web Architecture. More and more processing is happening client side rather than on the server. Instead of the Server doing heavy processing and generating all the html, it is responding to only ajax requests that sends out just raw data! This is also true for mobile applications that consume these data with their native apps.The end result is developers are looking for a fast, efficient, lightweight and extensible host for the Web applications and Web Services, particularly with cloud based services where you pay for every byte and CPU cycles.
Like Linkedin does using Node.JS and HTML5 to build better and faster apps. It is easy to add a package to Node and make it run a lean and mean web server using a fraction of traditional resources on server side. It is also easier to scale because it consumes just the resources it needs.
Katana follows this architecture unlike ASP.NET MVC which relies on one giant core System.Web assembly on every project. Instead of one large assembly, Katana features are highly modular and componentized so you can add only the features you need for your project.
Katana allows you to create and plug in your middleware components by being agnostic of whether they are hosted in a console app or in IIS etc. More and more middleware components like Cookie Authentication have been developed for Katana moving away from dependence on ASP.NET MVC modules and handlers and filters etc .
To use and host your Katana custom components in IIS, create the component with the Startup class as a DLL with its build target pointing at the /bin folder in your project or solution. For more information and Katana components, look at the Katana open source project in codeplex.
To learn more about Katana, there's an excellent course by Scott Allen @pluralsight
http://www.pluralsight.com/courses/aspdotnet-mvc5-fundamentals
Prior to Katana, ASP.NET has been built on top of IIS (inetinfo.exe) that provides the hosting and infrastructure features for Web applications. It runs with the SYSTEM account on the Web Server. IIS itself has been around longer than ASP.NET. To make it work with ASP.NET it uses aspnet_isapi.DLL that communicates with an ASP.NET worker process using named pipes.
IIS 7+ uses aspnet_wp.exe which runs with the ASPNET account and which is responsible for hosting the different application domains for ASP.NET.
Over the years ASP.NET and IIS have evolved to provide a wide range of features from authentication to hashing, encryption, compression, caching, configuration, web sockets, logging, diagnostics etc. Even within a specific feature like diagnostics there are multiple methods like logging, request monitoring, tracing et al. NOT EVERYONE needs all these features - and that is the whole idea behind the OWIN middleware framework and Katana.
As HTML5 standards continues to mature, we are seeing a shift in Web Architecture. More and more processing is happening client side rather than on the server. Instead of the Server doing heavy processing and generating all the html, it is responding to only ajax requests that sends out just raw data! This is also true for mobile applications that consume these data with their native apps.The end result is developers are looking for a fast, efficient, lightweight and extensible host for the Web applications and Web Services, particularly with cloud based services where you pay for every byte and CPU cycles.
Like Linkedin does using Node.JS and HTML5 to build better and faster apps. It is easy to add a package to Node and make it run a lean and mean web server using a fraction of traditional resources on server side. It is also easier to scale because it consumes just the resources it needs.
Katana follows this architecture unlike ASP.NET MVC which relies on one giant core System.Web assembly on every project. Instead of one large assembly, Katana features are highly modular and componentized so you can add only the features you need for your project.
Katana allows you to create and plug in your middleware components by being agnostic of whether they are hosted in a console app or in IIS etc. More and more middleware components like Cookie Authentication have been developed for Katana moving away from dependence on ASP.NET MVC modules and handlers and filters etc .
To use and host your Katana custom components in IIS, create the component with the Startup class as a DLL with its build target pointing at the /bin folder in your project or solution. For more information and Katana components, look at the Katana open source project in codeplex.
To learn more about Katana, there's an excellent course by Scott Allen @pluralsight
http://www.pluralsight.com/courses/aspdotnet-mvc5-fundamentals
Friday, April 3, 2015
ASP.NET Async Tips
- Avoid using background threads in ASP.NET as there are no background threads on servers unlike a WPF or Console application. For the latter, it may be a good idea to keep the async work separate from the main UI thread to avoid locking up the UI. But there is no separate UI thread for Web Applications to lock up!
- Doing so gives up the current thread for processing other requests, but you end up taking another thread from the same thread pool, only adding up the cost for a thread swap for no reason. All threads come from the same pool used to serve requests. Moving to another thread just adds cost.
- If indeed you need a real background thread legitimate reason, consider using SynchronizationContext.Post which can be used in a thread safe manner.
- Avoid using Task.Wait in ASP.NET like the plague. It is blocking and often causes deadlocks. Deadlocks occur because the framework spins up locks to make thread run thread-safe. But in ASP.NET if blocking using Task.Wait on the same thread it is very easy to cause a deadlock with async code.
- Avoid Task.ContinueWith as it is not aware of SynchronizationContext and always puts you on a new thread! This has become redundant with await and await is aware of SynchronizationContext is the task does end up running in a separate thread.
- Be careful with parallelism on the ASP.NET server. Multiple requests * multiple threads can quickly lead to thread starvation for as all threads come from the same pool. Threads consume minimum of 1/4 MB each.
- However kicking off multiple awaitable async tasks is fine. This actually helps scale your application better as the same thread can serve multiple tasks in an async manner.
- Don't call fire and forget methods - methods that don't return anything as your void methid code could be terminated anytime the original request ended to return the thread to the thread pool! If needed, use WebBackgrounder from http://nuget.org/packages/webBackgrounder
Check out these references:
Parallel Programming with .NET Blog
http://blogs.msdn.com/pfxteam/
Asynchrony in .NET Whitepaper
http://msdn.com/library/vstudio/hh191443.aspx
ASP.NET Async Tutorial
http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45
Task Parallelism Usage Pattern using Async in ASP.NET
1) Use a list of tasks
var tasks = new List<Task<string>>
{
CreateHtmlTextFirstAsync(),
CreateHtmlTextSecondAsync(),
CreateHtmlTextLastAsync()
};
2) Process tasks if any left in a while loop, removing completed task within the loop.
Keep flushing out the completed contents of each task as it completes in the loop.
(Note: Commenting out the check for IsFaulted that would not display content if the task had faulted, as this check may not be correctly coded here)
context.Response.ContentType = "text/html";
context.Response.Write(@"<!DOCTYPE html><html><body>");
context.Response.Write(@"<title>Async Body Sections!</title>");
while (tasks.Any())
{
var completed = await Task.WhenAny(tasks);
task.Remove(completed);
//if (!completed.IsFaulted)
//{
context.Response.Write(completed.Result);
context.Response.Flush();
// }
}
context.Response.Write(@"</body></html>");
**********************************************
We can improve the above code further by making the Response.Flush run asynchronously.
There is no async method for it, but we can make use of Task class like so and make it awaitable:
await Task.Factory.FromAsync(context.Response.BeginFlush, context.Response.EndFlush, null);
var tasks = new List<Task<string>>
{
CreateHtmlTextFirstAsync(),
CreateHtmlTextSecondAsync(),
CreateHtmlTextLastAsync()
};
2) Process tasks if any left in a while loop, removing completed task within the loop.
Keep flushing out the completed contents of each task as it completes in the loop.
(Note: Commenting out the check for IsFaulted that would not display content if the task had faulted, as this check may not be correctly coded here)
context.Response.ContentType = "text/html";
context.Response.Write(@"<!DOCTYPE html><html><body>");
context.Response.Write(@"<title>Async Body Sections!</title>");
while (tasks.Any())
{
var completed = await Task.WhenAny(tasks);
task.Remove(completed);
//if (!completed.IsFaulted)
//{
context.Response.Write(completed.Result);
context.Response.Flush();
// }
}
context.Response.Write(@"</body></html>");
**********************************************
We can improve the above code further by making the Response.Flush run asynchronously.
There is no async method for it, but we can make use of Task class like so and make it awaitable:
await Task.Factory.FromAsync(context.Response.BeginFlush, context.Response.EndFlush, null);
Async Cancellation Tokens
ASP.NET has 3 built in Cancellation tokens that allow us to terminate an in-flight async task - say cancel even a database query that is executing. For instance, when the token is marked as Cancel, then ASP.NET terminates the async task to return the thread back to the threadpool.
The three built-in tokens are:
Note: Always use RegisterAsyncTask when doing async code in ASP.NET. It is a best practice.
Example code snippet on Page_Load of ASP.NET Webforms,
RegisterAsyncTask(new PageAsyncTask(async ()=>
{
var token = Response.ClientDisconnectedToken;
var stockJson = await new HttpClient().GetStringAsync(Constants.StockServiceUri, token);
var stock = JsonConvert.DeserializeObject<Stock>(stockJson);
DisplayStock(stock);
var rssXml = await new HttpClient().GetStringAsync(Constants.RssUri, token);
var rss = Desserialize(rssXml);
DisplayRss(rss);
}));
Note: The GetStringAsync is an extension method you can define as
public static class HttpClientExtensions
{
public static async Task<string> GetStringAsync(
this HttpClient client,
string requestUri,
CancellationToken token) // this parameter is optional!!
{
var response = await client.GetAsync(requestUri, token);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
**************************************************************************
The Webforms, WebAPI and MVC APIs allow only passing in one token object at a time, so we can wire all three tokens in a single object and pass it in! We can build a composite token this way,
var source = CancellationTokenSource.CreateLinkedTokenSource(
Response.ClientDisconnectedToken,
Request.TimedOutToken,
t); //where t is the AsyncTimeOut token
//Use this composite source object
var token = source.Token;
Make sure to pass in "t" as a parameter to the lambda expression for PageAsyncTask like so
new PageAsyncTask(async (t) =>
*************************************************************************
WebApi and MVC actually makes this simpler by simply taking in a CancellationToken parameter in its method signatures. Also retrospectively adding this parameter does not affect any existing clients that don't pass in this token.
Example WebApi Get,
private StockContext entityDb = new StockContext();
public async Task<Stock> Get(CancellationToken token)
{
return await entityDb.Stocks.FirstAsync(token);
}
Takeaways:
The three built-in tokens are:
- RequestTimeout - request timed out so discontinue
- ClientDisconnected - client closed the browser, so discontinue async work
- AsyncTimeout - set a timeout for my async task
Note: Always use RegisterAsyncTask when doing async code in ASP.NET. It is a best practice.
Example code snippet on Page_Load of ASP.NET Webforms,
RegisterAsyncTask(new PageAsyncTask(async ()=>
{
var token = Response.ClientDisconnectedToken;
var stockJson = await new HttpClient().GetStringAsync(Constants.StockServiceUri, token);
var stock = JsonConvert.DeserializeObject<Stock>(stockJson);
DisplayStock(stock);
var rssXml = await new HttpClient().GetStringAsync(Constants.RssUri, token);
var rss = Desserialize(rssXml);
DisplayRss(rss);
}));
Note: The GetStringAsync is an extension method you can define as
public static class HttpClientExtensions
{
public static async Task<string> GetStringAsync(
this HttpClient client,
string requestUri,
CancellationToken token) // this parameter is optional!!
{
var response = await client.GetAsync(requestUri, token);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
**************************************************************************
The Webforms, WebAPI and MVC APIs allow only passing in one token object at a time, so we can wire all three tokens in a single object and pass it in! We can build a composite token this way,
var source = CancellationTokenSource.CreateLinkedTokenSource(
Response.ClientDisconnectedToken,
Request.TimedOutToken,
t); //where t is the AsyncTimeOut token
//Use this composite source object
var token = source.Token;
Make sure to pass in "t" as a parameter to the lambda expression for PageAsyncTask like so
new PageAsyncTask(async (t) =>
*************************************************************************
WebApi and MVC actually makes this simpler by simply taking in a CancellationToken parameter in its method signatures. Also retrospectively adding this parameter does not affect any existing clients that don't pass in this token.
Example WebApi Get,
private StockContext entityDb = new StockContext();
public async Task<Stock> Get(CancellationToken token)
{
return await entityDb.Stocks.FirstAsync(token);
}
Takeaways:
- Cancellation tokens further reduce thread usage and supplement async/await
- ASP.NET has built-in Cancellation tokens
- Use CancellationTokenSource to combine tokens
Subscribe to:
Posts (Atom)