Hi folks,
This is the one more article of the BCS series. Learn how to create ECTs via Assembly .NET in SharePoint 2010 through Business Connectivity Services!
This approach will take advantage of the interface IContextProperty to get the BDC Connection details set against the BDC Model.
Enjoy it!
Creating ECTs via Assembly .NET
Creating ECTs via Assembly .NET just requires VS2010. The SPD2010 will not be used.
This approach can be applied in environments that:
-
Need to create business rules, which can be developed against the BDC model;
-
Use databases other than SQL Server, which can be implemented in the data access tier;
-
Require the deployment of WSP packages to activate features, which is automatically generated by VS2010;
If you have this scenario, this implementation has a higher level of difficulty by the level of details in creating the assembly .NET, which is displayed in the next sections of this article.
Working with Visual Studio 2010
The template called Business Data Connectivity Model will be used in this article. Start by opening up VS2010 and create a new project according to the Figure 1:
Figure 1 - Creating a new project and solution
Immediately after that a Wizard helps you in setting up the project. The URL needs to be validated for debugging purposes, and the solution will be created as a Farm Solution, according to the Figure 2:
Figure 2 – Wizard
Note: Once the project is created, delete the classes called Entity1 and Entity1Service. Don’t forget to delete the entity created which is available in the BDC Designer, because new classes will be generated in a new model.
Data Access Layer
Due to the fact the feature will be created as a package WSP, I preferred to provide data access in the same project. Some objects need to be added to manipulate the database, and for demonstration purposes I am using LINQ to SQL because it is simpler to implement.
Add the LINQ to SQL object to the project and name it Dev.dbml, then create a new connection through the Server Explorer that uses Windows Authentication, open the database and drag the table Contact (Part II) according to the Figure 3:
Figure 3 - Adding table Contact
Before manipulating data of the Contact object, a class that contains CRUD methods needs to be created. So create a class called ContactManager and add the code below, whose comments are well documented:
Code Snippet
- public class ContactManager
- {
- /// <summary>
- /// Gets all the Contacts
- /// </summary>
- /// <returns>Contacts Array</returns>
- public Contact[] GetContacts()
- {
- var contacts = new List<Contact>();
-
- using (DevDataContext dev = new DevDataContext())
- {
- contacts = (from cont in dev.Contacts
- select cont).ToList();
- }
- return contacts.ToArray();
- }
-
- /// <summary>
- /// Gets a specific Contact
- /// </summary>
- /// <param name="contactId">Contact Id</param>
- /// <returns>Returns the Contact</returns>
- public Contact GetContactById(int contactId)
- {
- var contact = new Contact();
-
- using (DevDataContext dev = new DevDataContext())
- {
- contact = (from cont in dev.Contacts
- where cont.ContactID == contactId
- select cont).First();
- }
- return contact;
- }
-
- /// <summary>
- /// Updates a specific Contact
- /// </summary>
- /// <param name="contact">Contact to be updated</param>
- public void UpdateContact(Contact contact)
- {
- var contactDB = new Contact();
-
- using (DevDataContext dev = new DevDataContext())
- {
- contactDB = (from cont in dev.Contacts
- where cont.ContactID == contact.ContactID
- select cont).First();
-
- // Alters the object
- contactDB.Address = contact.Address;
- contactDB.City = contact.City;
- contactDB.CompanyName = contact.CompanyName;
- contactDB.ContactName = contact.ContactName;
- contactDB.ContactTitle = contact.ContactTitle;
- contactDB.Country = contact.Country;
- contactDB.Email = contact.Email;
- contactDB.Fax = contact.Fax;
- contactDB.Phone = contact.Phone;
- contactDB.PostalCode = contact.PostalCode;
- contactDB.Region = contact.Region;
-
- // Submitting the changes
- dev.Refresh(System.Data.Linq.RefreshMode.KeepChanges, contactDB);
- dev.SubmitChanges();
- }
- }
-
- /// <summary>
- /// Adds a Contact
- /// </summary>
- /// <param name="contact">New Contact</param>
- public void AddContact(Contact contact)
- {
- using (DevDataContext dev = new DevDataContext())
- {
- dev.Contacts.InsertOnSubmit(contact);
- dev.SubmitChanges();
- }
- }
-
- /// <summary>
- /// Deletes a Contacts
- /// </summary>
- /// <param name="contactId">Contact Id</param>
- public void DeleteContact(int contactId)
- {
- using (DevDataContext dev = new DevDataContext())
- {
- var contact = (from cont in dev.Contacts
- where cont.ContactID == contactId
- select cont).First();
- dev.Contacts.DeleteOnSubmit(contact);
- dev.SubmitChanges();
- }
- }
- }
Note: This was already explained when creating ECTs via Web Services in part II, however as this is important in this demo, the same code was reused.
Create a new partial class called DevDataContext, as we already have this class automatically generated by Visual Studio. Create a new constructor, according to the code below:
Code Snippet
- public partial class DevDataContext
- {
- public DevDataContext() :
- base(BdcModel1.ContactService.GetConnection(), mappingSource)
- {
- OnCreated();
- }
- }
Note: This new constructor contains a call to the method GetConnection(). It belongs to the ContactService class and returns the connection string, which is obtained directly from the BDC Metadata Model (we’ll check it soon).
BDC Model
By using the new BDC Panels in Visual Studio the Metadata Model will be created. It needs to be created based on the Data Access layer, as we will work with the Contact entity. Do this by using the BDC Designer Panel, according to the Figure 4:
Figure 4 - Contact entity added
As the Contact entity was created, now it must be configured. In order to do that add an Identifier called ContactID and the following Methods: GetConnection, ReadItem, ReadList, Delete, Update and Create. The context menu makes things easier, according to the Figure 5:
Figure 5 - Identifier and Methods added
To add and configure methods, the most convenient way is the utilisation of the BDC Method Details Panel (as this tool is going to generate XML automatically) according to the Figure 6:
Figure 6 - BDC Method Details Panel in action
The Table 1 below shows a summary of the configuration started in the Figure 6. It contains all the methods and signatures:
Option | Method | Parameters | Direction | Type Descriptor |
Create Creator Method | Create | returnContact | Return | ReturnContact |
| | newContact | In | NewContact |
Create Deleter Method | Delete | contactID | In | ContactID |
Create Finder Method | ReadList | contactList | Return | ContactList |
Create Specific Finder Method | ReadItem | contact | Return | Contact |
| | contactID | In | ContactID |
Create Updater Method | Update | contact | In | Contact |
Create Blank Method | GetConnection | parameter | Return | connection |
Table 1 - Automatic method generation of the Contact entity Note: A Blank Method will create a method called Method, which needs to be renamed. In this example call it GetConnection.
Before configuring the methods, make sure that the ContactID identifier type is System.Int32. Take the ReadItem method as the first one to be configured and click over the parameter (aka type descriptor) Contact, so we can select its type according to the Figure 7:
Figure 7 - TypeDescriptor type
The next step is to include new Type Descriptors to the Type Descriptor called Contact through BDC Explorer Panel, which basically represent its attributes. The Figure 9 displays how to add Type Descriptors and the Table 2 reveals the Type Descriptors to be added.
Figure 8 - Adding TypeDescriptors to Contact
Type Descriptor | Type |
Address | System.String |
City | System.String |
CompanyName | System.String |
ContactID | System.Int32 |
ContactName | System.String |
ContactTitle | System.String |
Country | System.String |
Email | System.String |
Fax | System.String |
Phone | System.String |
PostalCode | System.String |
Region | System.String |
Table 2 - Types of Type Descriptors Once created, these Type Descriptors will be automatically reused when creating other methods. The code below shows the XML automatically generated of the Contact entity after configuring of all methods. This was extracted from the file called BdcModel1.bdcm:
Note: The file BdcModel1.bdcm can be visualised in XML directly through Visual Studio, just using the context menu Open With... and then XML (Text) Editor.
BDC Model Connection
Connection details can be set inside of the LobSystemInstance properties if you are using a database or web service. As we have this scenario, the code below shows the connection details:
Code Snippet
- <LobSystemInstance Name="BdcModel1">
- <Properties>
- <Property Name="AuthenticationMode" Type="System.String">PassThrough</Property>
- <!-- AuthenticationMode can be set to PassThrough, RevertToSelf, RdbCredentials, or WindowsCredentials. -->
- <Property Name="DatabaseAccessProvider" Type="System.String">SqlServer</Property>
- <!-- Options: SQL Server, OleDB, Oracle, or ODBC. -->
- <Property Name="RdbConnection Data Source" Type="System.String">W2008R2Sub1</Property>
- <!-- Type the database server name or the SQL Server instance name in the format SQLServer\Instance. -->
- <Property Name="RdbConnection Initial Catalog" Type="System.String">Dev</Property>
- <!-- Type the database name. -->
- <Property Name="RdbConnection Integrated Security" Type="System.String">SSPI</Property>
- <!-- Type SSPI for Integrated Security. -->
- <Property Name="RdbConnection Pooling" Type="System.String">false</Property>
- <!-- Type true or false for Pooling -->
- </Properties>
- </LobSystemInstance>
Note: If you want to know more about the authentication types available through BCS, check the section References. Basically the XML above contains properties commonly used when creating connection strings.
BDC Model Entity Methods
Along the creation of methods through BDC Panels, Visual Studio took charge of the generation of the ContactService class and its respective methods. They are not implemented yet and are throwing an exception type of NotImplementedException.
Before coding all methods, do you remember the code that contains the method called GetConnection? It needs to return a database connection string, but how? Well, we are going to take advantage of the LobSystemInstance properties set previously.
But how to read the XML that contains those properties? Easy peasy! Just implement the interface IContextProperty in the ContactService class and the BDC does the trick for you.
Note: When an assembly contains a class that implements IContextProperty, its properties are automatically initialized at the time the assembly is executed in BDC. It helps a lot!
Do that by adding a reference to the assembly Microsoft.Business, which is available at the 14: \ISAPI\Microsoft.BusinessData.dll.
Check out the code below, which shows the ContactService class:
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using ContactServices.BdcModel;
- using Microsoft.BusinessData.SystemSpecific;
- using Microsoft.BusinessData.MetadataModel;
- using Microsoft.BusinessData.Runtime;
- using Microsoft.BusinessData.MetadataModel.Collections;
-
- namespace ContactServices.BdcModel.BdcModel1
- {
- public partial class ContactService : IContextProperty
- {
- private static IMethodInstance methodInstance;
- private static ILobSystemInstance lobSystemInstance;
- private static IExecutionContext executionContext;
-
- #region IContextProperty implementation
-
- public IMethodInstance MethodInstance
- {
- get { return methodInstance; }
- set { methodInstance = value; }
- }
-
- public ILobSystemInstance LobSystemInstance
- {
- get { return lobSystemInstance; }
- set { lobSystemInstance = value; }
- }
-
- public IExecutionContext ExecutionContext
- {
- get { return executionContext; }
- set { executionContext = value; }
- }
-
- #endregion
-
- public static Contact ReadItem(int contactID)
- {
- // Implement your own business rules
- return new ContactManager().GetContactById(contactID);
- }
-
- public static IEnumerable<Contact> ReadList()
- {
- // Implement your own business rules
- return new ContactManager().GetContacts();
- }
-
- public static Contact Create(Contact newContact)
- {
- if (string.IsNullOrEmpty(newContact.ContactName) || string.IsNullOrEmpty(newContact.Email) || string.IsNullOrEmpty(newContact.Phone))
- throw new ObjectNotFoundException("ContactName, Email and Phone are mandatories.");
-
- var manager = new ContactManager();
- manager.AddContact(newContact);
- return manager.GetContactById(newContact.ContactID);
- }
-
- public static void Update(Contact contact)
- {
- if (string.IsNullOrEmpty(contact.ContactName) || string.IsNullOrEmpty(contact.Email) || string.IsNullOrEmpty(contact.Phone))
- throw new ObjectNotFoundException("ContactName, Email and Phone are mandatories.");
-
- new ContactManager().UpdateContact(contact);
- }
-
- public static void Delete(int contactID)
- {
- // Implement your own business rules
- new ContactManager().DeleteContact(contactID);
- }
-
- public static string GetConnection()
- {
- INamedPropertyDictionary properties = lobSystemInstance.GetProperties();
-
- string template = "Data Source={0};Initial Catalog={1};Integrated Security={2};";
-
- string dataSource = "RdbConnection Data Source";
- string initialCatalog = "RdbConnection Initial Catalog";
- string integratedSecurity = "RdbConnection Integrated Security";
-
- if (!properties.ContainsKey(dataSource) || !properties.ContainsKey(initialCatalog) || !properties.ContainsKey(integratedSecurity))
- throw new Exception("LobSystemInstance does not contain a connection string");
-
- return string.Format(template, properties[dataSource].ToString(), properties[initialCatalog].ToString(), properties[integratedSecurity].ToString());
-
- }
- }
- }
With the exception of the GetConnection method, all the others call CRUD methods from the ContactManager class. Still, in the Create and Update methods there is a validation of the required fields ContactName, Email and Phone, which cannot be null or empty as they throw an exception type of ObjectNotFoundException.
As expected the GetConnection method gets the properties of LobSystemInstance, which contains the BDC connection details, by returning the connection string used in the constructor of the DevDataContext Partial Class.
Creating the Deployment Package
Deployment of WSP packages in the real world is performed either manually or using scripts, not directly with the intervention of Visual Studio. I am explaining this for purposes of demonstration and understanding of STSADM.
Before generating the WSP package, some more settings are needed. Rename the feature to BdcModelFeature and add a property SiteUrl in the XML file BdcModelFeature.Template.xml that contains the URL for deployment, according to the Figure 9:
Figure 9 – Feature Property
Finally generate the WSP package by selecting Package in the context menu of Visual Studio. Get the WSP package from the Bin directory and by using STSADM deploy it with the following commands:
stsadm -o addsolution -filename "ContactServices.BdcModel.wsp"
stsadm -o deploysolution -name "ContactServices.BdcModel.wsp" -allowGacDeployment –immediate
stsadm -o execadmsvcjobs
stsadm -o installfeature -filename "ContactServices.BdcModel_BdcModelFeature\feature.xml" –force
stsadm -o activatefeature -name "ContactServices.BdcModel_BdcModelFeature"
Note: Download the solution here.
Configuring the External List
At this stage it is already possible to create an External List that will provide a visual interface to the external data in SharePoint 2010. Both SharePoint Designer and the SharePoint UI provides a way for us to create an External List, in the Part II I have showed how to use SharePoint Designer for this and now I am going to show how to create it by SharePoint UI.
Go to the web site and access Site Actions > More Options. The Figure 10 displays the modal dialog to select the External List:
Figure 10 – Selecting the External List
Then pick up the External Content Type ContactServices.BdcModel.BdcModel1.Contact and create the Contacts List, as displayed in the Figure 11:
Figure 11 - Creating the Contacts External List
After doing this you will get your Contacts List created. Is that all? No, you need to set permissions in the BDC Service Application for this Assembly, otherwise you will get the following screen:
Figure 12 – Access denied by Business Data Connectivity
Settings BDC Permissions
After the deployment of the .NET Assembly you need to set proper permissions in the BDC Service Application for users to see the external data. Go to the BDC Service Application in the Central Administration and find the .NET Assembly:
Figure 13 – Find the .NET Assembly
Then specify the users that are going to be allowed to see the external data, according to the Figure 14:
Figure 14 – Set Object Permissions
By doing this, refresh the External List (Figure 12) and you will get the external data.
This was advanced guys, from now on you are able to create your own ECTs via .NET Assemblies.
The BDC series is not yet finished, next time I will show how to interface ECTs with Client Applications. See you next time!
Reference:
http://msdn.microsoft.com/en-us/library/ee556826(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/microsoft.businessdata.systemspecific.icontextproperty(office.14).aspx
Cheers,
Marcel Medina
Click here to read the same content in Portuguese.