Logo
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
EPL Standings
 
 
Windows Azure

Integrating the SharePoint Server Object Model and the Entity Data Model (part 1) - Create a Console Application to Write Data to a SharePoint List

8/17/2011 6:36:38 PM
The SharePoint server object model is a server-only API through which you can interact with SharePoint in many different ways. This API is appropriate for applications that reside on the server. For example, you can use the SharePoint server object model when building and deploying Web Parts to the SharePoint server with which they need to interact. You can also use the server object model when creating management tools that people use directly on the server. You can imagine that the console application you’ll create in this article is a server-side application deployed to the SharePoint server.

Before you start this application, you’ll need to create another table in the SQL Azure Customers database you created in this article. Follow the same procedures you did in this article to first create a new table called StoreInformation and then populate that table with a specific set of data, which will include records comprising the following fields:

  • Store ID Primary key

  • Store Title Unique integer value for store

  • Store Name Name of store

  • Store Address Address of store

  • Store Phone Number Phone number for store

  • Latitude Latitudinal location of store

  • Longitude Longitudinal location of store

  • Hours Measurement of daylight hours for a particular latitude and longitude

  • Timestamp Time stamp of data entry

If you remember back, the script that you use to create the table is as follows:

CREATE TABLE [StoreInformation](
[StoreID] [int] IDENTITY(1,1)NOT NULL PRIMARY KEY CLUSTERED,
[StoreTitle] [nvarchar](8)NULL,
[StoreName] [nvarchar](50)NOT NULL,
[StoreAddress] [nvarchar](50)NOT NULL,
[StorePhoneNumber] [nvarchar](50)NULL,
[Latitude] [nvarchar](30)NULL,
[Longitude] [nvarchar](30)NULL,
[Hours] [nvarchar](30)NULL,
[Timestamp] [timestamp] NOT NULL,
)

The script to insert data into the table is as follows (note that LLK Sports is a fictional company):

INSERT INTO [StoreInformation]
([StoreID],[StoreTitle],[StoreName],[StoreAddress],[StorePhoneNumber],[Latitude],[Longitude],
[Hours],[Timestamp])
VALUES
('1', '1-CONS', 'LLK Sports', 'Stanton Mall, Denver, CO, USA',
'322-555-0188', '39.6274999999999998', '-104.221', '12', '0x0000000000000067')


Be sure to add the above record as shown and then a few more records that are valid addresses and latitude/longitudes.

At this point, you can get started creating the application.

1. Create a Console Application to Write Data to a SharePoint List

1.1. Create a Console Application to Write Data to a SharePoint List
  1. Open Microsoft Visual Studio 2010, and select File | New Project.

  2. Select Windows, and then select the Console Application project type. Note that the default .NET Framework setting for a console application is .NET Framework 4.0 Client profile. You’ll need to set your project properties to .NET Framework 3.5 because you’ll be adding the Microsoft.SharePoint.dll to your application, which is not conversant with the .NET Framework 4.

  3. Provide a name for the application (such as AzureConsoleApp), and click OK.

  4. After the project is created, right-click the References node in the Solution Explorer, and select Add Reference.

  5. Click the Browse tab, navigate to the ISAPI folder within the SharePoint root folder system (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI), select the Microsoft.SharePoint.dll as shown in the following image, and click OK.



  6. Next, right-click the project and select Add | New Item. In the installed Templates category, click Data, and then select the ADO.NET Entity Data Model.

  7. Provide a name for the model (for example, AzureStores), and click Add.

  8. In the Entity Data Model wizard, select Generate From Database, and then click Next.

  9. In the Choose Your Data Connection dialog box, click New Connection, and add the name of your SQL Azure server (for example, yourservername.database.windows.net). Click Use SQL Server Authentication to enter your SQL Server Authentication (the user name and password you created in the Windows Azure developer portal), and then in the Select Or Enter A Database Name list, select the Customers database you created in this article.

  10. This will take you back to the Choose Your Data Connection dialog box, which will have generated a connection string for you. To create a demo application, click Yes, and include the sensitive data in the connection string. Note that you would not want to send this information across the wire in production code; instead, you can set it programmatically or from a configuration file.

  11. Provide a name for the model (such as CustomersEntities), and click Next.



  12. In the Choose Your Data Objects dialog box, select the tables you want to include in the model in the Tables node, and click Finish. The table you want to select is the StoreInformation table.

    Now that you have added the ADO.NET EDM to the project, you can use it in your code. In the next steps in this exercise, you’ll programmatically create a “data context”—a reference to your model in code—that you can use to query the model directly.

  13. Right-click the Program.cs file, and select View Code.

  14. Add the following bold code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint;

    namespace AzureConsoleApp
    {
    class Program
    {
    static void Main(string[] args)
    {
    string storeAddressToAdd = "";
    string storePhoneToAdd = "";
    //Be sure to change to your SharePoint server.
    string mySPSite = "http://blueyonderdemo";

    CustomersEntities dc = new CustomersEntities();

    var query = from store in dc.StoreInformations
    where store.StoreName == "LLK Sports"
    select store;

    foreach (var item in query)
    {
    StoreInfo tempStore = new StoreInfo();
    tempStore.storeAddress = item.StoreAddress;
    tempStore.storePhone = item.StorePhone;

    storeAddressToAdd = tempStore.storeAddress;
    storePhoneToAdd = tempStore.storePhone;
    }

    using (SPSite site = new SPSite(mySPSite))
    {
    using (SPWeb web = site.OpenWeb())
    {
    web.AllowUnsafeUpdates = true;

    SPList list = web.Lists["Announcements"];
    SPListItem item = list.Items.Add();
    item["Title"] = "Contoso Store Follow-Up";
    item["Body"] = "Contact request from the store in this
    announcement.";
    item["Store Address"] = storeAddressToAdd;
    item["Store Phone"] = storePhoneToAdd;
    item.Update();

    web.AllowUnsafeUpdates = false;
    }
    }
    Console.Writeline("Hit any key to exit.");
    Console.ReadLine();
    }
    }
    class StoreInfo
    {
    public string storeAddress { get; set; }
    public string storePhone { get; set; }
    }
    }


    The preceding example code is fairly straightforward. The goal of the code is to insert two variables (a store address and a store phone number) into a SharePoint list, along with some other information. The store address and phone number (storeAddressToAdd and storePhoneToAdd) are the variables used to store this information in the code. You got this information by adding the ADO.NET EDM to the Visual Studio project, which was represented as a data model (or context) that you could use in your code, and subsequently querying this data context by using a simple LINQ statement. The following code shows the instantiation of the new data context (dc) along with the query, which uses a hard-coded value of LLK Sports—one of the stores you should have added earlier to the SQL Azure database. Using the hard-coded store name ensures that you’ll retrieve this one store record, which you can then use in the code:

    CustomersEntities dc = new CustomersEntities();

    var query = from store in dc.StoreInformations
    where store.StoreName == "LLK Sports"
    select store;

    Note that the same query run as an SQL statement in SQL Azure would return the following record.



    After you iterate through the results of the query, the results are mapped to a custom object. Note that although this example used a custom class (StoreInfo), because you only need two fields within one entity, you could use two string variables and save yourself some coding.

    After you query the results by using the LINQ statement, you then take that information and use the SharePoint server object model to add the information to SharePoint. In this part of the application, you set the context for the SharePoint site by using the SPSite and SPWeb objects, allowed updates to occur by setting the AllowUnsafeUpdates property to true, programmatically created a new list item (using the item variable), and then called the Update method to update that list item in SharePoint:

     using (SPSite site = new SPSite(mySPSite))
    {
    using (SPWeb web = site.OpenWeb())
    {
    web.AllowUnsafeUpdates = true;

    SPList list = web.Lists["Announcements"];
    SPListItem item = list.Items.Add();
    item["Title"] = "Contoso Store Follow-Up";
    item["Body"] = "Contact request from the store " +
    "in this announcement.";
    item["Store Address"] = storeAddressToAdd;
    item["Store Phone"] = storePhoneToAdd;
    item.Update();

    web.AllowUnsafeUpdates = false;
    }
    }

    Now that you understand the code, you can jump back into Visual Studio and complete the exercise.

    Having built the console application to write data to the Announcements list, you need to add those columns (Store Address and Store Phone) to the list. If you don’t add these columns, your console application will throw an exception.

  15. Navigate to SharePoint, click Lists, and then click the Announcements list.

  16. Click the List tab, and then select List Settings.

  17. Under Columns, click Create Column to add the two new columns. Ensure that the column names are Store Address and Store Phone. You can mark each column as a Single Line Of Text column type.

  18. When you’re done, return to your Visual Studio project, and press F5 to debug the application.

  19. After you create the new list item, press Enter to exit the application. Then navigate to the Announcements list. You should see that a new list item has been added to the Announcements list, which pulled its data from SQL Azure and inserted it into the list by using the ADO.NET EDM you added to your console application.



Using a console application is a simple way to illustrate how you can integrate SharePoint and SQL Azure by using ADO.NET and the SharePoint server object model. However, you’re more than likely going to want to move beyond the simple console application to build common SharePoint artifacts such as Web Parts.

In this next exercise, you’ll create a Visual Web Part. You’re going to use the ADO.NET EDM and the server object model; you’ll also integrate the SQLDataAdapter class so you can see the differences between these two data integration methods.

Other -----------------
- Collaborating on Presentations : Evaluating Web-Based Presentation Applications (part 2)
- Collaborating on Presentations : Evaluating Web-Based Presentation Applications (part 1)
- Securing the Connection to SQL Azure (part 3) - Surface SQL Azure Data in a Visual Web Part
- Securing the Connection to SQL Azure (part 2) - Set Permissions for an External Content Type
- Securing the Connection to SQL Azure (part 1) - Create an Application ID & Create an External Content Type
- Consuming SQL Azure Data : Integrating SQL Azure with BCS by Using SharePoint Designer 2010
- Collaborating on Databases : Exploring Web-Based Databases
- Consuming SQL Azure Data : Introduction to Business Connectivity Services
- Integrating Silverlight, Windows Azure DataMarket, and SharePoint
- Local Application for Updates : JupiterMotorsERP local application
- Collaborating on Spreadsheets : Exploring Web-Based Spreadsheets (part 3)
- Collaborating on Spreadsheets : Exploring Web-Based Spreadsheets (part 2)
- Collaborating on Spreadsheets : Exploring Web-Based Spreadsheets (part 1) - Google Spreadsheets
- Integrating DataMarket Data with a Visual Web Part : Create a WCF Service to Retrieve DATA.gov Crime Data (part 2)
- Integrating DataMarket Data with a Visual Web Part : Create a WCF Service to Retrieve DATA.gov Crime Data (part 1)
- Integrating DataMarket Data with Excel and SharePoint - Consume Windows Azure Data in Excel 2010
- Using Cloud Services : Collaborating on Word Processing (part 2)
- Using Cloud Services : Collaborating on Word Processing (part 1)
- Using Cloud Services : Collaborating on Project Management
- Windows Azure Marketplace DataMarket (part 2)
 
 
Most view of day
- Microsoft OneNore 2010 : Opening a Backup Copy of a Notebook Section
- Microsoft Word 2010 : Creating Desktop Publishing Documents - Adding a Watermark
- Nginx HTTP Server : Basic Nginx Configuration - A configuration for your profile
- Advanced Windows 7 Programming : Working in the Background - DEVELOPING TRIGGER-START SERVICES (part 4)
- Understanding IPv6 (part 1) - Understanding IPv6 Terminology , Understanding IPv6 Addressing
- Microsoft Exchange Server 2010 : Managing Message Pickup, Replay, Throttling, and Back Pressure (part 1) - Configuring and Moving the Pickup and Replay Directories
- Understanding IPv6 (part 3) - Understanding Address Autoconfiguration, Understanding Name Resolution
- Maintaining Dynamics GP : Maintaining updated code by rolling out Service Packs with Client Updates
- Microsoft Exchange Server 2010 : Completing Transport Server Setup (part 3) - Enabling Anti-Spam Features
- Sharepoint 2013 : Service Application Fundamentals (part 3) - Connecting Across Farms
Top 10
- Windows Server 2012 : DHCP,IPv6 and IPAM - Exploring DHCP (part 3) - Creating IPv4 DHCP Scopes
- Windows Server 2012 : DHCP,IPv6 and IPAM - Exploring DHCP (part 2) - Installing DHCP Server and Server Tools
- Windows Server 2012 : DHCP,IPv6 and IPAM - Exploring DHCP (part 1)
- Windows Server 2012 : DHCP,IPv6 and IPAM - Understanding the Components of an Enterprise Network
- Microsoft OneNote 2010 : Using the Research and Translate Tools (part 3) - Translating Text with the Mini Translator
- Microsoft OneNote 2010 : Using the Research and Translate Tools (part 2) - Translating a Word or Phrase with the Research Pane
- Microsoft OneNote 2010 : Using the Research and Translate Tools (part 1) - Setting Options for the Research Task Pane, Searching with the Research Task Pane
- Microsoft OneNote 2010 : Doing Research with Linked Notes (part 2) - Ending a Linked Notes Session, Viewing Linked Notes
- Microsoft OneNote 2010 : Doing Research with Linked Notes (part 1) - Beginning a Linked Notes Session
- Microsoft OneNote 2010 : Doing Research with Side Notes (part 3) - Moving Side Notes to Your Existing Notes
 
 
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
2015 Camaro