Monday, July 29, 2013

Node.JS tutorial - Create a simple chat with socket.io module - Part 3

Source Code: 

In that part we will create the chat functionallity (= Communication between the clients and the server).

Adding the chat communication functionallity


Client 
1. 

Add inside the body tag a script block:


<script type="text/javascript">
</script>


Client 
2. Creating a client socket

socket.io uses WebSockets. That means that when a client connects to the server, the connection remains open ("Wikipedia": WebSocket is a web technology providing full-duplex communications channels over a single TCP connection).
Let's connect to the server and get a brand new socket for our client by adding:

  // our websocket
 var socket = io.connect();

Keep the userName in a global variable by adding:

 var userName;


Client 
3. Writing login client logic

Let's start by implementing "onLogInLogOut()" function.
First we will take his user name from the text-box by :

userName = document.getElementById("txtUserName").value; 


And we'll check whether it's a "LogIn" or "LogOut" :


// get button text
var btnLogInLogOut = document.getElementById('btnLogInLogOut');
var txtBtnLogInLogOut = btnLogInLogOut.textContent || btnLogInLogOut.innerText;
if(txtBtnLogInLogOut == 'LogIn') {
}
else {
}

Suppose it's a LogIn, we need to inform the server that a new user has just connected.
We do it by:


// send join message
socket.emit('join', userName);

Here is the full LogIn condition, including changing "LogIn" button to a "LogOut" button after the user connected:


if(txtBtnLogInLogOut == 'LogIn') {
// send join message
socket.emit('join', userName);
btnLogInLogOut.innerText = 'LogOut';
document.getElementById('btnSendMessage').disabled = false;
}


Server
4. 

We need to keep the users, so we'll add an array as a global variable:

var users = {};

g. Let's define the 'join' event whenever a client connects:

io.sockets.on('connection', function (socket) {
   socket.on('join', function(userNameParam) {
   });
}

io.sockets.on('connection', function() { .. } ) - is a socket.io built-in event, and we use it to trigger each client connection.
As a result, we are getting a socket for that client, and we define the event that we have been using in the client side (remember "socket.emit('join', userName);" ?).

Here's a brief on the LogOn cycle from socket.io point of view:
User loads the page and socket is created ( "var socket = io.connect();" ).
"io.sockets.on('connection', ...)" is being triggered and all of the events definitions are save to that socket.
User clicks on the LogOn button and 'join' is being called on server ("socket.emit('join', userName);").
"socket.on('join', function(userNameParam)" is triggered due to the call.


Server
5. 

Add the full 'join' event:

socket.on('join', function(userNameParam) {
    socket.join('chatchannel'); // create/join a socket.io room
    users[userNameParam] = userNameParam; // save the user name in the users array
    socket.userName = userNameParam; // save the user name inside the socket
    socket.emit('firstLogin',users); // when a user login first, call 'firstLogin' only in that client socket
    socket.broadcast.to('chatchannel').emit('addConnectedUser',userNameParam); // tells everyone except that user that a new user has been connected
   io.sockets.in('chatchannel').emit('message',userNameParam, 'I am connected !'); // tells every client that the user connected
});

socket.io allows us to use a "room" functionallity. That means a few sockets can join a room, and the server can refer to that room when transferring messages (it's very easy to implement chat rooms like that, right ?).
In our chat version, we use only one room which called 'chatchannel' : 
"socket.join('chatchannel');".

Regarding the UI, if a user login we want to add all of the users to the listview, so we need a special event for it on the client side. We will call 'firstLogin' on the client by: "socket.emit('firstLogin',users);".

Now we need to inform all the connected users (clients) about that user who had just connected:
socket.broadcast.to('chatchannel').emit('addConnectedUser',userNameParam);
That will inform everyone in that room, except the brand new user (= the current socket).



Client
6. 

Define the 'firstLogin' event on the client, which adds all user names to the users list, and 'addConnectedUser' which adds the new user to an existing users list on a connected client.
Again, 'firstLogin' - for a brand new connected user, 'addConnectedUser' - for all of the connected users which already has a users list in their UI.

socket.on('firstLogin', function(data) {
    var ulFriends = document.getElementById('friends');
    ulFriends.innerHTML = '';
    for (i in data) {
addUserToList(ulFriends, data[i]);
   }
});
socket.on('addConnectedUser', function(data) {
    var ulFriends = document.getElementById('friends');
    addUserToList(ulFriends, data);
});
function addUserToList(ulFriends, userName) {
    var li = document.createElement('li');
    li.appendChild(document.createTextNode(userName));
   li.setAttribute('id','user-' + userName);
   ulFriends.appendChild(li);
}



Server
7.
When a user closes the chat browser tab, or press 'LogOut' we notify the chat clients, and leaving the socket.io 'chatchannel' room:

socket.on('leave', onUserDisconnected);

socket.on('disconnect', onUserDisconnected);

function onUserDisconnected() {
  delete users[socket.userName]; // removing the user from users list
  io.sockets.in('chatchannel').emit('logout',socket.userName); // call logout event on each client
  io.sockets.in('chatchannel').emit('message',socket.userName, 'I am disconnected !'); // tells every client that the user disconnected
  socket.leave('chatchannel'); // leaving socket.io 'chatchannel' room
}

Keep in mind that 'leave' is our event, and 'disconnect' is a built-in socket.io event.


Client
8.
Removing the disconnected client from the users list in each client:

socket.on('logout', function(data) {
var user = document.getElementById('user-' + data);
user.parentNode.removeChild(user);
});


Client
9.
When a user sends message, we want to notify the server:

function onSendMessageClick() {
    var messageText = document.getElementById("txtUserMessage").value;
    socket.emit('send',userName, messageText);
}


Server
10.
Sending the message to all clients:

socket.on('send', function(userName, messageText) {
  io.sockets.in('chatchannel').emit('message',userName, messageText);
});


Client
11.
Getting the message and publish it to the text area place:

socket.on('message', function(userName, messageText) {
   document.getElementById("txtUserMessage").value = '';
   var ulChat = document.getElementById('chat');
   var li = document.createElement('li');
   var userSpan = document.createElement('span');
   userSpan.style.color = 'red';
   userSpan.innerHTML = userName + ': ';
   var messageSpan = document.createElement('span');
   messageSpan.innerHTML = messageText;
   li.appendChild(userSpan);
   li.appendChild(messageSpan);
   ulChat.appendChild(li);
});


Summary

We're done! 
Now you have a nice not-fancy chat built with node.js.

Sunday, July 7, 2013

Node.JS tutorial - Create a simple chat with socket.io module - Part 2

Source Code:

In my previous post, I explained how to:
1. Install node.js environment and modules
2. Create a template application using express module
3. Install Eclipse IDE and node.js plugin

Now let's start building our chat application. PLEASE work with Google Chrome. I didn't test it on other browsers and i'm not sure about it's compitability.

First of all, I've searched for a decent CSS for chat, so I googled and found that post:
Create "stylesheets" under "public" directory and add "chat.css".

We are ready to write some code!

Creating the chat view


1. Create "chat.hjs" under "views" folder. ".hjs" extension tells the engine it's a hogan.js template.

2. At first, we'll include socket.io.js file and jquery (although I'm not sure we will be using the last).

<html>
  <head>
  <link rel='stylesheet' href='/stylesheets/chat.css' />
  </head>
  <body>
  <script src="/socket.io/socket.io.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</body>
</html>


3. Creating the view includes:

"upperPanel" - divided to two list: "chat" for the chat messages, "friends" for the chat users list.
"bottomPanel" - divided to two panels:
"messagePanel" - contains text area for the user to send messages, and a "send" button. Please note the onclick="onSendMessageClick()".
"signInPanel" - contains text box for the user to enter his chat user-name, and a "LogIn" button. Please note the onclick="onLogInLogOutClick()".

<div id="wrapper">
   <div id="upperPanel">
       <div>
           <ul id="chat">
           </ul>
       </div>
       <div>
        <ul id="friends">
        </ul>
       </div>
   </div>
   <div id="bottomPanel">
    <div id="messagePanel" style="float:left">
       <textarea id="txtUserMessage" style="resize:none;height:80px;float:left;width:800px;"></textarea>
       <input id="btnSendMessage" onclick="onSendMessageClick()" type="submit" style="width:50px;height:80px;float:right;" disabled="disabled" value="send" />
       </div>
       <div id="signInPanel" style="float:right">
        <input id="txtUserName" style="width:130px;" type="text" name="userName"/>
        <button id="btnLogInLogOut" onclick="onLogInLogOutClick()">LogIn</button>
       </div>
   </div>
</div>

Also add session id div, just in order to demonstrate hogan.js:

<div id="sessionId" style="float:right">
Session Id: {{sessionId}}
</div>

The curly buckets mention that this data would be injected from the server.



Server 
4. Server configurations and events

Let's take a break from the client-side, and move to write some node.js server code. We had just written a server call, so let's try to catch it.


A. 

Open app.js, which is the main file of our server application. This is where all starts. 
Please remove all code before you continue.


B. 

Add those module imports including socket.io on top:

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , socketio = require('socket.io')  // library for realtime web applications based on WebSocket protocol


C. 

Create the server, and make socket.io availiable on server by:

var app = express()
, server = http.createServer(app)
, io = socketio.listen(server);


D. 

Add those configurations to your express application:

app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'hjs');
    app.use(express.favicon());
    //app.use(express.logger('dev')); // Express logger
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser()); // To parse cookies
    app.use(express.session({secret: '1234567D9sQWERTY'})); // To use sessions
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public'))); 
});

You can see that we are setting the port of our server application, defining what is our view engine (hogan.js) and so on. We are doing this with app.set().
The app.use() calls pass 'middleware' functions for express to use. Each layer is essentially adding a function that specifically handles something to the flow through the middleware.
For example by adding "app.use(express.bodyParser());",  we ensure that our server handles incoming requests through the express middleware, and now parsing the body of incoming requests is part of the procedure that the app middleware takes when handling incoming requests.

Also add:

app.configure('development', function(){
    app.use(express.errorHandler());
});


That line would tell our app to use the middleware errorHandler function when running on development mode. (We can run development mode by writing: process.env.NODE_ENV='development' in our node app)

E. 

Start the server on the chosen port by adding:


server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port')); 
});


F.

Now we want to configure routing for our app. 
We want our chat app to be placed at: "{URL}/chat".
Add to app.js:

require('./routes')(app);


And modify index.js to:

module.exports = function(app) {
  app.get('/', index);
  app.get('/chat',chat);
};


var index = function(req, res){
    res.render('index', { title: 'Express' });    
};



var chat = function(req, res){ 
    res.render('chat', { sessionId: req.session.id});
};

"app.get('/chat',chat);" - sends all GET requests of '/chat' to 'chat' function we have defined.
"res.render('chat', { sessionId: req.session.id});" - that line tells the engine to render 'chat.hjs' view, and to inject the user's session id.


Summary


In that part we created a basic chat view, and set some configurations to our server.
Now we are all set to create the communication between the clients and server.

Sunday, June 30, 2013

Node.JS tutorial - Create a simple chat with socket.io module - Part 1

Source Code: 
https://github.com/ohadinho/chat-sample

Previous Parts:
Part 1

In my last post (http://avenshteinohad.blogspot.co.il/2013/05/nodejs-behind-scenes-whats-difference.html) I have introduced Node.JS.
I wrote about why and when we should be using it. As mentioned, one of the most popular usage is a realtime application.
In this post, we will build a very simple chat with Node.JS and some other modules (= libraries) which will be explained later.


Installing Node.JS & Express Module


I will refer to Windows environment in my post.

1. First step is very easy. Log in to: http://nodejs.org/download/ , and download node.js for your appropriate platform.

2. After downloading and installing node.js in your machine, run 'cmd' and go to node.js folder.
For example: "cd C:\Program Files\nodejs".

3. Now we will install express module using npm.

npm is the web repository which keeps node.js packaged modules. You can look for modules here: https://npmjs.org/ .
Any package can be installed in your node.js app using "npm install *package-name*" from the root folder of your app using command-line.

express is a minimalist web framework for node. It's a very common and popular module among node developers, and it organizes your web app into an MVC architecture on the server side. You can look on express API here:

Executing "c:\Program Files\nodejs\npm install -g express", will download and install express module in your node installation folder.

4. "express *node-app-folder*" will create a template of node application using express.
We want to have hogan.js engine support in our chat node app, so add '-H' option and execute: "c:\Program Files\nodejs\express -H c:\apps\chat-sample".
hogan is a templating engine developed at Twitter. We will use in order to inject data into our chat template view.

5. Now it's time to look at our sample app.
Run "c:\apps\chat-sample\node app.js".
You should see as a result:
"Express server listening on port 3000" - That ofcourse means that your web server is up and running!

6. Open your web browser and navigate to: "http://localhost:3000/".
That is what you are suppose to see:


Installing socket.io module

I chose "socket.io" module for communicating between the clients and the server.
"socket.io" is a cross-browser module for real-time apps. It's very easy to use and it have a simple broadcasting mechanism.
It's important to mention that socket.io doesn't support broadcasting between multiple servers.
In order to achieve multiple servers support, you'll have to use "redis" database module.
"Redis" is a fast database, and it's module has a built-in pub-sub mechanism.
In this tutorial, we will only use socket.io, thus you can use only one server to serve the chat application.
We will install also "ws" module, because "ws" is a dependency of "socket.io-client", and the last is a dependency of "socket.io".

1. Open cmd, go to: "C:\apps\chat-sample" and run "npm install ws".
2. After ws module was installed, run "npm install socket.io".

Installing Eclipse and Nodeclipse plugin


We would use Eclipse IDE and Nodeclipse plugin in order to develop out chat app.

1. Go to: "http://www.eclipse.org/downloads/" and download "Eclipse IDE for Java EE Developers".
2. Extract the downloaded zip to: "C:\Program files\"
3. Run eclipse by executing "eclipse.exe" from the installation folder.
4. Go to Help --> Eclipse Marketplace, and search for "Nodeclipse". Install it, and restart eclipse.

Adding our chat application to eclipse workspace


Actually, we could have created a new node application straight from eclipse, but I thought it's a good practice doing it from command line.
It's important to mention that modules still can only be installed from command line. You cannot do it within eclipse environment.

1. Go to: File --> New --> Node Project










2. Project Name: 'chat-sample', and use the location of the app we have created: 'c:\apps\chat-sample'.




















3. Run the app by Right-Click on "app.js" --> Run as --> Node Application










Summary


That's it !
We have installed:
1. Node.js with some modules
2. Eclipse and Nodeclipse plugin in order to have a decent development environment

and at last we have added our app to our new development environment.

In the next part we will start writing some code for our chat application.

Thursday, May 30, 2013

Node.JS behind the scenes. What's the difference between Node.JS and IIS ?

The first thing you think about when you hear the word 'JavaScript' - is about developing client-side web-pages. It's perfect to interact with the DOM of the page, and handling DHTML.
Well, JavaScript is more than that. It's a prototype-base programming language in the full sense of the word.
Node.JS is a server written in JavaScript, based on Google's new V8 JavaScript engine, and it's an event-driven, non-blocking I/O model.
Node.JS is a single-process, unlike other servers like Apache (that runs PHP) which starts its own process for every HTTP Request.

When writing Node.JS code, there will always be a use of one of the most powerful and important JavaScript features: Callback functions. That is the whole idea of asynchronous programming, and that would keep your single Node.JS process running fast. 
With callback functions, you can avoid blocking code.

Here is an example of how NOT doing it. 

Synchronous code:
var result = database.query("SELECT * FROM hugetable");
console.log("Hello World");

Suppose getting the results from the database takes several seconds. The single Node.JS process will be halt, and other requests would not be handled until receiving a response. Same same as for the "console.log("Hello World")" line. If this synchronous code was written in PHP, other requests 
won't get affected by that blocking code (each process for every request).

Here is an example of how doing it, using the concept of event-driven.

Asynchronous code:
function dbRows(rows)
{
  var result = rows;
}

var result = database.query("SELECT * FROM hugetable", dbRows);
console.log("Hello World");


By giving the second argument, which is the callback function, the single Node.JS process won't be halt, and "Hello World" would be printed. If you are writing your code in ASP.NET, then your web-application is served on w3wp.exe process, which is a single-process just like Node.JS. On MVC 2.0, you can implement "AsyncController" for asynchronous methods, or you can do it without MVC with "IHTTPAsyncHandler" interface.


So what is the difference between Node.JS and ASP.NET Async ?


First of all, the whole concept of Node.JS is "event-driven". That means it's very easy to write Asynchronous application. So an average Node.JS programmer will think Async, and an ASP.NET one - it wouldn't really matter. That because synchronous code in .NET would be much more readable than async one. Furthermore, writing a complete ASP.NET Async application is simply harder.

In addition, if a Node.JS developer is using external libraries (=modules), probably those would be Async, but with .NET you cannot be sure about it.

In order to implement Async, .NET uses I/O completion ports. Many .NET libraries don't use them. For example: ADO.NET supports Async (Engine is using completion ports) while Entity Framework doesn't (engine is NOT using completion ports).
ASP.NET dedicates a thread per request from its thread pool and it has a maxmium number of working threads. In case of a blocking code (Synchronous code), new threads would be created and other threads would be stuck doing nothing (using CPU resources), and if that doesn't enough - the application can run out of threads as you define it on the web.config:











Request Flow


Although people tend to think Node.JS is single-threaded - it's not. It uses the event-loop as a manager to transfer work from the clients to the C++ thread pool (= Gets requests from the clients and send them to thread workers). 
When the work gets done, it transfer the response back to the client.
Back to the threads thing. The event-loop (which is a permanant thread) runs on the same - single I/O thread, BUT the work it delivers is done multi-threaded behind the scenes.
In Windows and Linux, each user mode thread has a kernel mode thread (one-to-one threading model). If the user mode thread needs to use the kernel thread (in order to perform privileged instructions, such as process creation or I/O operations) it does it by system calls.
Node.JS threads (Event loop thread and C++ ThreadPool workers) are working on user mode only.

So "everything runs in parrallel except your code". Your Node.JS code doesn't contain any threads.
Node.JS built upon LibUv library, which provides the event loop mechanism. That mechanism allows a task to be registered on the ThreadPool and get a response once the task completed (uses
the callback function in order to send the response).


IIS 6.0 request flow is more efficient than IIS 5.0 (or less version): 


1. The kernel receives a request and delivers it to HTTP.SYS
2. HTTP.SYS delivers the request to the target worker process (the one that belongs to the requested application pool)
3. Worker process uses a thread pool to process the request
4. Worker process sends the response back to HTTP.SYS which delivers it to the client



A short explanation about Thread Context Switches


Context switches (CPU switch between threads) occur in one of those situations:
1. A running thread voluntarily releases the processor
2. Kicked out by a higher priority ready thread
3. Might happen when switches between user-mode and privileged (kernel) mode to use an Executive or subsystem service (that switch is a mode switch, not context switch. Context switch has heavy performance penalty. Sometimes mode switch causes context switch).


Performance Differences


- When a request is being made : The kernel thread delivers it to the IIS I/O thread gets, which post it to the   CLR ThreadPool and gets a "pending" status from it.

On step 1 - there is a mode switch between kernel and user-mode, so there might be a context switch.
The IIS/IO thread waits for the "pending" status from CLR ThreadPool in order to continue. So there is a context switch, and the IIS/IO gets blocked.
On step 4 - there is a mode switch, so there might be a context switch as well.

On Node.JS, the request is passed from event-loop thread to C++ ThreadPool (both running on user-mode). BUT, if there are many requests there queued on the event-loop and the ThreadPool thread can pick up a bunch of requests and not just one like the IIS does.

- In case of a small number of requests - IIS should perform better.
In IIS, each request gets only one thread from the ThreadPool. In Node.JS, a request can be transferred between threads from the ThreadPool (And  that means more context switching). 

- In case of a large and concurrent number of requests - Node.Js should perform faster because it has fewer threads and includes the event-loop architecture (non-blocking I/O), so there will be less context switches and heavy load performs well on event-loop architecture.
IIS has larger ThreadPool, so the requests will use them all - and there will be more context switches. 

- In case of serving static HTML pages - IIS has a real significant advantage on Node.JS, because it has kernel mode caching, so the request won't arrive to user mode.


For conclusion

There isn't a straight answer which server is faster. It depends on your application needs. Basically, you should use Node.JS when receiving a lot of concurrent requests and heavy load.
One thing is for sure: Async code is more efficient than Sync code.


Ok, enough with performance. Besides that, why should I use Node.JS ?

1. It's open source. The community is growing, and you can find a variety of libraries for your server application. There are many implementations for every task, and no need to pay for license.
2. It's a low-level, lightweight and standalone framework.
If you want to install IIS, you need to install the whole .NET framework. That's heavy.
3. It's cross-platform. For example: you can write Node.JS code in Windows environment, and move it to Linux with ease.
4. No multithreading / locking bugs. As mentioned, your code doesn't include threads.
5. It's very easy to write Asynchronous code (which is efficient than synchronous code) and thus create non-blocking I/O.
6. You can use the same javascript code in the client and the server. For example: form validation.
7. JavaScript is becoming more and more popular. Now, a company can hire a developer for both client and server programming (Unlike C#, PHP and so on).
8. You can also check out this cool article: http://www.toptal.com/nodejs/why-the-hell-would-i-use-node-js  which explains the benefits of node.js.

And why not ?

1. There isn't a remarkable IDE for developing Node.JS server application. 
I'm working currently with "Notepad++" text editor, and "node-inspector" for debugging.
2. Async code is not readable as Sync code.
3. Node.JS is a young and immature framework. You should closely check the libraries you choose to add to your server application. Some of them can have insufficient documentation and support on the web. Some of the APIs change across versions, and some will die.
4. No convenient local server hosting manager (like IIS). You can deploy your server applications to cloud solutions (nodejitsu, nodester and so on..), but I couldn't find a server local manager tool for all the apps.

What about use-cases ?

I think that post: http://nodeguide.com/convincing_the_boss.html explains it well.

Finally, which web-sites already uses Node.JS ?

https://github.com/joyent/node/wiki/Projects,-Applications,-and-Companies-Using-Node

Tuesday, January 25, 2011

3 fast & easy ways to accelerate database operations when using LINQ & Entity Framework

Hi all,
Lately I had to handle a very large database.
I have been using Entity Framework model and LINQ queries, and encountered some performance difficulties. I didn't had time to start writing caching wrappers, so I came up with 3 quick main solutions:

Reading table rows was slow:
1. First thing was pretty obvious and probably known to you all: Indexing my table.
Indexing improves the speed of data retrieval operations on a database table at the cost of slower writes and increased storage space.
Indexing is based on sorting the table, so INSERT (or UPDATE of the index key) will cause the database engine to search the right place for the new record.
Use it when your application performs massive read operations against a few write operations.
Although indexing can be useful, it's important to follow those configuration guidelines (also considering whether to define Clustered or Non-Clustered index):
http://msdn.microsoft.com/en-us/library/ms179560.aspx


2. Most people don't know about a great .NET class named "CompiledQuery".
As you probably know, each time you run a LINQ query it is being translated to a SQL Statement. So if the translation engine (SQOT - Standard Query Operator Translation) translates the same query each time, why not doing it only once?
That's when "Compiled Query" comes into play.
Suppose you need to get a city by city ID many times, This is how it gets done:
public static readonly Func<MoviesContext, string, IQueryable<City>> CityByID =
CompiledQuery.Compile((MoviesContext context, string cityID) =>
context.Cities.Where(p => p.CityID == cityID));
First, you declare the method delegate as 'static' because all of the threads are using the same compiled query. Second, it's better to declare it as readonly - because the declaration does not suppose to change across the program.
Let's take a look at the Func arguments. The first argument is the type of the Entity Framework model, the second represents the city ID type, and the last one is the return type (query result type).
"CityByID" will be used to call the compiled query method.
(MoviesContext context, string cityID) - Sending the EF context and city id to the compiled query method.
context.Cities.Where(p => p.CityID == cityID) - Performing the query
CityByID(new MoviesContext(), id); - Calling the compiled query
Important: Using methods that cause a change in the query (For example: First(), FirstOrDefault and so on) will produce a not compiled query, and will take more time rather than using a regular LINQ with those kind of methods. You can solve it by doing: compiledQuery.AsEnumerable().First();
That way, the compiled query is being performed on the database (LINQ to SQL), and only afterwards selecting the first element (LINQ To Entities).

Inserting table rows was slow:
3. Try to minimize use of the famous ObjectQuery.SaveChanges() method (Reminder: This method persists all changes in the EF object context to the database) .
Suppose you have to add some new cities records to your database, It will be slower doing it that way:
foreach (City city in cities)
{
context.Cities.AddObject(city);
context.SaveChanges();
}
rather than keeping the "SaveChanges()" method out of the foreach loop:
foreach (City city in cities)
{
context.Cities.AddObject(city);
}
context.SaveChanges();
When SaveChanges() gets called it creates an IEntityAdapter object if one doesn't already exist. Each call will initiate database connection.
Now a little bit off-topic in order to explain how SaveChanges method is working:
After the provider creation, it generates many SQL Commands with the changes.
For example: after inserting one row to city table, I've looked at the SQL Profiler and found out the generated SQL Command:
"exec sp_executesql N'insert [dbo].[City]([CityID], [CityName])
values (@0, @1)
',N'@0 nchar(10),@1 nchar(10)',@0=N'8b3f07 ',@1=N'fde39c3 '"
In conclusion: Use less calls to SaveChanges in order to decrease the amount of round trips to the database.
You can read about SaveChanges() performance comprasion over here:

To sum up I have made performance tests (considering 2,3 paragraphs on a non-indexed table):
1. Inserting 10,000 city rows: SaveChanges() after each insert to the object context VS. SaveChanges() after insert all cities to the object context.

Inside Loop: 00:01:04.3431638
Outside Loop: 00:00:17.4012899

2. Getting 10,000 different cities (CityID by CityName): Using CompiledQuery VS. Not using CompiledQuery
Compiled: 00:56.025
Not Compiled: 00:01:19.989

Thank you Blogger, hello Medium

Hey guys, I've been writing in Blogger for almost 10 years this is a time to move on. I'm happy to announce my new blog at Med...