State Management – A complete understanding – Session – Part – I

What is Session?

Web is stateless, which means a new instance of a web page class is re-created each time the page is posted to the server. As we all know, HTTP is a stateless protocol, it can’t hold client information on a page. If the user inserts some information and move to the next page, that data will be lost and the user would not be able to retrieve that information. What do we need here? We need to store information. Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis. Have a look at the following diagram:

explor2.jpg

Fig: For every client, session data is stored separately

State management using session is one of the best ASP.NET features, because it is secure, transparent from users, and we can store any kind of object in it. Along with these advantages, some times session can cause performance issues in high traffic sites because it is stored in server memory and clients read data from the server. Now let’s have a look at the advantages and disadvantages of using session in our web applications.

Advantages and disadvantages of Session?

Following are the basic advantages and disadvantages of using session. I have describe in details with each type of session at later point of time.

Advantages:

  • It helps maintain user state and data all over the application.
  • It is easy to implement and we can store any kind of object.
  • Stores client data separately.
  • Session is secure and transparent from the user.

Disadvantages:

  • Performance overhead in case of large volumes of data/user, because session data is stored in server memory.
  • Overhead involved in serializing and de-serializing session data, because in the case of StateServer and SQLServer session modes, we need to serialize the objects before storing them.

Besides these, there are many advantages and disadvantages of session that are based on the session type. I have discussed all of them in the respective sections below.

Storing and retrieving values from Session

Storing and retrieving values in session are quite similar to that in ViewState. We can interact with session state with theSystem.Web.SessionState.HttpSessionState class, because this provides the built-in session object in ASP.NET pages.

The following code is used for storing a value to session:

//Storing UserName in Session
Session["UserName"] = txtUser.Text;

Now, let’s see how we can retrieve values from session:

//Check weather session variable null or not
if (Session["UserName"] != null)
{
    //Retrieving UserName from Session
    lblWelcome.Text = "Welcome : " + Session["UserName"];
}
else
{
 //Do Something else
}

We can also store other objects in session. The following example shows how to store a DataSet in session.

//Storing dataset on Session
Session["DataSet"] = _objDataSet;

The following code shows how we to retrieve that DataSet from session:

//Check weather session variable null or not
if (Session["DataSet"] != null)
{
    //Retrieving UserName from Session
    DataSet _MyDs = (DataSet)Session["DataSet"];
}
else
{
    //Do Something else
}

References:

Session ID

ASP.NET uses an 120 bit identifier to track each session. This is secure enough and can’t be reverse engineered. When a client communicates with a server, only the session ID is transmitted between them. When the client requests for data, ASP.NET looks for the session ID and retrieves the corresponding data. This is done in the following steps:

  • Client hits the web site and information is stored in the session.
  • Server creates a unique session ID for that client and stores it in the Session State Provider.
  • The client requests for some information with the unique session ID from the server.
  • Server looks in the Session Providers and retrieves the serialized data from the state server and type casts the object.

Take a look at the the pictorial flow:

Fig: Communication of client, web server, and State Provider

References:

Session Mode and State Provider

In ASP.NET, there are the following session modes available:

  • InProc
  • StateServer
  • SQLServer
  • Custom

For every session state, there is a Session Provider. The following diagram will show you how they are related:

Fig: Session state architecture

We can choose the session state provider based on which session state we are selecting. When ASP.NET requests for information based on the session ID, the session state and its corresponding provider are responsible for sending the proper information. The following table shows the session mode along with the provider name:

Session State Mode State Provider
InProc In-memory object
StateServer Aspnet_state.exe
SQLServer Database
Custom Custom provider

Apart from that, there is another mode Off. If we select this option, the session will be disabled for the application. But our objective is to use session, so we will look into the above four session state modes.

Session States

Session state essentially means all the settings that you have made for your web application for maintaining the session. Session State itself is a big thing. It says all about your session configuration, either in theweb.config or from the code-behind. In the web.config,<SessionState> elements are used for setting the configuration of the session. Some of them are Mode, Timeout, StateConnectionString,CustomProvider, etc. I have discussed about each and every section of the connection string. Before I discuss Session Mode, take a brief overview of session events.

Session Event

There are two types of session events available in ASP.NET:

  • Session_Start
  • Session_End

You can handle both these events in the global.asax file of your web application. When a new session initiates, the session_start event is raised, and the Session_End event raised when a session is abandoned or expires.

void Session_Start(object sender, EventArgs e) 
{
    // Code that runs when a new session is started
}

void Session_End(object sender, EventArgs e) 
{
    // Code that runs when a session ends. 
}

References:

Session Mode

I have already discussed about session modes in ASP.NET. Following are the different types of session modes available in ASP.NET:

  • Off
  • InProc
  • StateServer
  • SQLServer
  • Custom

If we set session Mode="off" in web.config, session will be disabled in the application. For this, we need to configure web.config the following way:

InProc Session Mode

This is the default session mode in ASP.NET. Its stores session information in the current Application Domain. This is the best session mode for web application performance. But the main disadvantage is that, it will lose data if we restart the server. There are some more advantages and disadvantages of the InProc session mode. I will come to those points later on.

Overview of InProc session mode

As I have already discussed, in InProc mode, session data will be stored on the current application domain. So it is easily and quickly available.

InProc session mode stores its session data in a memory object on the application domain. This is handled by a worker process in the application pool. So if we restart the server, we will lose the session data. If the client request for data, the state provider read the data from an in-memory object and returns it to the client. In web.config, we have to mention the session mode and also set the timeout.

explor3.gif

The above session timeout setting keeps the session alive for 30 minute. This is configurable from the code-behind too.

Session.TimeOut=30;

There are two types of session events available in ASP.NET:Session_Start() and Session_End and this is the only mode that supports the Session_End() event. This event is called after the session timeout period is over. The general flow for the InProc session state is like this:

When the Session_End() is called depends on the session timeout. This is a very fast mechanism because no serialization occurs for storing and retrieving data, and data stays inside the same application domain.

When should we use the InProc session mode?

InProc is the default session mode. It can be very helpful for a small web site and where the number of users is very less. We should avoid InProc in a Web Garden scenario (I will come to this topic later on).

Advantages and disadvantages

Advantages:
  • It store session data in a memory object of the current application domain. So accessing data is very fast and data is easily available.
  • There is not requirement of serialization to store data in InProc session mode.
  • Implementation is very easy, similar to using the ViewState.
Disadvantages:

Although InProc session is the fastest, common, and default mechanism, it has a lot of limitations:

  • If the worker process or application domain is recycled, all session data will be lost.
  • Though it is the fastest, more session data and more users can affect performance, because of memory usage.
  • We can’t use it in web garden scenarios.
  • This session mode is not suitable for web farm scenarios.

As per the above discussion, we can conclude that InProc is a very fast session storing mechanism but suitable only for small web applications. InProc session data will get lost if we restart the server, or if the application domain is recycled. It is also not suitable for Web Farm and Web Garden scenarios.

Now we will have a look the other options available to overcome these problems. First comes the StateServer mode.

StateServer Session Mode

Overview of StateServer session mode

This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Service which is independent of IIS and can also be run on a separate server. This session state is totally managed byaspnet_state.exe. This server may run on the same system, but it’s outside of the main application domain where your web application is running. This means if you restart your ASP.NET process, your session data will still be alive. This approaches has several disadvantages due to the overhead of the serialization and de-serialization involved, it also increases the cost of data access because every time the user retrieves session data, our application hits a different process.

Configuration for StateServer session mode

In StateServer mode, session data is stored in a separate server which is independent of IIS and it is handled by aspnet_state.exe. This process is run as a Windows Service. You can start this service from the Windows MMC or from the command prompt.

By default, the “Startup Type” of the ASP.NET state service is set to Manual; we have to set it to Automatic.

From the command prompt, just type “net start aspnet_state”. By default, this service listens to TCP port 42424, but we can change the port from the Registry editor as show in the picture below:

Now have a look at the web.config configuration for the StateServer setting. For the StateServer setting, we need to specify thestateConnectionString. This will identify the system that is running the state server. By default, stateConnectionString used the IP 127.0.0.1 (localhost) and port 42424.

explor9.gif

When we are using StateServer, we can configure thestateNetworkTimeOut attribute to specify the maximum number of seconds to wait for the service to respond before canceling the request. The default timeout value is 10 seconds.

explor10.gif

For using StateServer, the object which we are going to store should be serialized, and at the time of retrieving, we need to de-serialize it back. I have described this below with an example.

How the StateServer Session Mode works

We use the StateServer session mode to avoid unnecessary session data loss when restarting our web server. StateServer is maintained by theaspnet_state.exe process as a Windows service. This process maintains all the session data. But we need to serialize the data before storing it in StateServer session mode.

As shown in the above figure, when the client sends a request to the web server, the web server stores the session data on the state server. The StateServer may be the current system or a different system. But it will be totally independent of IIS. The destination of the StateServer will depend on the web.config stateConnectionString setting. If we set it to 127.0.0.1:42424, it will store data in the local system itself. For changing the StateServer destination, we need to change the IP, and make sure aspnet_state.exe is up and running on that system. Otherwise you will get the following exception while trying to store data on session.

When we are storing an object on session, it should be serialized. That data will be stored in the StateServer system using the State Provider. And at the time of retrieving the data, the State Provider will return the data. The complete flow is given in the picture below:

Example of StateServer Session Mode

Here is a simple example of using the StateServer session mode. I have created this sample web application directly on IIS so that we can easily understand its usage.

Step 1: Open Visual Studio > File > New > Web Sites. Choose Location as HTTP and create the web application.

Now if you open IIS, you will see a virtual directory created with the name of your web application, in my case it is StateServer.

Step 2: Create s simple UI that will take the roll number and the name of a student. We will store the name and roll number in a state server session. I have also created a class StudentInfo. This class is listed below:

[Serializable]
public class StudentInfo
{
    //Default Constructor
    public StudentInfo()
    {
       
    }
    /// <summary>
    /// Create object of student Class
    /// </summary>
    /// <param name="intRoll">Int RollNumber</param>
    /// <param name="strName">String Name</param>
    public StudentInfo(int intRoll, string strName)
    {
        this.Roll = intRoll;
        this.Name = strName;
    }

    private int intRoll;
    private string strName;
    public int Roll
    {
        get
        {
            return intRoll;
        }
        set
        {
            intRoll = value;
        }
    }

    public string Name
    {
        get
        {
            return strName;
        }
        set
        {
            strName = value;
        }
    }
}

Now have a look at the code-behind. I have added two buttons: one for storing session and another for retrieving session.

protected void btnSubmit_Click(object sender, EventArgs e)
{
    StudentInfo _objStudentInfo = 
      new StudentInfo(Int32.Parse( txtRoll.Text) ,txtUserName.Text);
    Session["objStudentInfo"] = _objStudentInfo;
    ResetField();
}
protected void btnRestore_Click(object sender, EventArgs e)
{
    StudentInfo _objStudentInfo = (StudentInfo) Session["objStudentInfo"];
    txtRoll.Text = _objStudentInfo.Roll.ToString();
    txtUserName.Text = _objStudentInfo.Name;
}

Step 3: Configure your web.config for state server as I have already explained. And please make sure aspnet_state.exe is up and running on the configured server.

Step 4: Run the application.

Enter the data, click on Submit.

There are the following tests that I have made which will totally explain how exactly StateServer is useful.

First: Remove the [Serializable ] keyword from the StudentInfoclass and try to run the application. When you click on the Submit button, you will get the following error:

Which clearly says that you have to serialize the object before storing it.

Second: Run the application, store data by clicking on the Submit button. Restart IIS.

In the case of InProc, you will have already lost your session data, but with StateServer, click on Restore Session and you will get your original data, because StateServer data does not depend on IIS. It keeps it separately.

Third: Stop aspnet_state.exe from the Windows Services MMC and submit the data. You will get the following error:

because your State Server process is not running. So please keep in mind these three points when using StateServer mode.

Advantages and Disadvantages

Based on the above discussion:

Advantages:
  • It keeps data separate from IIS so any issues with IIS will not hamper session data.
  • It is useful in web farm and web garden scenarios.
Disadvantages:
  • Process is slow due to serialization and de-serialization.
  • State Server always needs to be up and running.

I am stopping here on StateServer, you will find some more interesting points on it in the Load Balancer, Web Farm, and Web Garden section.

References:

SQLServer Session Mode

Overview of SQL Server Session Mode

This session mode provide us more secure and reliable session management in ASP.NET. In this session mode, session data is serialized and stored in A SQL Server database. The main disadvantage of this session storage method is the overhead related with data serialization and de-serialization. It is the best option for using in web farms though.

To setup SQL Server, we need these SQL scripts:

  • For installing: InstallSqlState.sql
  • For uninstalling: UninstallSQLState.sql

The easiest way to configure SQL Server is using the aspnet_regsqlcommand.

I have explained in detail the use of these files in the configuration section. This is the most useful state management in web farm scenarios.

When should we use SQLServer Session Mode?

  • SQL Server session mode is a more reliable and secure session state management.
  • It keeps data in a centralized location (database).
  • We should use the SQLServer session mode when we need to implement session with more security.
  • If there happens to be frequent server restarts, this is an ideal choice.
  • This is the perfect mode for web farm and web garden scenarios (I have explained this in detail later).
  • We can use SQLServer session mode when we need to share session between two different applications.

Configuration for SQLServer Session Mode

In SQLServer session mode, we store session data in SQL Server, so we need to first provide the database connection string in web.config. ThesqlConnectionString attribute is used for this.

After we setup the connection string, we need to configure the SQL Server. I will now explain how to configure your your SQL Server using the aspnet_regsql command.

Step 1: From command prompt, go to your Framework version directory. E.g.: c:\windows\microsoft.net\framework\<version>.

Step 2: Run the aspnet_regsql command with the following parameters:

Have a look at the parameters and their uses:

Parameters Description
-ssadd Add support for SQLServer mode session state.
-sstype p P stands for Persisted. It persists the session data on the server.
-S Server name.
-U User name.
-P Password.

After you run the command, you will get the following message:

That’s all.

Step 3: Open SQL Server Management Studio, check if a new database ASPState has been created, and there should be two tables:

  • ASPStateTempApplications
  • ASPStateTempSessions

Change the configuration string of the StateServer example and run the same sample application.

Just store the roll number and user name and click on the Submit button. Open the ASPStateTempSessions table from SQL Server Management Studio.. here is your session data:

Now do the following test that I have already explained in the StateServer mode section:

  1. Remove the Serialize keyword from the StydentInfo class
  2. Reset IIS and click on Restore Session
  3. Stop SQL Server Services

I think I have explained the SQLServer session mode well.

Advantages and Disadvantages

Advantages:
  • Session data not affected if we restart IIS.
  • The most reliable and secure session management.
  • It keeps data located centrally, is easily accessible from other applications.
  • Very useful in web farms and web garden scenarios.
Disadvantages:
  • Processing is very slow in nature.
  • Object serialization and de-serialization creates overhead for the application.
  • As the session data is handled in a different server, we have to take care of SQL Server. It should be always up and running.

References:

Custom Session Mode

Overview of Custom Session Mode

Commonly we use the InProc, StateServer, or SQLServer session modes for our application, but we also need to know the fundamentals of the Custom session mode. This session mode is quite interesting, because Custom session gives full control to us to create everything, even the session ID. You can write your own algorithm to generate session IDs.

You can implement custom providers that store session data in other storage mechanisms simply by deriving from theSessionStateStoreProviderBase class. You can also generate a new session ID by implementing ISessionIDManager.

These are the methods called during the implementation of Custom session:

In the Initialize method, we can set a custom provider. This will initialize the connection with that provider. SetItemExpireCallbackis used to set SessionTimeOut. We can register a method that will be called at the time of session expiration. InitializeRequest is called on every request and CreateNewStoreData is used to create a new instance of SessionStateStoreData.

When should we use Custom Session Mode?

We can use Custom session mode in the following cases:

  • We want to store session data in a place other than SQL Server.
  • When we have to use an existing table to store session data.
  • When we need to create our own session ID.

What configuration do we need for it?

We need to configure our web.config like this:

If you want to explore this more, please check the References section.

Advantages and Disadvantages

Advantages:
  • We can use an existing table for storing session data. This is useful when we have to use an existing database.
  • It’s not dependent on IIS, so restarting the web server does not have any effect on session data.
  • We can crate our own algorithm for generating session ID.
Disadvantages:
  • Processing of data is very slow.
  • Creating a custom state provider is a low-level task that needs to be handled carefully to ensure security.

It is always recommended to use a third party provider rather than create your own.

References:

Overview of production deployment

Production environments are where we deploy our applications on a live production server. It is a major and big challenge for web developers to deploy their applications on a live server, because in a big production environment, there are a large number of users and it is hard to handle the load for so many users with a single server. Here comes in the concepts of Web Farm, Load Balancer, Web Garden, etc.

Just a few months back, I deployed a web application in a live production environment which is accessed by millions of user and there were more than 10 Active Directory instances, more than 10 web servers over a Load Balancer, and several database server, Exchange Server, LCS Server, etc. The major risk involved in multiple servers is session management. The following picture shows a general diagram of production environments:

I will try to explain the different scenarios that you need to keep in mind while deploying your application.

Application Pool

This is one of the most important things you should create for your applications in a production environment. Application pools are used to separate sets of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability. The worker process serves as the process boundary that separates each application pool so that when one worker process or application has an issue or is recycled, other applications or worker processes are not affected.

Identity of Application Pool

Application pool identity configuration is an important aspect of security in IIS 6.0 and IIS 7.0, because it determines the identity of the worker process when the process is accessing a resource. In IIS 7.0, there are three predefined identities that are the same as in IIS 6.0.

Application Pool Identity Description
LocalSystem Built-in account that has administrative privileges on the server. It can access both local and remote resources. For any kind accessing of server files or resources, we have to set the identity of the application pool to LocalSystem.
LocalServices Built-in account has privileges of an authenticated local user account. It does not have any network access permission.
NetworkServices This is the default identity of Application Pool.NetworkServices has the privileges of an authenticated local user account.

Creating and assigning Application Pool

Open IIS Console, right click on Application Pool Folder > Create New.

Give the Application Pool ID and click OK.

Now, right click on the Virtual Directory (I am using StateServer web sites) and assign StateServerAppPool to the StateServer Virtual Directory.

So this StateServer web site will run independently withStateServerAppPool. Any problem related with other applications will not affect this application. This is the main advantage of creating application pools separately.

Web Garden

By default, each application pool runs with a single worker process (W3Wp.exe). We can assign multiple worker processes with a single application pool. An application pool with multiple worker processes is called a Web Garden. Many worker processes with the same Application Pool can sometimes provide better throughput performance and application response time. And each worker process should have its own Thread and memory space.

As shown in the picture, in IIS, there may be multiple application pools and each application pool will have at least one worker process. A Web Garden should contain multiple worker processes.

There are certain restrictions in using a Web Garden with your web application. If we use the InProc session mode, our application will not work correctly because the session will be handled by a different worker process. To avoid this problem, we should use the OutProc session mode and we can use a session state server or SQL-Server session state.

Main advantage: The worker processes in a Web Garden share the requests that arrive for that particular application pool. If a worker process fails, another worker process can continue processing the requests.

How to Create a Web Garden?

Right click on Application Pool > Go to Performance tab > Check Web Garden section (highlighted in picture):

By default, it would be 1. Just change it to more than one.

How Session depends on Web Garden?

I have already explained that InProc is handled by a worker process. It keeps data inside its memory object. Now if we have multiple worker processes, then it would be very difficult to handle the session because each and every worker process has its own memory, so if my first request goes to WP1 and it keeps my session data and the second request goes to WP2, I am trying to retrieve session data and it will not be available, which will throw an error. So please avoid Web Gardens in InProc session mode.

We can use StateServer or SQLServer session modes in Web Gardens because as I have already explained, these two session modes do not depend on worker processes. In my example, I have also explained that if you restart IIS, you are still able to access your session data.

In short:

Session Mode Recommended
InProc No
StateServer Yes
SQLServer Yes

Web Farm and Load Balancer

This is the most common terms that are used in production deployments. These terms come in when we are using multiple web servers for deploying our applications. The main reason for using these is we have to distribute the load over multiple servers. A Load Balancer is used to distribute the load on multiple servers.

If we take a look at the above diagram, the client request the URL and it will hit a Load Balancer, which decides which server to access. The load balancer will distribute the traffic over all the different web servers.

Now how does this affect Session?

Handling Session in web farm and load balancer scenarios

Handling session is one of the most challenging jobs in a web farm.

InProc: In InProc session mode, session data is stored in an in-memory object of the worker process. Each server will have its own worker process and will keep session data inside its memory.

If one server is down, and if the request goes to a different server, the user is not able to get session data. So it is not recommended to use InProc in Web Farms.

StateServer: I have already explained what a state server is and how to configure a state server, etc. For web farm scenarios, you can easily understand how much this is important because all session data will be stored in a single location.

Remember, in a web farm, you have to make sure you have the same<machinekey> in all your web servers. Other things are the same as I have describe earlier. All web.config files will have the same configuration (stateConnectionString) for session state.

SQL Server: This is another approach, the best that we can use in a web farm. We need to configure the database first. The required steps have been explained covered.

explor37.jpg

As shown in the above picture, all web server session data will be stored in a single SQL Server database. And it is easily accessible. Keep one thing in mind, you should serialize objects in both StateServer and SQLServer modes. If one of the web servers go down, the load balancer will distribute the load to other servers and the user will still be able to read session data from the server, because data is stored in a centralized database server.

In summary, we can use either StateServer or SQLServer session mode in a web farm. We should avoid InProc.

Session and Cookies

Clients use cookies to work with session. Because clients need to present the appropriate session ID with each request. We can do this in the following ways:

Using cookies

ASP.NET creates a special cookie named ASP.NET_SessionIdautomatically when a session collection is used. This is the default. Session ID is transmitted through that cookie.

Cookie munging

Some older browsers do not support cookies or the user may disable cookies in the browser, in that case, ASP.NET transmits session ID in a specially modified (or “munged”) URL.

How Cookie Munging works?

When the user requests for a page on a server, the server encoded the session ID and adds it with every HREF link in the page. When the user clicks on a link, ASP.NET decodes that session ID and passes it to the page that the user is requesting. Now the requesting page can retrieve session variables. This all happens automatically if ASP.NET detects that the user’s browser does not support cookies.

How to implement Cookie Munging?

For this, we have to make our session state cookie-less.

Removing Session

Following are the list of methods that are used to remove Session:

Method Description
Session.Remove(strSessionName); Removes an item from the session state collection.
Session.RemoveAll() Removes all items from the session collection.
Session.Clear() Remove all items from session collection. Note: There is no difference between Clear andRemoveAll. RemoveAll()calls Clear() internally.
Session.Abandon() Cancels the current session.

Enabling and disabling Session

For performance optimization, we can enable or disable session because each and every page read and write access of the page involves some performance overhead. So it is always better to enable and disable session based on requirements rather than enable it always. We can enable and disable session state in two ways:

  • Page level
  • Application level

Page level

We can disable session state in page level using theEnableSessionState attribute in the Page directive.

explor38.gif

This will disable the session activities for that particular page.

The same way, we can make it read-only also. This will permit to access session data but will not allow writing data on session.

explor39.gif

Application level

Session state can be disabled for the entire web application using theEnableSessionState property in Web.Config.

explor40.gif

Generally we use page level because some pages may not require any session data or may only read session data.

References:

Summary

Hope you are now really familiar with Session, its use, how to apply it in web farms, etc. To summarise:

  • The in-process (InProc) session provider is the fastest because of everything being stored inside memory. Session data will be lost if we restart the web server or if the worker process is recycled. You can use this in small web applications where the number of users is less. Do not use InProc in web farms.
  • In StateServer session mode, session data is maintained byaspnet_state.exe. It keeps session data out of the web server. So any issues with the web server does not affect session data. You need to serialized an object before storing data in StateServer session. We can use this safely in web farms.
  • SQLServer session modes store data in SQL Server. We need to provide the connection string. Here we also need to serialize the data before storing it to session. This is very useful in production environments with web farms.
  • We can use a Custom provider for custom data sources or when we need to use an existing table to store session data. We can also create custom session IDs in Custom mode. But it is not recommended to create your own custom provider. It is recommended to use a third party provider.

Modules in JavaScript – Global Variable – A complete understanding

Modules

Private members

Because JavaScript has no syntax to denote scope, we need to use closures to implement private members. An extended example of this can be seen in my post about private variables in JavaScript
A simple example of this is shown in the following snippet:

1
2
3
4
5
6
7
8
9
10
MYAPPLICATION.MODEL.PRODUCTS.product = function(price){
    var price = price;   
    
    return {
        isVatApplicable: true,
        getPrice: function(){                                              
            return price;                                           
        }
    };
};

In this snippet, the variable price is private, but it is accessible to the method because it’s inside the closure. The public members are isVatApplicable and getPrice.

Another pattern would be the revealing module. It’s essentially the same as the previous pattern, but now we declare everything privately and then decide what we return (and thus expose as public members):

1
2
3
4
5
6
7
8
9
10
11
12
MYAPPLICATION.MODEL.PRODUCTS.product = function(price){
    var price = price;   
    var isVatApplicable = true;
    var getPrice: function(){                                              
            return price;                                           
        };
    return {
        isVatApplicable: isVatApplicable,
        getPrice: getPrice
    };
};

To me this last pattern is the clearest, because you are declaring everything up front and then explicitly make some members public. It shows the intent.

Private members: caveats

There’s one caveat with the pattern described above. Since in JavaScript all variables are passed by reference you could potentially expose members that you didn’t want to be public. In the example above that doesn’t happen because price is a value.
However, let’s consider the following example:

1
2
3
4
5
6
7
8
9
10
11
12
MYAPPLICATION.MODEL.PRODUCTS.product = function(width, height){
    var dimensions = {
        width: width,
        height: height
    };
    var getDimensions = function(){                                              
            return dimensions;                                           
        };
    return {
        getDimensions: getDimensions
    };
};

We are following the same pattern here, so one might think that the dimensions-variable is private. The following code shows a caveat though:

1
2
3
4
5
6
7
var model = MYAPPLICATION.MODEL.PRODUCTS;
var p = new model.product(50,100);
var dims = p.getDimensions();
dims.width = 1000;
dims.height = 1000;
// alerts 1000 1000 => unexpected
alert(p.getDimensions().width + “ “ + p.getDimensions().height); 

This code will actually alert “1000 1000”. Because the dimensions variable is returned by reference the first time we call p.getDimensions, changing its values will affect the values of the private variable.

What solutions are there for this problem?
There are a few things you can do to mitigate this problem:

  • Do not return objects, but only actual values. In our example this would constitute of creating two methods: getWidthand getHeight.
  • Create a copy of the object. You could do this in the getDimensions method.

Tying it together

The following example ties all the previous techniques together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// create the root namespace and making sure we're not overwriting it
var MYAPPLICATION = MYAPPLICATION || {};
// create a general purpose namespace method
// this will allow us to create namespace a bit easier
MYAPPLICATION.createNS = function (namespace) {
    var nsparts = namespace.split(".");
    var parent = MYAPPLICATION;
    // we want to be able to include or exclude the root namespace
    // So we strip it if it's in the namespace
    if (nsparts[0] === "MYAPPLICATION") {
        nsparts = nsparts.slice(1);
    }
    // loop through the parts and create
    // a nested namespace if necessary
    for (var i = 0; i < nsparts.length; i++) {
        var partname = nsparts[i];
        // check if the current parent already has
        // the namespace declared, if not create it
        if (typeof parent[partname] === "undefined") {
            parent[partname] = {};
        }
        // get a reference to the deepest element
        // in the hierarchy so far
        parent = parent[partname];
    }
    // the parent is now completely constructed
    // with empty namespaces and can be used.
    return parent;
};
// Create the namespace for products
MYAPPLICATION.createNS("MYAPPLICATION.MODEL.PRODUCTS");
MYAPPLICATION.MODEL.PRODUCTS.product = function(width, height){
    // private variables
    var dimensions = {
        width: width,
        height: height
    };
    // private methods
    // creating getWidth and getHeight
    // to prevent access by reference to dimensions
    var getWidth = function(){
        return dimensions.width;
    };
    var getHeight = function(){
        return dimensions.height;
    };
    // public API
    return {
        getWidth: getWidth,
        getHeight: getHeight
    };
};
// Create the namespace for the logic
MYAPPLICATION.createNS("MYAPPLICATION.LOGIC.BUSINESS");
MYAPPLICATION.LOGIC.BUSINESS.createAndAlertProduct = function () {
    var model = MYAPPLICATION.MODEL.PRODUCTS;
    var p = new model.product(50,100);
    alert(p.getWidth() + " " + p.getHeight());
};

As you can see, this patterns allows for modular and well-structured JavaScript. Using these techniques can make your code easier to read and to modify.
There are other techniques available too, and you can build and vary this pattern. In my next post I will show you can create a sandbox. This will allow your code to operate in an isolated environment. It also allows for a type of dependency Injection.

Namespaces in JavaScript – Global Variable – A complete understanding

Namespaces

In most programming languages we know the concept of namespaces (or packages). Namespaces allow us to group code and help us to avoid name-collisions.

In c# for example you have this declaration

1
2
3
4
5
6
namespace MyNameSpace
{
    public class MyClass
    {
    }
}

If you want to use MyClass, you need to do explicitly say in which namespace it lives:

1
MyNameSpace.MyClass obj;

Unfortunately, the concept of namespaces does not exist in JavaScript. To add insult to injury, everything you create in JavaScript is by default global. Now obviously, this is a recipe for disaster, especially since in any modern application you’ll probably end upll using third-party components. How do you avoid these collisions then?

Let’s first look at an anti-pattern, which is declaring all your functions and variables globally:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function calculateVat(prod) {
    return prod.price * 1.21;
}
var product = function (price) {
    this.price = price;
    this.getPrice = function(){
                       return this.price;
        };
    };
function doCalculations() {
    var p = new product(100);
    alert(calculateVat(p.getPrice()));
}

This is a simple snippet, but there are already 3 global items: CalculateVat, product and doCalculations. This could get us in trouble if we start using third-party libraries. What would happen if they use the same names? Well, if they are includedafter our script, they will overwrite our variables and function. Bad! If they’re included before our script, we’re overwriting their variables, which is also bad, since we’ll probably break the library.

How to create a namespace in JavaScript

To solve this problem you can create a single global object for your app and make all functions and variables properties of that global object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var MYAPPLICATION = {
    calculateVat: function (base) {
        return base * 1.21;
    },
    product: function (price) {
        this.price = price;
        this.getPrice = function(){
                          return this.price;
                       };
    },
    doCalculations: function () {
        var p = new MYAPPLICATION.product(100);
        alert(this.calculateVat(p.getPrice()));
    }
}

Now we only have one global variable (MYAPPLICATION). Although this is not really a namespace, it can be used as one, since you have to go through the MYAPPLICATION object in order to get to your application code:

1
2
var p = new MYAPPLICATION.product(150);
alert(p.getPrice());

Nested namespaces

In most languages you can declare a namespace inside a namespace. This allows for even better modularization. We can just apply the pattern again and define an object inside the outer object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var MYAPPLICATION = {
    MODEL: {
        product: function (price) {
                     this.price = price;
                    this.getPrice = function(){
                         return this.price;
                     };
                 }
    },
    LOGIC: {
        calculateVat: function (base) {
            return base * 1.21;
        },
        doCalculations: function () {
            var p = new MYAPPLICATION.MODEL.product(100);
            alert(this.calculateVat(p.getPrice()));
        }
    }
}

This pattern is fairly simple and is a good way to avoid naming collisions with other libraries (or your own code for that matter).

Safely creating namespaces

Since we still have one global object, there’s still a possibility that we are overwriting another global object with the same name. Therefore, we need to build in some safety:

1
2
3
4
5
6
7
8
9
10
// not safe, if there's another object with this name we will overwrite it
var MYAPPLICATION = {};
// We need to do a check before we create the namespace
if (typeof MYAPPLICATION === "undefined") {
    var MYAPPLICATION = {};
}
// or a shorter version
var MAYAPPLICATION = MYAPPLICATION || {};

As you can see in this example, if we want to safely create namespaces it can be quite cumbersome and require a bit of boilerplate code. Wouldn’t it be nice if we could avoid all of this?

Creating a multi-purpose Namespace function

What we’d like to do is simply call a function that creates a namespace safely and then lets us define function and variables in that namespace. Here’s where JavaScript’s dynamic nature really shines. Let’s start with an example of what we want to achieve:

1
2
3
4
5
6
7
8
9
10
var MAYAPPLICATION = MYAPPLICATION || {};
var ns = MYAPPLICATION.createNS("MYAPPLICATION.MODEL.PRODUCTS");
ns.product = function(price){
   this.price = price;
   this.getPrice = function(){
    return this.price;
   }
};

We still need to check our main namespace (you have to start somewhere), but it will allow us to create a hierarchy of namespaces with a single line and have it all figured out.

So how can we do that? Let’s take a look at the implementation of createNS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
MYAPPLICATION.createNS = function (namespace) {
    var nsparts = namespace.split(".");
    var parent = MYAPPLICATION;
    // we want to be able to include or exclude the root namespace so we strip
    // it if it's in the namespace
    if (nsparts[0] === "MYAPPLICATION") {
        nsparts = nsparts.slice(1);
    }
    // loop through the parts and create a nested namespace if necessary
    for (var i = 0; i < nsparts.length; i++) {
        var partname = nsparts[i];
        // check if the current parent already has the namespace declared
        // if it isn't, then create it
        if (typeof parent[partname] === "undefined") {
            parent[partname] = {};
        }
        // get a reference to the deepest element in the hierarchy so far
        parent = parent[partname];
    }
    // the parent is now constructed with empty namespaces and can be used.
    // we return the outermost namespace
    return parent;
};

This function splits the string you pass it and creates a nested namespace for each part. This means that this code:

1
MYAPPLICATION.createNS("MYAPPLICATION.MODEL.PRODUCTS");

is essentially the same as declaring the following (but with the advantage of checking whether we’re not overriding any existing namespace):

1
2
3
4
5
6
var MYAPPLICATION = {
    MODEL: {
        PRODUCTS: {
        }
    }
}

Aliasing namespaces

When your namespace hierarchy becomes deeper and deeper you will notice that it becomes cumbersome since you always have to type the complete reference to a function or a variable. This can easily be solved by aliasing a namespace (similar to the using statement in C# and Imports in JAVA and VB). Let’s take a look at an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
MYAPPLICATION.createNS("MYAPPLICATION.MODEL.PRODUCTS");
MYAPPLICATION.createNS("MYAPPLICATION.LOGIC.BUSINESS");
MYAPPLICATION.MODEL.PRODUCTS.product = function(price){                                          
    this.price = price;   
    this.isVatApplicable = true;
    this.getPrice = function(){                                              
        return this.price;                                           
    }                                      
};
MYAPPLICATION.MODEL.PRODUCTS.currentvatrate = 1.21;
MYAPPLICATION.LOGIC.BUSINESS.getSelectedProductTotal = function () {
    var p = new MYAPPLICATION.MODEL.PRODUCTS.product(100);
    if(p.isVatApplicable){
        return p.getPrice() * MYAPPLICATION.MODEL.PRODUCTS.currentvatrate;
    }
    else {
        return p.getPrice();
    }
}

This simple snippet declares two namespaces and then adds an object to the first and a function to the second. The function uses the object in the other namespace. As you can see, this simple method which just uses one function and a couple of variables is very cumbersome to write because of all the references.

A shortcut would be easier. We can achieve this by simply aliasing the namespace in a local variable:

1
2
3
4
5
6
7
8
9
10
MYAPPLICATION.LOGIC.BUSINESS.getSelectedProductTotal = function () {
    var model = MYAPPLICATION.MODEL.PRODUCTS;
    var p = new model.product(150);
    if (p.isVatApplicable) {
        return p.getPrice() * model.currentvatrate;
    }
    else {
        return p.getPrice();
    }
}

Apart from saving you typing work and decreasing your file size, this pattern has one more advantage that I think is even more important. Since you are declaring your namespace at the top of each function, you are explicitly clarifying in your code on what module it depends. That, in my opinion, is invaluable and will help you understand written code a lot better.

Disadvantages

Although this pattern is easy to use and perfectly valid for many tasks and scenarios there is one big disadvantage:

The one global instance is vulnerable. This means that anyone could access its internals. For example, the product has a property price and a method getPrice(). However, nothing prevents us from directly accessing the price property. We don’t want this, we want to expose only the method so we can control the access to our private variable.
To solve these problems we need to take a look at how can create modules that encapsulate certain data and behavior.

What is OAuth in SharePoint 2013 or O365? – a simple understanding

OAuth is having importance in CSOM /REST api.

Below is the execution framework of OAuth,

OAuth Framework

 

In above diagram right side zone is representing,

  • A. Resource Owner
  • B. Authorization Owner
  • C. Resource Server

Execution Process of OAuth is as below,

  1. Client made a request for “Authorization” to “Resource Owner”
  2. “Resource Owner” response with “Authorization Grant” to the Client
  3. Client made a request for “Access token” to “Authorization Server”
  4. “Authorization Server” response with “Access token” to the Client
  5. Client made a request for “Resource” to “Resource Server” with “Access Token”
  6. “Resource Server” response with “Protected Resource” to the Client

Resource File : OAuth

 

Apps development using KnockoutJS and AngularJS in CSOM

I did some research on JavaScript frameworks and can see that Microsoft TypeScript, Knockout.js and AngularJS keep coming up on various talks around Windows 8, Windows Phone 8 and general web development.

I decided to explore how I could take concepts from both to have the AngularJS Todo sample loading from a SharePoint Task List in the Host Web (ghettoweb) rather than the App Web.

From a net new Visual Studio 2013 project, you simply need to add the angular.min.js file to your scripts folder and add a reference to it on your default.aspx page.

The way that AngularJS hooks up to your default.aspx HTML code which essentially becomes your view is by some attributes on HTML elements. The nice part about this is that I am not writing in JavaScript how the View is going to look, very similar to ASP.NET MVC approach. I can actually write standard HTML without throwing it all in one big string in JavaScript.

Then if you open up your app.js file you can paste these blocks into it which I’ll explain in sections.

I declare all of the objects that are commonly used at the top of the App.js, I need to discuss more with the JavaScript peeps on best practices here on whether I should declare some of the other objects that I use in sections below up here or not.

In this section, this is where the AngularJS Controller is declared. The function maps directly to the HTML element ‘ng-controller’ attribute value. The $scope (the model) is very important and is used by the view and populated by the controller. You can see I have added a $scope.todos collection and the HTML View iterates through this collection using the HTML attribute ‘ng-repeat’.
You will also notice that I have various functions that map to a AngularJS service (next code section) to keep the controller relatively clean. Again some of these functions like AddTask are mapped in the View. Contructs like the remaining value that is in the View are calculated in the Controller below.

The ability of writing AngularJS Services means that you can really separate out the logic nicely rather than one big horrible JavaScript file. Technically the Controller and all the Services can be in different JavaScript files.

This block gets the SharePoint Tasks from the Host web Task List. Calling the Host web is a little more complex due to cross domain calls than calling the App web, there are some great samples that explain all this. For the $scope to retain I found that I had to use inline Delegates rather than calling out to a function, which makes the JavaScript a little too nested for my liking, I need to research how I can clean this up more…although I’m not sure I even like the chaining of function calls into function calls either?!?!

The Add Task function calls the SharePoint CSOM code up to the Host web to add a new task and notice how I use $scope.todos.push to add a new object to the collection and this will automatically update the View, I don’t have to rewrite the HTML on the screen.

The Archive Task function calls CSOM again to delete the completed tasks from the SharePoint list.

I only used one common function here, but I’ve already noticed that people like Andrew Connell are creating these in separate JavaScript files to make them reusable across projects.

I hope you found this sample useful, I certainly enjoyed pushing myself into the unknown and leveraging AngularJS. I will continue to build on this sample as I improve the UX to Update an exist task and set things more than just the title etc.

I have uploaded the completed app withUbertTaskListAngularApp as a Visual Studio 2013 project. I’d love to hear from JavaScript guys on anything I can do to improve this more too!

What is AngularJS and KnockoutJS in CSOM?

SharePoint versions prior to 2010 have been using SharePoint API (a.k.a. Server-Side Object model) to develop SharePoint web parts. Although the API allowed CRUD operations on SharePoint data, the restriction was that it had to be run on the SharePoint server or a developer would alternatively use SharePoint’s web server interface, which had its own limitations from a design perspective.

With SharePoint 2010, developers were now able to use Client Side Object Model to develop Web parts. The Client Side Object Model is a subset of the SharePoint API which mimics a large portion of the server-side API. The advantage of the client-side API is it can be called from .NET apps, Silverlight or using JavaScript libraries. In SharePoint 2013, the client-side API has been extended with REST/OData endpoints.

In this article, we will learn how to make use of JavaScript libraries to fetch data from SharePoint List and bind that data to some controls using SharePoint Web parts. For this demonstration, we will make use of AngularJS and KnockoutJS JavaScript libraries.

A Quick Look into AngularJS and KnockoutJS

Before getting started, let’s quickly introduce the two JavaScript libraries – Angular JS and Knockout JS.

AngularJS

AngularJS is an open source MV* JavaScript framework maintained by Google and community, for building rich, interactive, single page applications (SPA). AngularJS uses HTML as your template language and lets you extends the HTML vocabulary for your application. The * in AngularJS represents MVC, MVVM or the MVP pattern which makes both development and testing of AngularJS applications easier. The main components of AngularJS are shown here –

 

Controller – Controller is key to AngularJS. A Controller is a JavaScript constructor function that is used to create a scope. A controller is attached to the DOM via ng-controller directive. You can use controllers to initiate the state of the $scope object and add behaviours to $scope object. $scope – is a glue between a Controller and DOM and just watches the changes to models and also applies changes to the model. One thing to note about Controller is they do not perform DOM manipulations or maintain state. AngularJS uses Services to maintain state.

Services – Services are used to perform common tasks on the web applications which are consumed by Angular JS via Dependency Injection. Services are registered with a Module and are usually singular to the application.

Views – Views are complied DOM of Angular JS. A view is produced using $compile with HTML templates and $scope.

With clientside implementation, Angular can have integration with the server using REST and $http service.

KnockoutJS

KnockoutJS is a fantastic library when you are looking for a drop-in enhancement that brings in client side data-binding and applies the Model-View-View-Model design pattern to your websites.

Knockout works with a ViewModel that can either be a JS object or a JS function. Either ways, your ViewModel is your data source. Using Knockout, you can bind DOM elements to your model using a declarative syntax. Knockout also provides Templating (for repetitive structures in a web page) and dependency tracking using ko.observableArray. With dependency tracking, if a property is changed, it will automatically notify the UI. The UI reflects these changes and can also change the value to automatically update the source object again.

 

This was just a small introduction of Angular JS and Knockout JS libraries. We can get more details on both the libraries here –

  • Angularjs.org
  • Knockoutjs.com

You can also learn more about AngularJS in Getting Started with AngularJS in ASP.NET MVC and about Knockout at Getting Started with KnockoutJS in ASP.NET MVC

Using AngularJS and KnockoutJS in SharePoint

Using these libraries in SharePoint development can make a big difference as we will see shortly. We will use these libraries with SharePoint Web parts using our very favorite tool – Microsoft Visual Studio. I am using Visual Studio 2013 for these demonstrations.

I have already created a SharePoint Site using Team site Template –

 

We will create a Custom List in our SharePoint site with the name Customers and some columns as described here –

  • CustomerID
  • ContactName [Rename title column]
  • City
  • Country
  • ContactNo

Add some default data in our customers list. The list should look like the following –

 

Before we start building the Web Part, we will query SharePoint list data using OData queries. Let’s write some queries in our browser as described here –

· http://localhost/sites/dncmag/_api/web/lists/getByTitle(‘Customers&#8217;)/items

· http://localhost/sites/dncmag/_api/web/lists/getByTitle(‘Customers&#8217;)/items?$select=CustomerID,Title,City,Country,ContactNo

The output of the above query which uses $select operator is as shown –

 

As already mentioned earlier, we will be using Visual Studio to build our Web Part using the AngularJS library. Before that, we will need to add the scripts into our /_layouts/15/Scripts folder. Go to Windows Explorer and browse the following path –

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS

Now create a Scripts folder under Layouts folder and add the following script files into the same –

  • Angular JS
  • Bootstrap JS

I will also be using Twitter Bootstrap to make my UI look better. To those new to Bootstrap, it is a package that consists of predefined CSS styles, Components and jQuery plugins. It is licensed under Apache 2.0 and is free for commercial use. I have added the Bootstrap CSS into Scripts folder, although ideally you should create a separate CSS folder if you will be dealing with too many CSS files.

Also add some empty JavaScript files with the names SharePointListModule.js and CustomerController.js in the Scripts folder. We will these two files when we will be writing the script for fetching the SharePoint List Data using Angular JS.

Now we are ready to build the SharePoint Visual Web Part using AngularJS. Open Visual Studio and create a New Project. Choose Office/SharePoint > SharePoint Solutions and choose SharePoint 2013 – Visual Web Part template as shown here –

 

Click on the OK button. This will now show you a dialog box which will ask you for a site URL and security level for debugging.

 

Once the Web Part project is created, we will first import the AngularJS, Bootstrap JS, Bootstrap CSS, SharePointListModule.js and CustomerController.js in our User Control as shown here –

<link href=”/_layouts/15/Scripts/bootstrap.min.css” rel=”stylesheet” />
/_layouts/15/Scripts/jquery-2.1.0.min.js
/_layouts/15/Scripts/knockout-3.1.0.js
/_layouts/15/Scripts/bootstrap.min.js

Now we will create an Angular Module. You can think of a module as a container which wires the different parts of your application like controllers, services, directives, etc. To create an Angular Module, write the following code in our SharePointListModule.js file –

sharepoint-module

We will now add a Controller which will fetch the data from our SharePoint List using $http service. We will use the SharePoint OData query and bind the data in our user control. Let’s write some code in CustomerController.js file as shown here –

var webSiteURL = “<%= SPContext.Current.Web.Url %>”;

myAngApp.controller(‘spCustomerController’, function ($scope, $http) {
$http({
method: ‘GET’,
url: webSiteURL + “/_api/web/lists/getByTitle(‘Customers’)/items?$select=CustomerID,Title,City,Country,ContactNo”,
headers: { “Accept”: “application/json;odata=verbose” }
}).success(function (d, s, h, c) {
$scope.customers = d.d.results;
});
});

In the script we just saw, we have first created an Angular Controller with the name ‘spCustomerController’. We have also injected $scope and $http service. The $http service will fetch the list data from the specific columns of SharePoint list. $scope is a glue between Controller and a View. It acts as execution context for Expressions. Angular expressions are code snippets that are usually placed in bindings such as {{ expression }}.

You might have observed that we are creating separate JavaScript files for creating Angular JS Module and Controller. As already mentioned, the AngularJS module acts as a container for Controllers, Services, Filters, and Directives etc. Modules declaratively specify how an application should be bootstrapped. It offers several advantages like –

  • The declarative process is easier to understand
  • Modules can be reusable
  • Modules can be loaded in any order or parallel
  • Unit testing and end-to-end testing is easier

We will now build the UI which will display SharePoint list data in our User Control. Let’s write the following code after the script –

Customer ID Contact Name City Country Contact No
{{customer.CustomerID}} {{customer.Title}} {{customer.City}} {{customer.Country}} {{customer.ContactNo}}

</div>

In above HTML, we are using table and ng-repeat to iterate through the customers. Now deploy the Web Part and add the same in your SharePoint site. You should see the following output –

 

Using KnockoutJS in SharePoint

We will repeat the same demonstration that we did earlier with AngularJS, now using KnockoutJS. We will create one more webpart, but this time we will go with KnockoutJS JavaScript library to bind the data in our User Control. Before creating the Web Part, let’s add the following class libraries into our Script folder –

  • jquery-2.1.0.min.js
  • knockout-3.1.0.js

Follow the same steps to create a Web Part using Visual Studio as described in AngularJS Web Part section. Once the Web Part is created, we will now add the references of script files into our User Control as shown here –

 

To fetch the data from SharePoint list [Customers], we will make use of jQuery AJAX. Let’s write the following script in our user control –


var webSiteURL = “”;
$(function CustomersModel() {
var self = this;
self.Customers = ko.observableArray([]);
$.ajax({
method: ‘GET’,
url: webSiteURL + “/_api/web/lists/getByTitle(‘Customers’)/items?$select=CustomerID,Title,City,Country,ContactNo”,
headers: { “Accept”: “application/json;odata=verbose” }
}).success(function (d) {
self.Customers = d.d.results;
ko.applyBindings(self);
})();
});

Note: I am using the success() function considering those who are still using jQuery 1.7 or earlier. If you are using the latest version of jQuery, replace success() with done().

The above script, fetches the data from SharePoint List and exposes it as a Knockout observable array. We will now build the UI for our user control in which we will use the KnockoutJS binding capabilities. Let’s write some code in our User Control after the script

<h1>WelCome To Knockout JS Web Part !!</h1>

Customer ID Contact Name City Country Contact No

</div>

In the above HTML, we are using Knockout JS foreach loop to iterate through the list of customers. Now build the Web Part and deploy it to a SharePoint site. After deployment, add the Web Part on SharePoint site and the output should be similar to the following –

 

There you go! You now have a number of possibilities open to build different SharePoint Applications like Web Parts or SharePoint Apps.

Summary – In this article, we saw how you can use the client side JavaScript libraries like Angular JS and Knockout JS in SharePoint.

How can I access and contribute to Sharepoint site from Linux?

How to set up a mount point for MS SharePoint on Linux?

  1. You must download davfs2-1.0.2.tar.gz if mount.davfs does not exist on your system.
  2. Extract above file, and install with “./configure && make && make install”. This will require that the libneon library and headers exist on your system.
  3. Once davfs2 is installed, confirm that the coda kernel module is loaded on your system with “lsmod | grep coda”.
    1. If the module is not loaded, load it with “modprobe coda” and do one of the following to make it persistent:
      1. Debian: add a line to /etc/modules reading “coda”.
      2. Slackware: uncomment a line in /etc/rc.d/rc.modules reading “/sbin/modprobe coda”.
      3. Others: add modprobe to /etc/rc.local or use distribution-specific module loader mechanism.
    2. If the module is not loaded AND the above modprobe fails, recompile your kernel with built-in coda support or a coda module.
    3. If the module is already loaded, proceed to the next step.
  4. Create a directory to be used for sharepoint (I used /home/inittab/sharepoint)
  5. Add following line to /etc/fstab, adjusting for proper mount point: “http://9.17.232.196/sites/VSA/ /home/inittab/sharepoint davfs rw,noauto,user 0 0”
  6. Make sure your user is in the “users” group of /etc/group or LDAP.
  7. Add a password line to /usr/local/etc/davfs2/secrets. It should look like this: “http://9.17.232.196/sites/VSA/ schenzel myPaSSwoRd”
  8. Mount it: “mount /home/inittab/sharepoint”. An “ls -l /home/inittab/sharepoint” should show the contents, and you should be able to upload, download, and modify files on sharepoint.