Is event based model used in node the same as the event based model used in C# applications? - asp.net

I've heard about node.js and event based programming and things like the node event loop. In college I remember that I made an ASP.net web application. The professor said that ASP.net uses an event based architecture where callback functions on the server side were triggered by different events on the client side.
Are the two different technologies using the concept for events and event driven programming?

They're similar in that they're both using the idea of events - something that calls your code, rather than you going out and looking for changes. But in practice they're quite different.
In node (and in asp.net MVC) the events in question from the client are "this URL was requested". That's it. There's no more granularity other than the contents of the request.
In ASP.NET Webforms, they work very hard to synthesize events based on what happened on the client page. The events you get are "text changed", "button clicked", "checkbox checked"... basically the same kind of stuff you'd get in a straight desktop app.
It turns out that the Webforms model gets really, really complicated really fast, and the abstraction layer gets in the way of doing things like ajax calls.
Another thing node does is that just about everything is async events, unlike ASP.NET. Database call? Async in node, sync in ASP.NET. Read a file? Async in node, sync in ASP.NET. HTTP request to another server? You get the idea.
ASP.NET can do those things async, but you have to go out of your way to do it, and it uses threads. In node the async stuff is pretty natural and it doesn't need to use threads, resulting (somewhat surprisingly) in higher throughput in some cases.
So yes, they're the same in the sense that they're both "events", but the details are staggeringly different.

Yes, node uses an event based architecture where callback functions on the server side are triggered by different events on the client side.
Why Node.js is a big deal.
1) Using the same language on the client and the server speeds development.
2) Every web developer already knows JavaScript. The transition path to using it on the server has a lower learning curve.
3) Modules built for Node.js are all event driven. Writing event driven code on other platforms usually requires you to sift through third party modules to find the ones that are event driven. For example, there are several event driven libraries for Python, but most third party networking libraries for Python are synchronous because of Python's heritage. Same with Ruby, Java, Scala and many other platforms.
4) Speed. Node.js runs on the V8 javascript engine. It may not be quite as fast as Java or C#, but it's light years ahead of Python, Ruby and PHP. Python, Ruby and PHP make up a huge portion of the web application market share. When developers with their primary experience based in those languages need more speed, Node.js is a logical place to find it.

Related

Do I understand this MVC right?

I'm refactoring a large web app with another developer's help. In my mind, the backend is organized like so:
Symfony PHP: controller
PostgreSQL DB: model
As I understand it, the client-side browser is the 'view' of the server.
The frontend is additionally organized like this:
Redux.js: model + controller // this is all mildly simplified
React.js: view
Is it, therefore, conceptually correct to consider the client-side browser as the view of the server's state, and further, that the browser maintains its own state, controller, and view of the server-side data?
I'm a server-side "expert" (emphasize the quotes), while my helper is a front-end pro. We're deliberately trying to separate frontend and backend and restrict interaction to JSON payloads beyond the initial page load. If I'm looking at the global organization of the project right, it'll really help me organize our master codebase.
I don't think it's particularly helpful to think of the client-side app as just a view of the server-side state anymore.
The client-side is its own MVC application. Strictly, I don't think react-redux is actually MVC. It's considered an alternative to MVC. React is the View in MVC, but also a little bit of the Controller, and redux is an opinionated way of using the Model. You should read more here: http://redux.js.org/docs/introduction/Motivation.html
Relationship of the client-side M to the server-side M
Maybe another way of thinking about this is that the server has a 'model' and a part of the redux state-tree is actually kind of a view of that 'model' (like a list of todos derived from and kept in sync with a todo table on the server-side).
Parts of the redux state-tree could also have nothing to do with the server-side 'models' and could just be useful for storing client-side state (like the current url/route).
My firm belief is to not worry too much about the terminologies too much and stick to first principles. The server has state, the client-app has state. A part of the client-app's state is derived from and/or synced to the server-side state. The rest of the client-app's state helps generate the UI that the user sees. As the user interacts with the app, code is triggered that manipulates the state. Once you write a simple react-redux app, you'll see where all these pieces go!
Sounds about right.
The state of the application
React components maintain internal state. The state is updated via this.setState upon an event (e.g. click, mouse move, keyboard input, timeout, AJAX response, etc.). When this.setState is called, en entire re-render of the component is scheduled, after which, the component is then redrawn.
The cycle pretty much continues. You can think of React's state to work just like a traditional LAMP web app, that is, in an example web app, user submits a form, the page is updated with new content. Only that instead of you setting up the listeners, and imperatively telling react what data to pass in to this.setState, with a traditional LAMP app, you do so declaratively in the HTML declaration of the <form>, in the inputs that you define.
Albeit, the above React vs LAMP example is probably a bad analogy, because React does not directly work with the server. It's your responsibility on how to design your code to work with the server.
Communication with server
So, with LAMP, trivially, if you want user input to persist on the server, you simply record the input from a form POST request.
With react, there's an extra step on your end.
When a user triggers an event (click, mouse move, keyboard input, etc.), you first need to issue an AJAX request, which, of course, the server will act on the request (e.g. store form input).
In the (successful) response callback, you would then call this.setState to update what the server responded with. With a traditional LAMP app, you would get an entirely new web page rendered with the user's persisted data. With React, instead, you get back some piece of data (perhaps JSON or XML) which isn't the web page, but is used by your front-end application to determine what the page should look like.
Is it, therefore, conceptually correct to consider the client-side
browser as the view of the server's state, and further, that the
browser maintains its own state, controller, and view of the
server-side data?
Yes, it is completely correct.
In fact, you can think about your web app as an MVC that lives inside another MVC (the browser) that is then executed inside another MVC (the OS windowing system). Which communicates with another MVC across the wire (your backend app).
Now, swap MVC for "the implementation of a software design pattern", because there is no canonical definition of what MVC is. There are many variations, for example, MVC in the server is quite different from MVC in a client machine.
The server side approach is based on what is known as Java Model 2. This design shares the same philosophy as MVC and most of its components resemble it, so we all call it MVC. Which is not incorrect, although inexact too.
http://givan.se/mvc-past-present-and-future/#server-mvc
You can compare all of the documented patterns that belong to the MVC collection here:
http://mvc.givan.se/

asp.net-async pages (comet/reverse ajax/server push)

I am trying to develop a comet page using Asp.net. Surfed a lot and found some plugins like Pokein. I feel this blog, to be best suited for my project as it goes in hand with jQuery. But this is in MVC. I wonder if i can do the same with ASP.NET website pages. All i need to do is to free up the worker process during the long waiting ajax-call duration. In MVC, async controllers come handy. Could someone help me if I can do the same with website pages(say: free up the worker process during the long waiting jquery Ajax call inside the static web method). I read about async pages in websites here, but this will take a full posback and the page is blocked during the long wait. (basically free up worker process during pre-render and wait for long polling, but the UI still keeps refreshing as the page life cycle is not completed)
Thanks in advance for your advice geeks...
'Push' style architectures on the web using purely ASP.NET, JavaScript, JQuery, AJAX etc. can be difficult and involved to implement. Normally the route most go is more of a glorified 'pull' model where a timer somewhere client side will check back to the server for the needed data or state required and then preform the necessary action. If you truly want a more of a push architecture with purely web technologies, you will want to look into the long polling 'Comet' architecture. You can read more about it below:
Comet (programming):
http://en.wikipedia.org/wiki/Comet_(programming))
Ideally in the Microsoft world if possible you could jump over to a rich client technology like Silverlight to work with a duplex polling WCF service in which a client subscribed to the server can get updates pushed from the server back to the client. Anytime (as of today)I would need to implement any type of 'push' architecture today I would personally opt for Silverlight as there are numerous examples on how to implement this easily. If you are interested take a look to the (2) links below:
Pushing Data to a Silverlight Client with a WCF Duplex Service:
http://weblogs.asp.net/dwahlin/archive/2008/06/16/pushing-data-to-a-silverlight-client-with-wcf-duplex-service-part-i.aspx
How to: Build a Duplex Service for a Silverlight Client:
http://msdn.microsoft.com/en-us/library/cc645027(VS.95).aspx
Regardless, COMET/Silverlight/Flash, etc. are probably not going to be a widely used option going forward anyways with web sockets in HTML5. But since the spec is not quite ready (see: http://ishtml5readyyet.com/) you might needs to look at using a Silverlight control on your ASP.NET page in the meantime and it will work well.

What should I be aware of when threading in ASP.NET?

Recently, the book on threading for Winforms application (Concurrent programming on Windows by Joe Duffy) was released. This book, focused on winforms, is 1000 pages.
What gotchas are there in ASP.NET threading? I'm sure there are plenty of gotchas to be aware of when implementing threading in ASP.NET. What should I be aware of?
Thanks
Since each http request received by IIS is processed separately, on it's own thread anyway, the only issues you should have is if you kick off some long running process from within the scope of a single http request. In that case, I would put such code into a separate referenced dependant assembly, coded like a middle-tier component, with no dependance or coupling to the ASP.Net model at all, and handle whatever concurrency issues arose within that assembly separately, without worrying about the ASP.Net model at all...
Jeff Richter over at Wintellect has a library called PowerThreading. It is very useful if you are developing applications on .NET. => Power Threading Library
Check for his presentations online at various events.
Usually you are encouraged to use the thread pool in .Net because it of the many benefits of having things managed on your behalf.....but NOT in ASP.net.
Since ASP.net is already multi-threaded, it uses the thread pool to serve requests that are mapped to the ASP.net ISAPI filter, and since the thread pool is fixed in size, by using it you are basically taking threads away that are set aside to do the job of handling request.
In small, low-traffic websites, this is not an issue, but in larger, high-traffic websites you end up competing for and consuming threads that the ASP.net process relies on.
If you want to use threading, it is fine to do something like....
Thread thread = new Thread(threadStarter);
thread.IsBackground = true;
thread.Start();
but with a warning: be sure that the IsBackground is set to true because if it isn't the thread exists in the foreground and will likely prevent the IIS worker process from recycling or restarting.
First, are you talking about asynchronous ASP.NET? Or using the ThreadPool/spinning up your own threads?
If you aren't talking about asynchronous ASP.NET, the main question to answer is: what work would you be doing in the other threads and would the work be specific to a request/response cycle, or is it more about processing global tasks in the background?
EDIT
If you need to handle concurrent operations (a better term than multi-threaded IMO) for a given request/response cycle, then use the asynchronous features of ASP.NET. These provide an abstraction over IIS's support for concurrency, allowing the server to process other requests while the current request is waiting for work to complete.
For background processing of global tasks, I would not use ASP.NET at all. You should assume that IIS will recycle your AppPool at a random point in time. You also should not assume that IIS will run your AppPool on any sort of schedule. Any important background processing should be done outside of IIS, either as a scheduled task or a Windows Service. The approach I usually take is to have a Windows Service and a shared work-queue where the web-site can post work items. The queue can be a database table, a reliable message-based queue (MSMQ, etc), files on the file system, etc.
The immediate thing that comes to mind is, why would you "implement threading" in ASP.NET.
You do need to be conscious all the time that ASP.NET is multi-threaded since many requests can be processed simulatenously each in its own thread. So for example use of static fields needs to take threading into account.
However its rare that you would want to spin up a new thread in code yourself.
As far as the usual winforms issues with threading in the UI is concerned these issues are not present in ASP.NET. There is no window based message pump to worry about.
It is possible to create asynchronous pages in ASP.NET. These will perform all steps up to a certain point. These steps will include asynchronously fetching data, for instance. When all the asynchronous tasks have completed, the remainder of the page lifecycle will execute. In the meantime, a worker thread was not tied up waiting for database I/O to complete.
In this model, all extra threads are executing while the request, and the page instance, and all the controls, still exist. You have to be careful when starting your own threads, that, by the time the thread executes, it's possible that the request, page instance, and controls will have been Disposed.
Also, as usual, be certain that multiple threads will actually improve performance. Often, additional threads will make things worse.
The gotchas are pretty much the same as in any multithreaded application.
The classes involved in processing a request (Page, Controls, HttpContext.Current, ...) are specific to that request so don't need any special handling.
Similarly for any classes you instantiate as local variables or fields within these classes, and for access to Session.
But, as usual, you need to synchronize access to shared resources such as:
Static (C#) / Shared(VB.NET) references.
Singletons
External resources such as the file system
... etc...
I've seen threading bugs too often in ASP.NET apps, e.g. a singleton being used by multiple concurrent requests without synchronization, resulting in user A seeing user B's data.

Silverlight,asynchronous,lazy loading what's the best way?

I started to use silverlight/flex and immediately bumped into the asynchronous service calling. I'm used to solving the data access problems in an OO-way with one server fetch mechanism or another.
I have the following trivial code example:
public double ComputeOrderTotal(Order order)
{
double total = 0;
// OrderLines are lazy loaded
foreach (Orderline line in order.Orderlines)
{
// Article,customer are lazy loaded
total = total + line.Article.Price - order.Customer.discount;
}
return total;
}
If I understand correctly, this code is impossible in Flex/Silverlight. The lazy loading forces you to work with callbacks. IMO the simple expample above will be a BIG mess.
Can anyone give me a structured way to implement the above ?
Edit:
The problem is the same for Flex/Silverlight, pseudo code would
do fine
Its not really ORM related but most orms use lazy loading so i'll remove
that tag
The problem is lazy loading in the model
The above example would be very doable of all data was in memory but
we assume some has to be fetched from
the server
Closueres dont help since sometimes data is already loaded and no asynchronous fetch is needed
Yes I must agree that O/R mapping is usually done on the server-side of your application.
In SilverLight asynchronous way of execution is the desired pattern to use when working with services. Why services? Because as I said before there is no O/R mapping tool at the moment that could be used on the client-side (SilverLight). The best approach is to have your O/R mapped data exposed by a service that can be consumed by a SilverLight application. The best way at the moment is to use Ado.Net DataServices to transport the data, and on the client-side to manage the data using LINQ to Services. What is really interesting about ADS (former Astoria project) is that it is designed to be used with Entity Framework, but the good folks also implemented support for IQueriable so basically you can hook up any data provider that support LINQ. To name few you can consider Linq To Sql, Telerik OpenAccess, LLBLGen, etc. To push the updates back to the server the data source is required to support the ADS IUpdateable.
You can look just exactly how this could be done in a series of blogposts that I have prepared here: Getting Started with ADO.NET Data Services and Telerik Open Access
I can't speak to Silverlight but Flex is a web browser client technology and does not have any database driver embedded in the Flash runtime. You can do HTTP protocol interactions to a web server instead. It is there in the middle-tier web server where you will do any ORM with respect to a database connection, such as Java JDBC. Hibernate ORM and iBATIS are two popular choices in the Java middle-tier space.
Also, because of this:
Fallacies of Distributed Computing
You do not do synchronous interactions from a Flex client to its middle-tier services. Synchronous network operations have become verboten these days and are the hallmark signature of a poorly designed application - as due to reasons enumerated at the above link, the app can (and often will) exhibit a very bad user experience.
You instead make async calls to retrieve data, load the data into your client app's model object(s), and proceed to implement operations on the model. With Flex and BlazeDS you can also have the middle-tier push data to the client and update the client's model objects asynchronously. (Data binding is one way to respond to data being updated in an event driven manner.)
All this probably seems very far afield from the nature of inquiry in your posting - but your posting indicates you're off on an entirely incorrect footing as to how to understand client-side technologies that have asynchronous and event-driven programming baked into their fundamental architecture. These RIA client technologies are designed this way completely on purpose. So you will need to learn their mode of thinking if you want to have a good and productive experience using them.
I go into this in more detail, and with a Flex perspective, in this article:
Flex Async I/O vs Java and C# Explicit Threading
In my direct experience with Flex, I think this discussion is getting too complicated.
Your conceptual OO view is no different between sync and asynch. The only difference is that you use event handlers to deal with the host conversation in the DAL, rather than something returned from a method call. And that often happens entirely on the host side, and has nothing to do with Flex or Silverlight. (If you are using AIR for a workstation app, then it might be in client code, but the same applies. As well if you are using prolonged AJAX. Silverlight, of course, has no AIR equivalent.)
I've been able to design everything I need without any other changes required to accomodate asynch.
Flex has a single-threaded model. If you make a synchronous call to the web server, you'd block the entire GUI of the application. The user would have a frozen application until the call completes (or times out on a network error condition, etc.).
Of course real RIA programs aren't written that way. Their GUI remains accessible and responsive to the user via use of async calls. It also makes it possible to have real progress indicators that offer cancel buttons and such if the nature of the interaction warrants such.
Old, bad user experience web 1.0 applications exhibited the synchronous behaviour in their interactions with the web tier.
As my linked article points out, the async single-threaded model coupled with ActionScript3 closures is a good thing because it's a much simpler programming model than the alternative - writing multi-thread apps. Multi-threading was the approach of writing client-server Java Swing or C# .NET WinForm applications in order to achieve a similarly responsive, fluid-at-all-times user experience in the GUI.
Here's another article that delves into this whole subject matter of asynchronous, messaging/event-driven distributed app architecture:
Building Effective Enterprise Distributed Software Systems
data-driven communication vs behavior-driven communication
Silverlight is a client technology and the Object - Relational mapping happens completely in the server. So you have to forgot about the ORM in Silverlight.
Following your example what you have to do is to create a webservice (SOAP, REST...) that can give your silverlight client the complete "Order" object.
Once you have the object you can work with it with no communication with the server in a normal - synchronous way.
Speaking about Silverlight, you should definitely check RIA services.
Simply, it brings the DataContext from the server to the client from where you can asynchronously query it (there is no need to write WCF services by hand, it's all done by RIA).
C# 5
async / await construct will almost exactly what I want..
watch presentation by anders hejlsberg

What's the best way to implement an API in ASP.NET using MVC?

I've been a longtime ASP.NET developer in the web forms model, and am using a new project as an opportunity to get my feet wet with ASP.NET MVC.
The application will need an API so that a group of other apps can communicate with it. I've always built API's out just using a standard web service prior to this.
As a sidenote, I'm a little hesitant to plunge headfirst into the REST style of creating API's, for this particular instance at least. This application will likely need a concept of API versioning, and I think that the REST approach, where the API is essentially scattered across all the controllers of the site, is a little cumbersome in that regard. (But I'm not completely opposed to it if there is a good answer to the potential versioning potential requirement.)
So, what say ye, Stack Overflow denizens?
I'd agree with Kilhoffer. Try using a "Facade" wrapper class that inherits from an "IFacade". In your Facade class put your code to consume your web service. In this way your controllers will simply make calls to the Facade. The plus side of this being that you can swap a "DummyFacade" that implements the same IFacade interface in that doesn't actually talk to the web service and just returns static content. Lets you actually do some unit testing without hitting the service. Basically the same idea as the Repository pattern.
I would still recommend a service layer that can serve client side consumers or server side consumers. Possibly even returning data in a variety of formats, depending on the consuming caller.

Resources