- The figure below is a syntax diagram of the structure of SharePoint Foundation REST service URIs. You can read more about the SharePoint Foundation REST service here.
Syntax diagrams are a useful way of illustrating linear data structures. Things like:
- REST URI composition
- API signatures
- JSON, OData, or other XML-based data notation
Wednesday, August 22, 2012
SharePoint 2010 REST Service Syntax Diagram
Sandboxed Solutions Object Model Hierarchy
Today’s diagram is probably best considered a work in progress.
We created the following diagram as a prototype, to see if we could use large-scale static graphics as aids for developers to visualize the SharePoint object model hierarchy and the relationships between classes within it. As an experiment, we took the subset of classes available in sandbox solutions, and, starting from a handful of the most important classes, laid out the Microsoft.SharePoint namespace hierarchy.
The results were mixed: we quickly realized that, as recursively nested as the SharePoint object model is, arbitrarily picking starting points (even important classes such as SPWeb and SPList) and presenting a single hierarchical view of the object model from there probably isn’t going to be that useful long-term for developers. Locating a specific class was difficult. Also, in order to conserve space, we omitted the names of the members used to access a class from another class; in doing so, we inadvertently stripped off an important layer of information about the relationship between the classes.
However, the diagram does provide a useful general reference for how the major classes of the SharePoint namespace are structured, so we’re presenting it here as a free download. The diagram is 34” by 44”, and available as a Visio drawing or pdf file. You can download the larger versions in a zip here on the blog. In the comments, tell us what information you’d want to help you visualize a complex object model like SharePoint, be it in a static diagram like this, or an interactive application that enabled you to select what to display.
![Sandboxed Solutions Object Model Hierarchy Sandboxed Solutions Object Model Hierarchy](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_sa11WDbEjJnD8zo2w9-52lgh3tKDgnvZ82VEr-95xjoxXNnglaCNSNbdzBs7cz5_g7xR2rO9QnhOx3XlWM46blMhgX6lCwo9ghpzKZiLNz-qjtVgi60M-qigJo6Dc-3dXZFoMS-vlKLy3uI77_jr_zeG05UVPLowz2-U47DtcAZip474bBdDS8krp9r8CehHk9XTRrnK-__Xsm4V32IVpugOPeWLri4Xt6DL0gI0-P_Qe1j3lGdCDLMMIeaXNJxg6O25hAXRL2pb0QIHBHNS3VJptestVZb6hGyJi4ISnkofDTpD3TFxl5SrqBtyqFHMeaPrEnPOQ=s0-d)
We created the following diagram as a prototype, to see if we could use large-scale static graphics as aids for developers to visualize the SharePoint object model hierarchy and the relationships between classes within it. As an experiment, we took the subset of classes available in sandbox solutions, and, starting from a handful of the most important classes, laid out the Microsoft.SharePoint namespace hierarchy.
The results were mixed: we quickly realized that, as recursively nested as the SharePoint object model is, arbitrarily picking starting points (even important classes such as SPWeb and SPList) and presenting a single hierarchical view of the object model from there probably isn’t going to be that useful long-term for developers. Locating a specific class was difficult. Also, in order to conserve space, we omitted the names of the members used to access a class from another class; in doing so, we inadvertently stripped off an important layer of information about the relationship between the classes.
However, the diagram does provide a useful general reference for how the major classes of the SharePoint namespace are structured, so we’re presenting it here as a free download. The diagram is 34” by 44”, and available as a Visio drawing or pdf file. You can download the larger versions in a zip here on the blog. In the comments, tell us what information you’d want to help you visualize a complex object model like SharePoint, be it in a static diagram like this, or an interactive application that enabled you to select what to display.
How to Programmatically Update an ODC File
This post describes how to update ODC files programmatically by using either a SharePoint feature or a console application written in .Net code, or with a PowerShell script. The contents pertain to:
<odc:Connection odc:Type="OLEDB"> <odc:ConnectionString>Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=<Database Name>;Data Source=<Database Server>;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=<Computer Name>;Use Encryption for Data=False;Tag with column collation when possible=False</odc:ConnectionString>
<odc:CommandType>SQL</odc:CommandType>
<odc:CommandText> "<Database Name>"."dbo"."<Stored Procedure Name>"</odc:CommandText>
<odc:SSOApplicationID>ExcelServicesApplicationID</odc:SSOApplicationID>
<odc:CredentialsMethod>Stored</odc:CredentialsMethod>
<odc:AlwaysUseConnectionFile/>
</odc:Connection>
</odc:OfficeDataConnection>
{
using System.Linq;
using System.Text;
using System.Xml;
/// <summary>
/// Class to change the ODC file parameters
/// </summary>
class Program
{
/// <summary>
/// Index from where tag begins
/// </summary>
private static int sourceIndex = 0;
/// <summary>
/// Index from where tag ends
/// </summary>
private static int destinationIndex = 0;
static void Main(string[] args)
{
// You can keep the source an destination file path same if you want to
// overwrite the existing file with new values.
string odcFilePath = @"C:\Reports\Connection.odc";
string destinationFilePath = @"C:\Reports\Connection.odc";
// Provide values for following patameters that will be changed in the ODC file.
string databaseName = "<your database name>";
string serverName = "<your server name>";
string SSOApplicationID = "<application ID>";string provider = "<Provider>";
string integratedSecurity = "<integrated security>";
string persistSecurityInfo = "<persist security info>";
string useProcedure = "<use procedure>";
string autoTranslate = "<auto translate>";
string packetSize = "<packet size>";
string workSatationID = "<workstation ID>";
string encryptionData = "<encryption data>";
string tagWithCollation = "<tag with column collation>";
The following code reads the ODC file and retrieves the ODC connection XML data from it.
string xmlConnection = GetConnectionString(odcFilePath);
XmlDocument odcXmlConnection = new XmlDocument();
odcXmlConnection.LoadXml(xmlConnection);
XmlNamespaceManager nameManager = new XmlNamespaceManager(odcXmlConnection.NameTable);
nameManager.AddNamespace("odc", odcXmlConnection.DocumentElement.NamespaceURI);
XmlNodeList nodelistConnectionString = odcXmlConnection.SelectNodes("//odc:Connection/odc:ConnectionString", nameManager);
The following code changes the connection properties mentioned above.
StringBuilder finalConnectionString = CreateNewConnectionString(databaseName, serverName, provider, integratedSecurity, persistSecurityInfo, useProcedure, autoTranslate, packetSize, workSatationID, encryptionData, tagWithCollation, nodelistConnectionString);
nodelistConnectionString[0].InnerText = finalConnectionString.ToString();
The following code changes the SSOApplicationID property in the XML.
XmlNodeList nodelistSSOApplicationID = odcXmlConnection.SelectNodes("//odc:Connection/odc:SSOApplicationID", nameManager);
nodelistSSOApplicationID[0].InnerText = SSOApplicationID;
The following code saves the updated file on to a disk. When this is complete, the file can be published to SharePoint.
SaveConnectionString(odcFilePath, destinationFilePath, odcXmlConnection.OuterXml);
}
The following code finds the connection string tag in the ODC file and returns the full connection string.
/// <summary>
/// Finds the connection string in the ODC file
/// </summary>
/// <param name="filePath">path of ODC file</param>
/// <returns>office data connection xml</returns>
public static string GetConnectionString(string filePath)
{
string xmlConnection = string.Empty;
System.IO.StreamReader myFile = new System.IO.StreamReader(filePath);
string myString = myFile.ReadToEnd();
sourceIndex = myString.IndexOf("<odc:OfficeDataConnection");
destinationIndex = myString.IndexOf("</odc:OfficeDataConnection");
xmlConnection = myString.Substring(sourceIndex, destinationIndex - sourceIndex + 27);
myFile.Close();
return xmlConnection;
}
The following code saves the connection string tag to the ODC file and saves it to a disk.
/// <summary>
/// save the changed ODC file
/// </summary>
/// <param name="filePath">path at which you want to read the ODC file</param>
/// <param name="newFilePath">path at which you want to save</param>
/// <param name="connectionString">new data connection string to be changed</param>
public static void SaveConnectionString(string filePath, string newFilePath, string connectionString)
{
string xmlConnection = string.Empty;
System.IO.StreamReader myFile = new System.IO.StreamReader(filePath);
string myString = myFile.ReadToEnd();
myFile.Close();
string lessString = myString.Remove(sourceIndex, destinationIndex - sourceIndex + 27);
myString = lessString.Insert(sourceIndex, connectionString);
System.IO.StreamWriter writer = new System.IO.StreamWriter(newFilePath);
writer.Write(myString);
}
The following code finds the properties in the ODC file and then changes them. If a property does not require any changes, it can be removed from this code. The new connection string will be returned to the Main function.
/// <summary>
/// Function to replace the old values with new one.
/// </summary>
/// <param name="databaseName">database Name</param>
/// <param name="serverName">server Name</param>
/// <param name="provider">provider</param>
/// <param name="integratedSecurity">integrated Security</param>
/// <param name="persistSecurityInfo">persist Security Info</param>
/// <param name="useProcedure">use Procedure</param>
/// <param name="autoTranslate">auto Translate</param>
/// <param name="packetSize">packet Size</param>
/// <param name="workSatationID">work Satation ID</param>
/// <param name="encryptionData">encryption Data</param>
/// <param name="tagWithCollation">tag With Collation</param>
/// <param name="nodelistConnectionString">nodelist Connection String</param>
/// <returns>final connection string</returns>
private static StringBuilder CreateNewConnectionString(string databaseName, string serverName, string provider, string integratedSecurity, string persistSecurityInfo, string useProcedure, string autoTranslate, string packetSize, string workSatationID, string encryptionData, string tagWithCollation, XmlNodeList nodelistConnectionString)
{
string[] connectionStringArray = nodelistConnectionString[0].InnerText.Split(';');
StringBuilder finalConnectionString = new StringBuilder();
foreach (string connections in connectionStringArray.ToList())
{
string[] splitOnEqual = connections.Split('=');
switch(splitOnEqual[0])
{
case "Initial Catalog": splitOnEqual[1] = databaseName;
break;
case "Data Source": splitOnEqual[1] = serverName;
break;
case "Provider": splitOnEqual[1] = provider;
break;
case "Integrated Security": splitOnEqual[1] = integratedSecurity;
break;
case "Persist Security Info": splitOnEqual[1] = persistSecurityInfo;
break;
case "Use Procedure for Prepare": splitOnEqual[1] = useProcedure;
break;
case "Auto Translate": splitOnEqual[1] = autoTranslate;
break;
case "Packet Size": splitOnEqual[1] = packetSize;
break;
case "Workstation ID": splitOnEqual[1] = workSatationID;
break;
case "Use Encryption for Data": splitOnEqual[1] = encryptionData;
break;
case "Tag with column collation when possible": splitOnEqual[1] = tagWithCollation;
break;
}
finalConnectionString = finalConnectionString.Append(splitOnEqual[0]);
finalConnectionString = finalConnectionString.Append("=");
finalConnectionString = finalConnectionString.Append(splitOnEqual[1]);
finalConnectionString = finalConnectionString.Append(";");
}
finalConnectionString = finalConnectionString.Remove((finalConnectionString.Length-1), 1);
return finalConnectionString;
}
}
}
# Initialize the variables
$BICenterSite = "<Site where you have to upload the updated ODCs>"
$reportingDBname = "<Database Name>"
$databaseServer = "<Database Server Name>"
$listName = "<List Name where ODCs have to be uploaded>"
$ODCFilesFolder = "<Folder path where all the ODCs are present>"
$SubFolderName = "<Sub Folder Name>"
$fileEntry = [IO.Directory]::GetFiles($ODCFilesFolder)
# reading all the ODC files from the given folder
foreach($fileName in $fileEntry)
{
$w=Get-Content $fileName
$d=[string]$w
if($d.Contains("<odc:OfficeDataConnection"))
{
[int] $i = $d.IndexOf("<odc:OfficeDataConnection")
[int] $j = $d.IndexOf("</odc:OfficeDataConnection>")
[xml] $xmlPart = $d.SubString($i, ($j-$i+27))
$con = $xmlPart.OfficeDataConnection.Connection | Select ConnectionString
[string] $connectionString = $con.ConnectionString
[string] $finalString = ""
$stringArray = $connectionString.Split(";")
foreach($element in $stringArray)
{
$item = $element.Split("=")
if($item[0] -eq "Initial Catalog")
{
$item[1]=$reportingDBname
}
if($item[0] -eq "Data Source")
{
$item[1]=$databaseServer
}
# Put all other parameters here in separate if blocks which you want to change.
$finalString=$finalString+$item[0]+"="+$item[1]+";"
}
[string] $finalXmlNode = "<odc:ConnectionString>"+$finalString+"</odc:ConnectionString>"
[string] $finalXml = $xmlPart.OuterXml
[int] $k = $finalXml.IndexOf("<odc:ConnectionString>")
[int] $l = $finalXml.IndexOf("</odc:ConnectionString>")
$finalXml=$finalXml.Remove($k,($l-$k+23))
$finalXml=$finalXml.Insert($k,$finalXmlNode)
[string] $odc=$d.Remove($i,($j-$i+27))
$odc=$odc.Insert($i,$finalXml)
Set-Content -Path $fileName -Value $odc -Force
}
}
$site = New-Object Microsoft.SharePoint.SPSite($BICenterSite)
$web = $site.OpenWeb()
$list = $web.Lists[$listName]
$fileCollection = $list.RootFolder.SubFolders[$SubFolderName].Files
# Uploading the ODC files on SharePoint server
foreach ($file in $fileEntry)
{
$stream = $file.OpenRead()
$uploaded = $fileCollection.Add($file.Name, $stream, $TRUE)
$uploaded.Item.File.Publish("Published by PowerShell script")
"Uploaded " + $file.Name
if ($stream) {$stream.Dispose()}
}
# Disposing the web and site objects
if ($web) {$web.Dispose()}
if ($site) {$site.Dispose()}
- Microsoft SharePoint Server 2010
- Microsoft SharePoint Server 2010 – Excel Services
- Microsoft SQL Server 2008
Overview of Office Data Connection Files
An Office Data Connection (ODC) file contains connection information about how to connect to a data source and retrieve data for use in various documents such as Microsoft Excel workbooks. Connection information can either be stored in the workbook or in a connection file, such as an (ODC) file (.odc) or a Universal Data Connection (UDC) file (.udcx).
Typically, an ODC file is used while building Excel services reports that fetch data from a data source. As part of the implementation, this report can be deployed in multiple environments such as development, staging, test, and production. Each environment may have a different data source and hence a different connection string. The connection string should be changed in the ODC file as based on the environment it is deployed in. Usually this is a manual step; however this task can be automated. This approach is the topic of this post.
You can update ODC files programmatically by using either a SharePoint feature or a console application written in .Net code, or with a PowerShell script.
With the console application approach, files need to be published on the SharePoint site with some additional code or deployment steps which are not covered in this article. The PowerShell approach takes care of uploading and publishing the ODC file to the SharePoint site.
One ODC file can be used for one or more Excel files. ODC files contain the following types of information:
- Connection string
- Command Type
- Command Text
- SSO Application ID
- Credentials Method
- Whether to always use the connection file
Description of an ODC File
An ODC file is a HTML file that contains embedded sections of XML. The XML in an ODC file determines the core connection information for the data source. This information includes:
- Data provider-specific connection string that is used to establish and open a connection to the data source
- Query text that is used to fetch data
- Name of the specific table or cube from which to fetch data
- Hints about how the query text, cube, or table name is interpreted
- Flag indicating that the ODC file is always used to connect to and query the data source (as opposed to an application using a cached version of the data connection information)
- Specific authentication information to use for the data source. If a server application is using the ODC file to fetch data, this information will often be used for connecting to the data sources
The following HTML is an example of an ODC connection string inside of an ODC file:
<odc:OfficeDataConnection xmlns:odc="urn:schemas-microsoft-com:office:odc" xmlns="http://www.w3.org/TR/REC-html40"><odc:Connection odc:Type="OLEDB"> <odc:ConnectionString>Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=<Database Name>;Data Source=<Database Server>;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=<Computer Name>;Use Encryption for Data=False;Tag with column collation when possible=False</odc:ConnectionString>
<odc:CommandType>SQL</odc:CommandType>
<odc:CommandText> "<Database Name>"."dbo"."<Stored Procedure Name>"</odc:CommandText>
<odc:SSOApplicationID>ExcelServicesApplicationID</odc:SSOApplicationID>
<odc:CredentialsMethod>Stored</odc:CredentialsMethod>
<odc:AlwaysUseConnectionFile/>
</odc:Connection>
</odc:OfficeDataConnection>
A C# Code Example
The following is a simple console application that shows how to change values inside an ODC file. This code can be used in a feature or a console application with all the previous parameter values provided from a configuration file. This code changes the highlighted values in the data connection XML shown above.
namespace UpdateODCFile{
using System.Linq;
using System.Text;
using System.Xml;
/// <summary>
/// Class to change the ODC file parameters
/// </summary>
class Program
{
/// <summary>
/// Index from where tag begins
/// </summary>
private static int sourceIndex = 0;
/// <summary>
/// Index from where tag ends
/// </summary>
private static int destinationIndex = 0;
static void Main(string[] args)
{
// You can keep the source an destination file path same if you want to
// overwrite the existing file with new values.
string odcFilePath = @"C:\Reports\Connection.odc";
string destinationFilePath = @"C:\Reports\Connection.odc";
// Provide values for following patameters that will be changed in the ODC file.
string databaseName = "<your database name>";
string serverName = "<your server name>";
string SSOApplicationID = "<application ID>";string provider = "<Provider>";
string integratedSecurity = "<integrated security>";
string persistSecurityInfo = "<persist security info>";
string useProcedure = "<use procedure>";
string autoTranslate = "<auto translate>";
string packetSize = "<packet size>";
string workSatationID = "<workstation ID>";
string encryptionData = "<encryption data>";
string tagWithCollation = "<tag with column collation>";
The following code reads the ODC file and retrieves the ODC connection XML data from it.
string xmlConnection = GetConnectionString(odcFilePath);
XmlDocument odcXmlConnection = new XmlDocument();
odcXmlConnection.LoadXml(xmlConnection);
XmlNamespaceManager nameManager = new XmlNamespaceManager(odcXmlConnection.NameTable);
nameManager.AddNamespace("odc", odcXmlConnection.DocumentElement.NamespaceURI);
XmlNodeList nodelistConnectionString = odcXmlConnection.SelectNodes("//odc:Connection/odc:ConnectionString", nameManager);
The following code changes the connection properties mentioned above.
StringBuilder finalConnectionString = CreateNewConnectionString(databaseName, serverName, provider, integratedSecurity, persistSecurityInfo, useProcedure, autoTranslate, packetSize, workSatationID, encryptionData, tagWithCollation, nodelistConnectionString);
nodelistConnectionString[0].InnerText = finalConnectionString.ToString();
The following code changes the SSOApplicationID property in the XML.
XmlNodeList nodelistSSOApplicationID = odcXmlConnection.SelectNodes("//odc:Connection/odc:SSOApplicationID", nameManager);
nodelistSSOApplicationID[0].InnerText = SSOApplicationID;
The following code saves the updated file on to a disk. When this is complete, the file can be published to SharePoint.
SaveConnectionString(odcFilePath, destinationFilePath, odcXmlConnection.OuterXml);
}
The following code finds the connection string tag in the ODC file and returns the full connection string.
/// <summary>
/// Finds the connection string in the ODC file
/// </summary>
/// <param name="filePath">path of ODC file</param>
/// <returns>office data connection xml</returns>
public static string GetConnectionString(string filePath)
{
string xmlConnection = string.Empty;
System.IO.StreamReader myFile = new System.IO.StreamReader(filePath);
string myString = myFile.ReadToEnd();
sourceIndex = myString.IndexOf("<odc:OfficeDataConnection");
destinationIndex = myString.IndexOf("</odc:OfficeDataConnection");
xmlConnection = myString.Substring(sourceIndex, destinationIndex - sourceIndex + 27);
myFile.Close();
return xmlConnection;
}
The following code saves the connection string tag to the ODC file and saves it to a disk.
/// <summary>
/// save the changed ODC file
/// </summary>
/// <param name="filePath">path at which you want to read the ODC file</param>
/// <param name="newFilePath">path at which you want to save</param>
/// <param name="connectionString">new data connection string to be changed</param>
public static void SaveConnectionString(string filePath, string newFilePath, string connectionString)
{
string xmlConnection = string.Empty;
System.IO.StreamReader myFile = new System.IO.StreamReader(filePath);
string myString = myFile.ReadToEnd();
myFile.Close();
string lessString = myString.Remove(sourceIndex, destinationIndex - sourceIndex + 27);
myString = lessString.Insert(sourceIndex, connectionString);
System.IO.StreamWriter writer = new System.IO.StreamWriter(newFilePath);
writer.Write(myString);
}
The following code finds the properties in the ODC file and then changes them. If a property does not require any changes, it can be removed from this code. The new connection string will be returned to the Main function.
/// <summary>
/// Function to replace the old values with new one.
/// </summary>
/// <param name="databaseName">database Name</param>
/// <param name="serverName">server Name</param>
/// <param name="provider">provider</param>
/// <param name="integratedSecurity">integrated Security</param>
/// <param name="persistSecurityInfo">persist Security Info</param>
/// <param name="useProcedure">use Procedure</param>
/// <param name="autoTranslate">auto Translate</param>
/// <param name="packetSize">packet Size</param>
/// <param name="workSatationID">work Satation ID</param>
/// <param name="encryptionData">encryption Data</param>
/// <param name="tagWithCollation">tag With Collation</param>
/// <param name="nodelistConnectionString">nodelist Connection String</param>
/// <returns>final connection string</returns>
private static StringBuilder CreateNewConnectionString(string databaseName, string serverName, string provider, string integratedSecurity, string persistSecurityInfo, string useProcedure, string autoTranslate, string packetSize, string workSatationID, string encryptionData, string tagWithCollation, XmlNodeList nodelistConnectionString)
{
string[] connectionStringArray = nodelistConnectionString[0].InnerText.Split(';');
StringBuilder finalConnectionString = new StringBuilder();
foreach (string connections in connectionStringArray.ToList())
{
string[] splitOnEqual = connections.Split('=');
switch(splitOnEqual[0])
{
case "Initial Catalog": splitOnEqual[1] = databaseName;
break;
case "Data Source": splitOnEqual[1] = serverName;
break;
case "Provider": splitOnEqual[1] = provider;
break;
case "Integrated Security": splitOnEqual[1] = integratedSecurity;
break;
case "Persist Security Info": splitOnEqual[1] = persistSecurityInfo;
break;
case "Use Procedure for Prepare": splitOnEqual[1] = useProcedure;
break;
case "Auto Translate": splitOnEqual[1] = autoTranslate;
break;
case "Packet Size": splitOnEqual[1] = packetSize;
break;
case "Workstation ID": splitOnEqual[1] = workSatationID;
break;
case "Use Encryption for Data": splitOnEqual[1] = encryptionData;
break;
case "Tag with column collation when possible": splitOnEqual[1] = tagWithCollation;
break;
}
finalConnectionString = finalConnectionString.Append(splitOnEqual[0]);
finalConnectionString = finalConnectionString.Append("=");
finalConnectionString = finalConnectionString.Append(splitOnEqual[1]);
finalConnectionString = finalConnectionString.Append(";");
}
finalConnectionString = finalConnectionString.Remove((finalConnectionString.Length-1), 1);
return finalConnectionString;
}
}
}
Code Example using a PowerShell
The following is a PowerShell script to accomplish the same task described previously.# Initialize the variables
$BICenterSite = "<Site where you have to upload the updated ODCs>"
$reportingDBname = "<Database Name>"
$databaseServer = "<Database Server Name>"
$listName = "<List Name where ODCs have to be uploaded>"
$ODCFilesFolder = "<Folder path where all the ODCs are present>"
$SubFolderName = "<Sub Folder Name>"
$fileEntry = [IO.Directory]::GetFiles($ODCFilesFolder)
# reading all the ODC files from the given folder
foreach($fileName in $fileEntry)
{
$w=Get-Content $fileName
$d=[string]$w
if($d.Contains("<odc:OfficeDataConnection"))
{
[int] $i = $d.IndexOf("<odc:OfficeDataConnection")
[int] $j = $d.IndexOf("</odc:OfficeDataConnection>")
[xml] $xmlPart = $d.SubString($i, ($j-$i+27))
$con = $xmlPart.OfficeDataConnection.Connection | Select ConnectionString
[string] $connectionString = $con.ConnectionString
[string] $finalString = ""
$stringArray = $connectionString.Split(";")
foreach($element in $stringArray)
{
$item = $element.Split("=")
if($item[0] -eq "Initial Catalog")
{
$item[1]=$reportingDBname
}
if($item[0] -eq "Data Source")
{
$item[1]=$databaseServer
}
# Put all other parameters here in separate if blocks which you want to change.
$finalString=$finalString+$item[0]+"="+$item[1]+";"
}
[string] $finalXmlNode = "<odc:ConnectionString>"+$finalString+"</odc:ConnectionString>"
[string] $finalXml = $xmlPart.OuterXml
[int] $k = $finalXml.IndexOf("<odc:ConnectionString>")
[int] $l = $finalXml.IndexOf("</odc:ConnectionString>")
$finalXml=$finalXml.Remove($k,($l-$k+23))
$finalXml=$finalXml.Insert($k,$finalXmlNode)
[string] $odc=$d.Remove($i,($j-$i+27))
$odc=$odc.Insert($i,$finalXml)
Set-Content -Path $fileName -Value $odc -Force
}
}
$site = New-Object Microsoft.SharePoint.SPSite($BICenterSite)
$web = $site.OpenWeb()
$list = $web.Lists[$listName]
$fileCollection = $list.RootFolder.SubFolders[$SubFolderName].Files
# Uploading the ODC files on SharePoint server
foreach ($file in $fileEntry)
{
$stream = $file.OpenRead()
$uploaded = $fileCollection.Add($file.Name, $stream, $TRUE)
$uploaded.Item.File.Publish("Published by PowerShell script")
"Uploaded " + $file.Name
if ($stream) {$stream.Dispose()}
}
# Disposing the web and site objects
if ($web) {$web.Dispose()}
if ($site) {$site.Dispose()}
Conclusion
This post explained how to write code to update ODC files programmatically. This approach can be used to update the ODC files when moving them from one environment to another. The PowerShell script can be useful for automated deployment of ODC files.How to set automatically focus on ASP.NET controls when validation fails ?
If you are using ASP.NET Validation Control then you can use “SetFocusOnError” properties to automatically focus the control if validation fails. This will help the end user to identify the control easily.
To set focus automatically you have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically move to the control which is specified in ControlToValidate.
![SetFocus SetFocus](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_twYYOV7PbYhHOxr86Bg14zmeHqxUMPiMvm1DdNKqeHp3fqTZHeZk7UrNhDeluSWP0aq9mV1POf5YQlYXUt9YOPZnxFWrdjL6GC3dKz9GVBWS5iWpiE1DPkwcNOtl_BkXnURs7IJbPcX5sOn2CC72WV=s0-d)
Now in such case where multiple validation fails at same time then first validation will get the focus.
Hope this will help you !
Cheers !
If you are using ASP.NET Validation Control then you can use “SetFocusOnError” properties to automatically focus the control if validation fails. This will help the end user to identify the control easily.
To set focus automatically you have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically move to the control which is specified in ControlToValidate.
![SetFocus SetFocus](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_twYYOV7PbYhHOxr86Bg14zmeHqxUMPiMvm1DdNKqeHp3fqTZHeZk7UrNhDeluSWP0aq9mV1POf5YQlYXUt9YOPZnxFWrdjL6GC3dKz9GVBWS5iWpiE1DPkwcNOtl_BkXnURs7IJbPcX5sOn2CC72WV=s0-d)
Now in such case where multiple validation fails at same time then first validation will get the focus.
Hope this will help you !
Cheers !If you are using ASP.NET Validation Control then you can use “SetFocusOnError” properties to automatically focus the control if validation fails. This will help the end user to identify the control easily.
To set focus automatically you have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically move to the control which is specified in ControlToValidate.
![SetFocus SetFocus](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_twYYOV7PbYhHOxr86Bg14zmeHqxUMPiMvm1DdNKqeHp3fqTZHeZk7UrNhDeluSWP0aq9mV1POf5YQlYXUt9YOPZnxFWrdjL6GC3dKz9GVBWS5iWpiE1DPkwcNOtl_BkXnURs7IJbPcX5sOn2CC72WV=s0-d)
Now in such case where multiple validation fails at same time then first validation will get the focus.
Hope this will help you !
Cheers !
To set focus automatically you have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically move to the control which is specified in ControlToValidate.
Now in such case where multiple validation fails at same time then first validation will get the focus.
Hope this will help you !
Cheers !
If you are using ASP.NET Validation Control then you can use “SetFocusOnError” properties to automatically focus the control if validation fails. This will help the end user to identify the control easily.
To set focus automatically you have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically move to the control which is specified in ControlToValidate.
Now in such case where multiple validation fails at same time then first validation will get the focus.
Hope this will help you !
Cheers !If you are using ASP.NET Validation Control then you can use “SetFocusOnError” properties to automatically focus the control if validation fails. This will help the end user to identify the control easily.
To set focus automatically you have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically move to the control which is specified in ControlToValidate.
Now in such case where multiple validation fails at same time then first validation will get the focus.
Hope this will help you !
Cheers !
Programmatically Create a Managed Metadata List Column (Mohammed Faizan)
Managed metadata is a hierarchical collection of centrally managed terms that you can define, and then use as attributes for items in Microsoft SharePoint Server 2010. Refer here for more information on the managed metadata in SharePoint 2010.
A column is a location in a list in which to store information about a SharePoint Server 2010 item. When you define a column, you provide a name for the column, specify the column's type, and provide additional information that depends on the column type.
SharePoint Server 2010 introduces a new column type named managed metadata. When you create a managed metadata column, you specify the term set from which the column's values must come. When you want users to provide information for list items (including documents), and the valid values for the information are contained in a term set, use a managed metadata column. Create a new content type or modify an existing content type, and then add the managed metadata column to the content type.
This post describes the way of programmatically creating a managed metadata taxonomy column and adding the column to a custom content type.
In this article, you:
Before you begin, ensure that you have the Managed Metadata service provisioned and Term sets and terms created. Figure 1 shows the terms set and terms.
Figure 1. Term set and terms
![Figure01 Figure01](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_srSwcPqUlHKvruml31oL_TvqbQBRZi1dqjLs0kaIVgLwz4wuK5sFprFBw-S2OenX9JaYb02vmG85gfsvqaFxNy4H_fLkcjbt_hGjQHmC9P4T44YD5A_2NxoDhcBTbBvlgntFz-ZzvA9YV5RK_YRJUJ8s0UM4Ww0bFaCiFUwLgdm0i8QkyqCrtDsQCwA3yW_MbUj_csSyaBKme2iGvZJnaXMEqBhHSQwlHwhEWL3bLOsIsBTzNeOXFXFbL_iOdylWU=s0-d)
1. In Visual Studio 2010, click New Project, expand the SharePoint node, click 2010, and then click Empty SharePoint Project. Provide name for the project.
2. In the SharePoint Customization Wizard, select the local SharePoint site that will be used for debugging. Select the Deploy as a farm solution option and then click Finish.
Note: Creating a TaxonomyField class requires a reference to the Microsoft.SharePoint.Taxonomy.dll. This .dll is not available in a sandbox solution and therefore the solution will have to be deployed as a farm solution.
3. In Solution Explorer, right-click the Features node, and then click Add Feature as shown in Figure 2.
Figure 2. Add the feature
![Figure02 Figure02](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_sv4ygshkeTNPR9BgG5FRPLrVBXQHFDV-tjBKywTS55UZBpRgsJBY_8dW8FUEAZxgRGQjrrETwThRQHGrnCe-Osoh01LZZI9GWsA4Sgd3Q15N6K1YQ_-HhMKk_Xejz5KwO9QREdbEGQmeGv1c00JxMgzpaeRq7kN6lLg_7BaV8Z0iAGsTviCfQT3rChODHeJD6WBe2g05JvrPFpdCTnwUu_oErCHn2p-Lcl-wqB49o-I1HYttmeTVKOMRThN9nw90k=s0-d)
4. Name the feature AddMMSColumn and add a description as shown in Figure 3. Change the Scope to Site.
Figure 3. Define the feature
![Figure03 Figure03](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_uDnfS3YILLyFC_61R3LNOIGHSiR8Cmcw2dpoHfbRqY3bBwbyPJU9H1wVgm5aT3w2LpLpmC_D-0_VIPN2bSBipOWEHqwI2jr7r4NLQ1WmdYgwBUlubM30jM0riHX6VMGpcaKQ7Nb83q0rRBz1cCYiaFJQ1q0CMbh3i2nRAuNWstDZvR7xOBAP5zHbBiy7sno5LJCi7S947RljeT9XVr96zN39SNL3Km2JhK4bV1hyqTnJ1oROQ15B-OMeX-WVseoco=s0-d)
5. Right click the AddMMSColumn feature node and then click Add Event Receiver. (see Figure 4).
Figure 4. Add an event receiver
![Figure04 Figure04](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_uY6EI8m6oYz668Hneop38rx-QFI24a6782s_ccRloh2oCqRBP4IM4GFx9otYajcr2sO4ily2jHhqFnTphY1ljZLcZcgWzXjHO1Tqst76IJrD1bJaRDYyWtnfpcaA64psu1qTSKKiPCJ0syqSJvtp6wB9x1Axv2ugD8-zGZCvOYZLoewqvq6tR51B8eqLEvDGQO2hq-snPjaog3oaHxFO1QrKc1gSP0V8TQOJylrFmDXujprQ9fEsD2yD8H00t3Jhk=s0-d)
6. Add the following code in the feature receiver’s FeatureActivated event.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
const string TermStoreName = "Managed Metadata Service";
const string GroupName = "Office Locations";
const string TermSetName = "Europe";
const string SPLocationListColumn = "OfficeLocation";
const string ContentTypeOfficeDetails = "Office Details";
//Get the Taxonomy session for current SPSite
TaxonomySession session = new TaxonomySession(SPContext.Current.Site);
if (session.TermStores.Count != 0)
{
using (SPSite site = (SPSite)properties.Feature.Parent)
{
SPWeb rootweb = site.RootWeb;
var termStore = session.TermStores[TermStoreName];
var group = from g in termStore.Groups where g.Name == GroupName select g;
var termSet = group.FirstOrDefault().TermSets[TermSetName];
//Get the content type to which the taxonomy field is to be added
SPContentType contentTypeOfficeDetails = rootweb.ContentTypes[ContentTypeOfficeDetails];
//Check if field exists, if yes take no action
bool fieldExists = rootweb.Fields.ContainsField(SPLocationListColumn);
if (!fieldExists)
{
//Create a new TaxonomyField
TaxonomyField field = rootweb.Fields.CreateNewField("TaxonomyFieldType", SPLocationListColumn) as TaxonomyField;
field.SspId = termSet.TermStore.Id;
field.TermSetId = termSet.Id;
field.TargetTemplate = string.Empty;
field.AllowMultipleValues = true;
field.CreateValuesInEditForm = true;
field.Open = true;
field.AnchorId = Guid.Empty;
field.Group = "Taxonomy Fields";
//Add the taxonomy field to site columns
rootweb.Fields.Add(field);
rootweb.Update();
TaxonomyField fieldAdded = rootweb.Fields[SPLocationListColumn] as TaxonomyField;
//Add the field to the a custom content type
SPFieldLink fieldLnkArticle = new SPFieldLink(fieldAdded);
contentTypeOfficeDetails.FieldLinks.Add(fieldLnkArticle);
contentTypeOfficeDetails.Update(true);
}
}
}
7. Right click the project name in Visual Studio and then click Deploy as shown in Figure 5.
Figure 5. Deploy the solution
![Figure05 Figure05](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_v6P93n9thR9Wk4A9e-MOvvQsxna6mrlcsJt1UbLvrOUPZ74KKDCLRkho-BGFXFAhrf1fLptBHTCVPmJOTj64rfRj3V0tv4wH2ZyNrm9rtUkcGIlpLZx5AlaRxlAAj2cFu8Eqk88R83PZ1wx90FE6pk5ifMKxU-uMw-Xt4y3UWNZbvsf193BKRLUzbuvBKwwgIIDWA1YnJGPwMrEbc4KkT-8KMaHyT0TD5P6PZeCSdkfWbo2CstsTVEfRIFn23Z0sc=s0-d)
8. Navigate to the site where the feature is activated. Click Site Settings and then click Site columns. The newly created column is visible in the Taxonomy Fields group as shown in Figure 6.
Figure 6. The newly create column
![Figure06 Figure06](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_vU_aVfMAAbvQqwrXALaOoJxj3n2EAOQANUg22sJ30urQrMUC2PNyzcX8_AIdDQo6sn7vYu-Nh6qck_-0pIeECRS8yU7cj1_mgzZyBnsPdpBdG53I7qukwhFUUikN--6-PXNNhxHMFD5mfINm6SK_E_crq-PF9voxIR5mmSyCTgbhJ2VP2lEo39E42AQHxOnMVkGXYirhyo6dbDXQkv6vB2-NaW9ag6o19G_iMQ9nVXMVASS0cg8xJmKKb2P2dBIcM=s0-d)
9. Click the column name to go to the Edit page of the column. The term set that was specified in the code should be selected as shown in Figure 7.
Figure 7. The highlighted term set
![Figure07 Figure07](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_uNZDbRHEUvnuhITDwv0jF6-60555fWAJclEUTxBXAR7ZXKJdEPJ-VybfIHY2ZYtW4RRsFEXtJnVv27Mfas5sB-Jl3ZMYQcrQju6xK0L0o3L0ACSSds4vDOJL_9Wmcjw4ie_uPiIVrFN-ntEFX9Qig5SG1iZ_hLFyHtfSb6-YECdzvezZGz-p_BK9D8dJsHfQcycQKkXZESYa2iQG3aV5XFUKui4-cstnlSflasCONE5Vi94wx7hH0G6OryGzR-x8w=s0-d)
10. Click Site Settings and then click Site content types. Click the content type to which the column was added. The column is visible in the Manage content type page of the selected content type (see Figure 8).
Figure 8. The new column
![Figure08 Figure08](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_v5UJq3_WJYZAydXKDD2q2wqTsMhOud1oN0juGstgfzlSu69dO8ePxsWKI6GbHoSOPvxmAPHQMFgxqD3vaw66oog_3HAxpxyY1WWpYJjYv88gKncOSL1sqm7FDR2-_TV_t4Qi_gecZ_EgMa_kcmE0YK-wr1A8xuPsLAtxXl0JNh6NDIw5GrOXeX2GX7egFkJBlE899JIuQDqRcBNvrF8ZEIlaa-NGbbysOOJpg9nOPUb6gpLFJebJxO3rOoafKyDqs=s0-d)
You can start using this content type or the column in your lists and libraries.
A column is a location in a list in which to store information about a SharePoint Server 2010 item. When you define a column, you provide a name for the column, specify the column's type, and provide additional information that depends on the column type.
SharePoint Server 2010 introduces a new column type named managed metadata. When you create a managed metadata column, you specify the term set from which the column's values must come. When you want users to provide information for list items (including documents), and the valid values for the information are contained in a term set, use a managed metadata column. Create a new content type or modify an existing content type, and then add the managed metadata column to the content type.
This post describes the way of programmatically creating a managed metadata taxonomy column and adding the column to a custom content type.
In this article, you:
- Create a SharePoint 2010 project
- Add a feature and feature receiver
- Add code to create a managed metadata site column and then add the site column to a custom content type
- Deploy the solution to SharePoint 2010
Programmatically Create the Managed Metadata Column
The following steps deploy the code to SharePoint 2010 as a feature receiver that programmatically creates the managed metadata column. The procedures in this section assume a development environment where SharePoint 2010 is installed and configured, Microsoft Visual Studio 2010 is installed, and the currently logged-in user has administrative rights on the SharePoint environment for deployment purposes.Before you begin, ensure that you have the Managed Metadata service provisioned and Term sets and terms created. Figure 1 shows the terms set and terms.
Figure 1. Term set and terms
1. In Visual Studio 2010, click New Project, expand the SharePoint node, click 2010, and then click Empty SharePoint Project. Provide name for the project.
2. In the SharePoint Customization Wizard, select the local SharePoint site that will be used for debugging. Select the Deploy as a farm solution option and then click Finish.
Note: Creating a TaxonomyField class requires a reference to the Microsoft.SharePoint.Taxonomy.dll. This .dll is not available in a sandbox solution and therefore the solution will have to be deployed as a farm solution.
3. In Solution Explorer, right-click the Features node, and then click Add Feature as shown in Figure 2.
Figure 2. Add the feature
4. Name the feature AddMMSColumn and add a description as shown in Figure 3. Change the Scope to Site.
Figure 3. Define the feature
5. Right click the AddMMSColumn feature node and then click Add Event Receiver. (see Figure 4).
Figure 4. Add an event receiver
6. Add the following code in the feature receiver’s FeatureActivated event.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
const string TermStoreName = "Managed Metadata Service";
const string GroupName = "Office Locations";
const string TermSetName = "Europe";
const string SPLocationListColumn = "OfficeLocation";
const string ContentTypeOfficeDetails = "Office Details";
//Get the Taxonomy session for current SPSite
TaxonomySession session = new TaxonomySession(SPContext.Current.Site);
if (session.TermStores.Count != 0)
{
using (SPSite site = (SPSite)properties.Feature.Parent)
{
SPWeb rootweb = site.RootWeb;
var termStore = session.TermStores[TermStoreName];
var group = from g in termStore.Groups where g.Name == GroupName select g;
var termSet = group.FirstOrDefault().TermSets[TermSetName];
//Get the content type to which the taxonomy field is to be added
SPContentType contentTypeOfficeDetails = rootweb.ContentTypes[ContentTypeOfficeDetails];
//Check if field exists, if yes take no action
bool fieldExists = rootweb.Fields.ContainsField(SPLocationListColumn);
if (!fieldExists)
{
//Create a new TaxonomyField
TaxonomyField field = rootweb.Fields.CreateNewField("TaxonomyFieldType", SPLocationListColumn) as TaxonomyField;
field.SspId = termSet.TermStore.Id;
field.TermSetId = termSet.Id;
field.TargetTemplate = string.Empty;
field.AllowMultipleValues = true;
field.CreateValuesInEditForm = true;
field.Open = true;
field.AnchorId = Guid.Empty;
field.Group = "Taxonomy Fields";
//Add the taxonomy field to site columns
rootweb.Fields.Add(field);
rootweb.Update();
TaxonomyField fieldAdded = rootweb.Fields[SPLocationListColumn] as TaxonomyField;
//Add the field to the a custom content type
SPFieldLink fieldLnkArticle = new SPFieldLink(fieldAdded);
contentTypeOfficeDetails.FieldLinks.Add(fieldLnkArticle);
contentTypeOfficeDetails.Update(true);
}
}
}
7. Right click the project name in Visual Studio and then click Deploy as shown in Figure 5.
Figure 5. Deploy the solution
8. Navigate to the site where the feature is activated. Click Site Settings and then click Site columns. The newly created column is visible in the Taxonomy Fields group as shown in Figure 6.
Figure 6. The newly create column
9. Click the column name to go to the Edit page of the column. The term set that was specified in the code should be selected as shown in Figure 7.
Figure 7. The highlighted term set
10. Click Site Settings and then click Site content types. Click the content type to which the column was added. The column is visible in the Manage content type page of the selected content type (see Figure 8).
Figure 8. The new column
You can start using this content type or the column in your lists and libraries.
SharePoint Developer Tools in Visual Studio 11 Beta – Part III: Tips and Tricks in SharePoint List Designer
the Part I of this series, we were pleased to announce the SharePoint List Designer as one of the new features introduced in Visual Studio 11 Beta. Using the List Designer, you can quickly and visually build a SharePoint list within Visual Studio without having to create a list first in SharePoint Designer and then import it into Visual Studio.
To familiarize you with the List Designer, in Part I of this series, we provided a link to a MSDN Help topic that walks you through the process of creating a list and a content type by using the List Designer. If you’ve used the List Designer, you might want more details about its functionality. This blog post provides more information about it.
To familiarize you with the List Designer, in Part I of this series, we provided a link to a MSDN Help topic that walks you through the process of creating a list and a content type by using the List Designer. If you’ve used the List Designer, you might want more details about its functionality. This blog post provides more information about it.
Monday, July 16, 2012
How to set automatically focus on ASP.NET controls when validation fails ?
If you are using ASP.NET Validation Control then you can use “SetFocusOnError” properties to automatically focus the control if validation fails. This will help the end user to identify the control easily.
To set focus automatically you have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically move to the control which is specified in ControlToValidate.
![](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_uYps3HFgix-AeR7_n0ta94_wMJ2FXsAMOgpU-T95oyJUk6QCOsKDYrwDm3b_X2B3CK8Ni4Ti39GKufpjCbBLGYJ44MhP9RS8HN0OakwME-BpJZ6ILkNgjiUpn1pRo=s0-d)
Now in such case where multiple validation fails at same time then first validation will get the focus.
Hope this will help you !
Cheers !
To set focus automatically you have to set SetFocusOnError=”True”. By default it’s false. SetFocusOnError of a validation control is associated with “ControlToValidate” properties. If the validation fails, focus will automatically move to the control which is specified in ControlToValidate.
Now in such case where multiple validation fails at same time then first validation will get the focus.
Hope this will help you !
Cheers !
Subscribe to:
Posts (Atom)