SharePoint Dragons

Nikander & Margriet on SharePoint

Working with Connection Strings in Auto-Hosted 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:

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)

Updates and alternative insights can be tracked here: http://social.technet.microsoft.com/wiki/contents/articles/16353.sharepoint-2013-best-practices-working-with-connection-strings-in-auto-hosted-sharepoint-apps.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: