Share via


SharePoint 2013: Working with Connection Strings in Auto-Hosted SharePoint Apps

Richard diZerega has a really nice util method for working with connection strings in Auto-Hosted Apps in SharePoint 2013. It goes like this:

The Code

using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
 
namespace MovemberWeb.Util
{
    public class  ConnectionUtil
    {
        public static  string GetEntityConnectionString(ClientContext clientContext)
        {
            //try to get the connection string from from the clientContext
            clientContext.Load(clientContext.Web, web => web.Title);
            ClientResult<string> result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
            clientContext.ExecuteQuery();
            string connString = result.Value;
 
            //if the connection string is empty, then this is debug mode
            if (String.IsNullOrEmpty(connString))
                connString = WebConfigurationManager.ConnectionStrings["LocalDBInstanceForDebugging"].ConnectionString;
 
            //build an Entity Framework connection string
            EntityConnectionStringBuilder connBuilder = new  EntityConnectionStringBuilder();
            connBuilder.Provider = "System.Data.SqlClient";
            connBuilder.ProviderConnectionString = connString;
            connBuilder.Metadata = "res://*/MovemberModel.csdl|res://*/MovemberModel.ssdl|res://*/MovemberModel.msl";
 
            //return the formatted connection string
            return connBuilder.ConnectionString;
        }
    }
}

You can get it here: https://skydrive.live.com/?cid=743e7abd51ea3851&id=743E7ABD51EA3851%21757&authkey=!ACIqsQhqXZipXcY (Movember.zip)

Credits

Richard diZerega created this useful utility function, get it at https://skydrive.live.com/?cid=743e7abd51ea3851&id=743E7ABD51EA3851%21757&authkey=!ACIqsQhqXZipXcY (Movember.zip)