MongoDB Basics – Part 2 (CRUD Operaions)

Friends, After MongoDB basic overview and system setup now let’s discuss some basic CRUD operations on MongoDB.

First start MongoDB service which we installed in previous article using below command. You can change the db and log path as per your convenience –

Step-1 : Install service

>mongod –dbpath D:\MongoDbFiles\data –logpath “D:\MongoDbFiles\logs\mongo.logs” –logappend –install –serviceName mdb27017 –serviceDisplayName “MongoDB Server Instance 27017” -serviceDescription “MongoDB Server Instance running on 27017”

Step-2 : Start Service

>net start mdb27017

Step-3 : Start mongo client/shell

>mongo OR mongo.exe

As we have three things in MongoDB which are Database, Collection and Document. So lets do some CRUD operation on these.

CRUD Operations on Database (In MongoDB, databases hold collections of documents) – 

  1. Create => use DATABASE_NAME command will create a new database if it doesn’t exist, otherwise it will switch to the existing database.
    • > use TestDB 
    • switched to db TestDB
  2. Read => db command is use to display current database name and show dbs use to display all database names. If a database database does not have any record then it will not display in the list.
    • > db
    • TestDB
    • > show dbs
    • admin 0.00 GB
      local    0.00 GB
  3. Update => We have two options to rename a database. First, copy database with the new name using db.copyDatabase() method and second is create a backup of database using mongodump utility program and restore with a new name using mongorestore utility and then delete the old database. Make sure that new database is created before deleting old database.
    • Rename with Database Copy
      • > db.copyDatabase(‘old_database_name’, ‘new_database_name’)
      • { “ok” : 1 }
    • Rename with Backup/Restore
      • Backup => mongodump is a utility for creating a binary export of the contents of a database. Since its a program not command so we have to run it from the system command prompt, not the mongo shell. 
      • > mongodump –db TestDB
      • Restore => mongorestore program writes data from a binary database dump created by mongodump to a MongoDB instance. Since its also a program not command so we have to run it from the system command prompt, not the mongo shell. 
      • mongorestore –db NewTestDatabase ./dump/TestDB
  4. Delete => db.dropDatabase() is used to drop the current database.
    • > db.dropDatabase()
    • { “dropped” : “TestDB”, “ok” : 1 }

 

CRUD Operations on MongoDB Collections (Collections are analogous to tables in relational databases and stores documents)- 

  1. Create – There are two ways to create collections-
    • Implicit Creation – MongoDB also creates the collection when you first store data for that collection i.e If the collection does not exist, insert operations will create the collection automaticaly.
    • Explicit Creation – 
      • MongoDB provides the db.createCollection() method to explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.
      • db.createCollection(“myExplicitCollection2”, { capped : true, size : 6142800, max : 10000 } )
      • { “ok” : 1 }
  2. Read – show command is used to display all available collections 
    • > show collections
    • impCollection
      myExplicitCollection
  3. Update – db.COLLECTION_NAME.renameCollection(target, dropTarget) is use to update the collection name
    • > db.myNewCollection.renameCollection(“myNewRenamedCollection”, true)
    • { “ok” : 1 }
  4. Delete – db.COLLECTION_NAME.drop() is use to delete a collection
    • > db.myNewCollection.drop()
    • true

 

CRUD Operations on MongoDB Documents (MongoDB documents is a set of key-value pairs and basic unit of data LIKE row in the RDBMS)  –

  1. Create – Below are some methods to create documents
    • db.COLLECTION_NAME.insert(<document or array of documents>) – It allows you to insert One or more documents in the collection and Returns a WriteResult object
      • > db.testCollection.insert({a:10})
        WriteResult({ “nInserted” : 1 })
      • In the inserted document, if we don’t specify the _id parameter, then MongoDB assigns a unique ObjectId for this document
      • deprecated in major driver
    • db.COLLECTION_NAME.insertOne(document) – It allows you to insert exactly 1 document in the collection and returns the document.
      • > db.testCollection.insertOne({ _id: 10, name: “jogendra”})
        { “acknowledged” : true, “insertedId” : 10 }
    • db.COLLECTION_NAME.insertMany() –  It allows you to insert an array of documents in the collection
      • > db.testCollection.insertMany([{ _id: 1, name: “jogendra”},{name: “anmol”}])
      • {
        “acknowledged” : true,
        “insertedIds” : [
        1,
        ObjectId(“59b97fbf6edbc77428869950”)
        ]
        }
    • db.COLLECTION_NAME.save()
      • > db.testCollection.save({ name :”sahib”, age : 4.5})
  2. Read – 
    1. Select All Documents in a Collection. 
      • >db.COLLECTION_NAME.find(query, projection)

        • query – Optional. Specifies selection filter
        • projection – Optional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter
      • >db.testCollection.find({}) OR db.testCollection.find()
        { “_id” : 1, “name” : “jogendra”, “age” : 30 }
        { “_id” : 2, “name” : “anmol”, “age” : 5 }
        { “_id” : 3, “name” : “bani”, “age” : 5 }
      • To display the results in a formatted way, you can use pretty() method
    2.  Return only Selected Fields- We need to pass in the second parameter i.e projection for required fields only. _id fields always returns if not explicitly excluded.
      • db.testCollection.find({ age : 5}, {_id:false, name : true})
      • { “name” : “anmol” }
        { “name” : “bani” }
    3. Select one document in a Collection
      • db.COLLECTION_NAME.findOne(query, projection)
        • Without query returns the first document from the collection
          • db.testCollection.findOne()
          • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
        • With a Query Specification returns the first matching document from the bios collection.
          • db.testCollection.findOne({age:5})
          • { “_id” : 2, “name” : “anmol”, “age” : 5 }
    4. RDBMS Where Clause Equivalents in MongoDB – All operations are on below documents-
      { “_id” : 1, “name” : “jogendra”, “age” : 30 }
      { “_id” : 2, “name” : “anmol”, “age” : 5 }
      { “_id” : 3, “name” : “bani”, “age” : 5 } 

      • Equality (=)
        • Syntax- {<key>:<value>}
        • Ex- Select all documents where age=5
        • > db.testCollection.find({age:5})
        • { “_id” : 2, “name” : “anmol”, “age” : 5 }
          { “_id” : 3, “name” : “bani”, “age” : 5 }
      • Less Than (<)
        • Syntax- {<key>:{$lt:<value>}}
        • Ex- Select all documents where age < 5
        • > db.testCollection.find({age:{$lt:50}})
        • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
          { “_id” : 2, “name” : “anmol”, “age” : 5 }
          { “_id” : 3, “name” : “bani”, “age” : 5 }
      • Less Than Equals (<=)
        • Syntax- {<key>:{$lte:<value>}}
        • > db.testCollection.find({age:{$lte:5}})
        • { “_id” : 2, “name” : “anmol”, “age” : 5 }
          { “_id” : 3, “name” : “bani”, “age” : 5 }
      • Greater Than ( > )
        • Syntax – {<key>:{$gt:<value>}}
        • > db.testCollection.find({age:{$gt:5}})
        • “_id” : 1, “name” : “jogendra”, “age” : 30 }
      • Greater Than Equals ( >= )
        • Syntax – {<key>:{$gte:<value>}}
        • > db.testCollection.find({age:{$gte:30}})
        • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
      • Not Equals ( != )
        • Syntax – {<key>:{$ne:<value>}}
        • db.testCollection.find({age:{$ne:30}})
        • { “_id” : 2, “name” : “anmol”, “age” : 5 }
          { “_id” : 3, “name” : “bani”, “age” : 5 }
      • Like (%text%)
        • name like ‘%o%’ => contains [ / o  /]
          • > db.testCollection.find({name : /o/})
        • name like ‘j%’ => start with [ / ^ J / ]
          • > db.testCollection.find({name : / ^j /})
        • name like ‘%j’ => end with [ / i $/ ]
          • > db.testCollection.find({name : /i$/})

    5. AND in MongoDB ($and )- In the find() method, if you pass multiple keys in a array then MongoDB treats it as AND condition
      • Syntax – >
        db.testCollection.find( { $and: [ {key1: value1}, {key2:value2}] })
      • > db.testCollection.find({$and : [{age:5}, {name:”anmol”}]})
      • { “_id” : 2, “name” : “anmol”, “age” : 5 }
    6. OR in MongoDB ( $or )
      • db.testCollection.find( { $or: [ {key1: value1}, {key2:value2}] })
      • > db.testCollection.find({ $or : [{age:30}, {name : “anmol” }]})
      • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
        { “_id” : 2, “name” : “anmol”, “age” : 5 }
    7. Using AND and OR Together
      • Ex- where age <= 50 AND (name = “Jogendra” OR name = “bani”)
      • > db.testCollection.find({ age:{$lte:50}, $or:[{name :”jogendra”} , {name : “bani” }]})
      • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
        { “_id” : 3, “name” : “bani”, “age” : 5 }
  3.  Update – 
    • Update a Single Document-
      • db.collection.updateOne(filter, update, options)
        • Updates a single document within the collection based on the filter.
        • > db.testCollection.updateOne({_id:1}, {$set: {name:”Jogendra Singh”, age : 31}})
        • { “acknowledged” : true, “matchedCount” : 1, “modifiedCount” : 1 }
        • > db.testCollection.updateOne({_id:1}, {$set: {name:”Jogendra Singh”, age : 31}, $currentDate: { lastModified: true }})
        • { “_id” : 1, “name” : “Jogendra Singh”, “age” : 31, “lastModified” : ISODate(“2017-09-14T19:16:31.167Z”) }
        •  $set – to update the value of the field
        • $currentDate – to update the value of the lastModified field to the current date
      • db.collection.update(query, update, options)
        • Either updates or replaces a single document that match a specified filter or updates all documents that match a specified filter.
    • Update Multiple Documents
      • db.collection.updateMany(filter, update, options)
        • Updates multiple documents within the collection based on the filter.
        • db.testCollection.updateMany({ $or: [{name:”bani”},{name : “anmol”}]}, { $set : {class: “LKG”}})
        • { “_id” : 2, “name” : “anmol”, “age” : 5, “class” : “LKG” }
          { “_id” : 3, “name” : “bani”, “age” : 5, “class” : “LKG” }
        • db.testCollection.updateMany({ age : {$lt: 30} }, { $set : {city : “Delhi”} })
        • { “_id” : 2, “name” : “anmol”, “age” : 5, “class” : “LKG”, “city” : “Delhi” }
          { “_id” : 3, “name” : “bani”, “age” : 5, “class” : “LKG”, “city” : “Delhi” }
    • Replace a Document
      • db.collection.replaceOne(filter, replacement, options)
        • Replaces a single document within the collection based on the filter.
        • To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne()
        • db.testCollection.replaceOne({“_id” : 3}, { firstname : “Gurbani”, lastname : “kaur”, age : 2.5})
        • { “_id” : 3, “firstname” : “Gurbani”, “lastname” : “kaur”, “age” : 2.5 }
    • Rename field name
      • $rename
        • The $rename operator updates the name of a field
        • db.testCollection.update({“_id”: 3}, {$rename : {firstname : “First-Name”}})
        • { “_id” : 3, “lastname” : “kaur”, “age” : 2.5, “First-Name” : “Gurbani” }
  4. Delete – 
    • db.collection.remove()
      • Removes documents from a collection.
      • he db.collection.remove() method can have one of two syntaxes. The remove() method can take a query document and an optional justOne boolean.
      • >db.testCollection.remove({“_id” : ObjectId(“59b992326edbc77428869952”)})
    • db.collection.deleteOne(filter, { writeConcern: <document>, collation: <document> })
      • > db.testCollection.deleteOne({$and : [{name:”sahib”},{age:4.5}]})
      • { “acknowledged” : true, “deletedCount” : 1 }
    • db.collection.deleteMany(<filter>, { writeConcern: <document>, collation: <document> })
      • Delete all documents that match a specified filter.
      • > db.testCollection.deleteMany({age : {$gte : 50}})

 

https://docs.mongodb.com/manual/reference/method/

Programming is Easy…

 

 

Advertisements

MongoDB Basics – Part 1

 MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling.

MongoDB stores data in flexible BSON documents meaning fields can vary from document to document and data structure can be changed over time. BSON is a binary representation of JSON documents, though it contains more data types than JSON.

Let’s understand the terms used in MongoDB-

  1. Database – 
    • A database is an organized collection of data.
    • A physical container for collections. Each database gets its own set of files on the file system.
    • MongoDB databases hold collections of documents.
  2. Collection –
    • Collection is a group of MongoDB documents.
    • It is the equivalent of an RDBMS table. A collection exists within a single database.
    • Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.
    • MongoDB collections hold data records i.e BSON documents.
  3. Documents –
    • A record in a MongoDB collection.
    • Documents are analogous to JSON objects(but exist in the database in a more type-rich format known as BSON).
    • MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON
    • Documents have dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.
    • MongoDB documents is a set of key-value pairs and basic unit of data.

mongo

 


Components ?

Mongo.exe =>  The mongo shell is an interactive JavaScript interface to MongoDB and is a component of the MongoDB package. You can use the mongo shell to query and update data as well as perform administrative operations. we can start the mongo shell by using the mongo command in the command prompt.

mongo2.PNG


Features ?

  1. High PerformanceMongoDB provides high performance data persistence. In particular-
    • Support for embedded data models reduces I/O activity on database system.
    • Indexes support faster queries and can include keys from embedded documents and arrays. Rich Query Language
  2. Rich Query LanguageMongoDB supports a rich query language to support read and write operations (CRUD) as well as:
  3. High Availability – MongoDB’s replication facility, called replica set(A replica set is a group of MongoDB servers that maintain the same data set, providing redundancy and increasing data availability.), provides:
    • automatic failover and
    • data redundancy.
  4. Horizontal Scalability – MongoDB provides horizontal scalability as part of its core functionality:
    • Sharding distributes data across a cluster of machines.
    • MongoDB 3.4 supports creating zones of data based on the shard key. In a balanced cluster, MongoDB directs reads and writes covered by a zone only to those shards inside the zone. See the Zones manual page for more information.
  5. Support for Multiple Storage Engines – MongoDB supports multiple storage engines, such as:
    • WiredTiger Storage Engine
    • MMAPv1 Storage Engine.

 


 

Environment Setup- 

  1. Download and Install latest version from – https://docs.mongodb.com/manual/installation/
    • Let’s assume default installation directory is – C:\Program Files\MongoDB\Server\3.4\bin
  2. Set Env Path variable to – C:\Program Files\MongoDB\Server\3.4\bin
    • Now check the version using below command to ensure that path is setup correctly- C:\Users\jogen>mongo -version
  3. MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is “C:\data\db”
  4. If you want to store the data files at different location so we can set the preferred location path using –dbpath as below then it will show waiting for connections message on the console output, which indicates that the mongod.exe process is running successfully. If this path contains spaces then put all its path in double qoutes.
    • C:\Users\jogen>mongod –dbpath “D:\MongoDbFiles\data”
  5. Set log path – used by mongo daemon process,for flush out logs instead of in standard console as-
    • C:\Users\jogen>mongod –logpath “D:\MongoDbFiles\logs\mongo.logs” –logappend
  6. Set port using –port, default is- 27017

We can also specify above configuration option using a config file. Config file is just text file, containing the parameters in the key=value form and each one is specified on the every line of file. We basically provide file path (which contains the configurations) as command line option as “-f” or “–config” as below-

mongo2

  • C:\Users\jogen>mongod –f D:\Servers\mongodb\config\mongodb.conf
  • C:\Users\jogen>mongod –config D:\Servers\mongodb\config\mongodb.conf

Start/Stop MongoDB using the Windows services –

MongoDB also comes with excellent support to turn your MongoDB server into a windows service that gets launched automatically at startup.

  • –install : command line switch to install the service
  • –remove : command line switch to remove the service
  • –serviceName :  the name for mongod windows service and must adhere to naming services in windows like only accepting the alphanumeric chars with no spaces
  • –serviceDisplayName : Display name for service that is shown in services console, put this in double quotes if contains the spaces
  • –serviceDescription   : Small description about service, put this in double quotes if contains the spaces

To do this open command prompt with admin rights and fire below on the shell-

mongod –dbpath “D:\MongoDbFiles\data” –logpath “D:\MongoDbFiles\logs\mongo.logs” –logappend –install –serviceName mdb27017 –serviceDisplayName “MongoDB Server Instance 27017” –serviceDescription “MongoDB Server Instance running on 27017”

In log path specified, you can check for the whether windows services started or not or look into services.msc for –

mongo2.PNG

 


 

GUI tool for MongoDB –

Robo 3T (formerly Robomongo) is the free lightweight GUI for MongoDB enthusiasts.

https://robomongo.org/

 

Programming is Easy…

 

How Logical Operators work in JavaScript?

Let’s understand the Logical Operators and how they work in JavaScript…

  1. Logical AND (&&)
  2. Logical OR (||)
  3. Logical NOT (!)

Logical operators are typically used with Boolean values but can also be used with non-Boolean values-

=> When values are Boolean then they return a Boolean value

=> When values are non-Boolean then they may return a non-Boolean value. In this case && and || operators actually return the value of one of the specified operands

LogicalOperators.PNG

LogicalOperators1.PNG

Programming is Easy…

 

What happens when we type a URL in the browser (In Depth)?

If you are reading this then i would recommend to read this  article first for a clear visibility that what we will understand in depth 🙂

https://jogendras.wordpress.com/2017/07/17/what-happens-when-we-type-a-url-in-the-browser/

Have you ever wondered, precisely – 

  • What happens in the background when we type a URL in the browser?
  • How does a web page life-cycle sequence work?
  • How browser knows, where to send request for the requested page?
  • What happens on the Web Server when a request for a web page comes in?
  • How does the Web server handle the incoming request?
  • How is the HTML that is emitted to the client generated?
  • How browser renders the page on the screen?
  • Etc…

If you are also looking answers of above mentioned questions then this article is definitely for you. In this article, we will take a deeper look at the sequence of events that take place when we visit a ASP.NET page URL –

  1. URL is typed in address bar of the browser
  2. The browser parses the URL to find the protocol, host, port, and path. Ex- http://www.jogendras.com/about/ will be parsed as-
    • Protocol – http
    • Hostname – http://www.jogendras.com
    • URL path – /about
  3. Browser checks cache, if requested object is in cache and is fresh then return response from cache.
  4. The browser looks up the IP address for the entered domain name.  When we want to connect to www. google.com, we actually want to reach out to a server where web application is hosted. One such server is having an IP address of XX.XXX.XXX.XX. Now, if we type http:// XX.XXX.XXX.XX in the browser, this will take us to www. google.com itself. Which means, www. google.com and http://XX. XXX.XXX.XX are nothing but same stuff. But, it is not so. 
    As google has multiple servers in multiple locations to cater to the huge volume of requests. Thus we should let application decide which server is best suited to our needs. Using www. google.com does the job for us. When we type www. google.com DNS services comes into play and resolves the URL to a proper IP address. The DNS lookup proceeds as follows-

    • Browser cache – The browser maintain cache of DNS records for some time. So, this is the first place to resolve DNS queries. If not found in browser’s cache then it makes a system call to underlying OS to fetch the record.
    • OS makes a DNS lookup and replies the IP address to the browser: OS uses the DNS client service to find the IP address- win + r => services.mscDNSCIt first checks in Hosts file and then-
      • OS cache – If not found in hosts file then it checks in OS local DNS cache.
      • Router cache – If above steps fail to get a DNS record, the search continues to your router which has its own cache
      • ISP DNS cache – If above also fails then search moves on to ISP’s DNS server, first, it tries in its cache if not found then ISP’s DNS recursive search comes into the picture.
      • Recursive search – If everything fails then recursive search begins from the root level namesever.  For the DNS enthusiasts – here is a great guide worth reading
  5. As, now browser knows the domain’s IP address so a socket needs to be opened from the user’s computer to that IP number, on the port specified (most often port 80)
  6. When a connection is open browser sends the HTTP request to the host server.
  7. On the server protocol listeners receive protocol-specific requests. In this case we have http request so HTTP/S listener i.e http.sys (Hypertext Transfer Protocol Stack) first listen the http request from network. Now, HTTP.SYS is Responsible to pass the request to the particular web server application i.e IIS or Apache etc.. and send response back to the client browsers… Let’s assume we have .net web application request so request will go to IIS.image1abhijit20jana_634041501195202656_withall
    • HTTP.sys contacts WAS to obtain information from the configuration store
    • WAS requests configuration information from the configuration store, applicationHost.config
    • The WWW Service receives configuration information, such as application pool and site configuration
    • Now we know the application pool so WAS starts a worker process(w3wp.exe) for the application pool to which the request was made.
    • The worker process “w3wp.exe” looks up the URL of the request to load the correct ISAPI (Internet Server Application Programming Interface => a low level unmanged Win32 API) extension. ASP.NET interfaces with IIS through an ISAPI extension. ISAPI is the first and highest performance entry point into IIS. 
    • Depending on the extension ASP.NET routes the request to an appropriate handler that is responsible for picking up requests.

Coming Soon….. 🙂

 

https://docs.microsoft.com/en-us/iis/get-started/introduction-to-iis/introduction-to-iis-architecture

Beginner’s Guide: How IIS Process ASP.NET Request

 

Programming is Easy…

What happens when we type a URL in the browser?

If you are curious to know what happens in the background when we type a URL in the browser then this article is definitely for you. Below are the sequence of events that occurs when we enter a URL in the browser’s address bar-

  1. You type the URL into address bar in your preferred browser
  2. The browser parses the URL to find the protocol, host, port, and path.
  3. Browser checks cache, if requested object is in cache and is fresh, skip to #15
  4. Browser asks OS for entered domain’s IP address
  5. OS makes a DNS lookup and replies the IP address to the browser
  6. Browser opens a TCP connection to the server
  7. When a connection is open, browser sends the HTTP request to the host
  8. The host forwards the request to the server software (most often Apache, IIS) configured to listen on the specified port
  9. Server handles the incoming request i.e server inspects the request (most often only the path), and launches the server plugin needed to handle the request (corresponding to the server language you use, PHP, Java, .NET, Python?)
  10. The server plugin gets access to the full request, and starts to prepare a HTTP response.
  11. Server sends the HTTP response back to the browser
  12. Browser receives HTTP response and may close the TCP connection, or reuse it for another request
  13. Browser checks if the response is a redirect or a conditional response (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  14. If cache-able, response is stored in cache
  15. Browser decodes response (e.g. if it’s gzipped)
  16. Browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound clip?) Browsers often use the MIME-type to determine what default action to do when a resource is fetched.
  17. If response is HTML then browser parses the HTML. A DOM tree is built out of the response HTML. New requests are made to the server for each new resource that is found in the HTML source (typically images, style sheets, and JavaScript files). Go back to step#7 and repeat for each resource. StyleSheets are parsed, and the rendering information in each gets attached to the matching node in the DOM tree. Javascript is parsed and executed, and DOM nodes are moved and style information is updated accordingly. The browser renders the page on the screen according to the DOM tree and the style information for each node
  18. Browser renders response, or offers a download dialog for unrecognized types

 

Hopefully this gives you a better idea of how a URL get proceeds 🙂

 

Programming is Easy…

Does Session use cookies in Asp.Net?

It’s very confusing for many developers that session use cookies or not, and also a interesting interview question for .net developer 🙂 Let’s understand the relation between session and cookies-

Does session use cookies? Answer is- YES and NO.

One more confusion?

While using session in the application we have two things which are SessionID which is used to uniquely identify the session variables and Session Value which is the actual data stored in the session variables.

As session is a server side and cookies are client side state management techniques, so session actual data always stored on the server memory by default. The following list describes the available session storage modes-

  • InProc mode, which stores session state in memory on the Web server. This is the default.
  • StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • Custom mode, which enables you to specify a custom storage provider.
  • Off mode, which disables session state.

I hope it’s clear that session data is stored on the server and has no relationship with the cookies.

Now let’s understand the session keys storage types-

 

 

 

 

Session and cookies relationship are limited to only session keys not session value.

 

Session use cookies – Yes :  By default Session key is stored in an HTTP  non-persistent cookie that the client sends to the server (and server to client) on each request/responses. The server can then read the key from the cookie and re-inflate the server session state.

If we will try to run below code after disabled the cookies then it will not work that proves that session use the cookies.

Session use cookies – No : There is the possibility that browser does not support cookie or disabled, then asp.net can not create a cookie to store session keys. ASP.NET offers an alternative in the form of cookieless sessions. You can configure your application to store session keys not in a cookie, but in the URLs. This can be done by setting cookieless=”true” in the web.config file  as-

<configuration>
<sessionstate cookieless=”true” />
</configuration>

http://localhost/(lit3py55t21z5v55vlm25s55)/Application/SessionState.aspx

 

Programming is Easy…

What is ES-5, ES-6 or ES2015 and TypeScript? [ES = ECMAScript]

Before discussing ES5 or ES6 let’s discuss what actually is ECMAScript-

ECMAScript is a standard, JavaScript is an implementation of that standard. ECMAScript defines the standard and browsers implement it.

In a similar way, HTML specifications (most recently HTML5) are defined by the organising body and are implemented by the browser vendors. Different browsers implement specifications in different ways, and there’s varying amounts of support for different features.

  1. ES5-  ES5 is the JavaScript we know today and use in web applications. It does not require a build step to transform it into something that will run in today’s browsers.
  2. ES6 – Also called ES2015 is the next iteration of JavaScript with many enhanced features(http://es6-features.org) but it does not run in today’s browsers. So we need a transpiler like Babel that will export ES5 code means it will compile ES6 code to ES5 code that today’s browsers support and can be run easily in the today’s browsers. 
  3. TypeScript – TypeScript is a typed superset of JavaScript that also compiles to plain JavaScript. This is pulling in features from ES6, ES7… Or future’s JavaScript. It help us to write safe JavaScript code means mistakes in JavaScript code can be noticed at development time due to it’s compile feature. As this is the superset of JavaScript so it contains JavaScript and some additional features as well.