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

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

Table of Contents



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)

See Also

Leave a Comment
  • Please add 4 and 8 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
Page 1 of 1 (2 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
Page 1 of 1 (3 items)