Wednesday, April 8, 2009

How to import data from AD to InfoPath 2007 Form Template




MOSS has a great new feature that allows (among other things) the publication of InfoPath forms to the server and thus enabling users that do not have InfoPath installed to fill in forms without having to distribute or purchase InfoPath for each client.

One of the things everyone who has asked me about this have in common is that they all work in a Microsoft Active Directory environment and they all want their form to load Meta data from the current user and populate their form with that data.

Now, InfoPath and AD do not have a method for creating a direct connection, but since all of our users also utilize the Microsoft Office SharePoint Server (MOSS) forms server they can take advantage of other features and capabilities of MOSS to solve this problem.

MOSS connects to your AD easily and builds a user profile based on the data stored in AD for each user. This part is easy enough to perform so I will not elaborate further on that here.


Once your MOSS “recognizes” your users, you can make use of its web services to retrieve all users list, a specific user profile and also the current user profile.


Here I will demonstrate how to create a form that loads current user profile data as stored in AD without writing a bit of code.

The only thing that needs to be done is to define a connection to a certain web service that already exists in your SharePoint site out-of-the-box (OOTB).


Step 1: Create a blank form template

1. Click file->design a form template

2. Select “Blank”


3. Click OK



Step 2: Setting up the web service connection

1. Create a new data source connection.

Go to tools –>Data connection



2. In the "Data connections” dialog Click on Add



3. Select create a new connection to - Receive data Click next



4. Select Web service as the source type



5. Insert the Following web service name: http:///_vti_bin/userprofileservice.asmx?wsdl


6. Replace <servername> with your SharePoint server name and click next


7. From the operations drop down list select GetUserProfileByName



8. In MOSS, calling this operation without sending a user name will return current user’s profile.

9. Click "next" keeping the defaults in every screen until you can hit Finish





10. Close the Data connection window.



Step 3: Viewing and choosing the AD details we wish to import:

Now, we need to insert the AD information to the correct fields. To do so, we first need to see what kind of data we can use.


Since the users profile may include different properties according to your organizations' software and other dependencies, the web service results returns a set of “name-value” collection that we can use in order to get the results we need.
So – first, we have to find the “name” of the property and then we'll use it to get its value from the web service.

Here is how it is done:

1. To see all the available fields click on View -> Data source


2. In the Data source drop-down select the one we just created.


3. Expand the DataFields container node and select the following fields in the results:


4. In the drop-down menu on the selected nodes select "repeating table" and place it in the form.

5. You now have a repeating table with all data returned by the web service. To see all the AD fields available to you, Click "preview" in the tool bar.


6. Now, locate the property you need and copy its name


7. Return to the design mode by clicking "close preview".

Step 4: placing the AD details in the controls:

Now the only thing left for us to do is place the field we chose earlier (in step 3) and define the control to show that field’s info.


1. In the form, double-click the control you wish to fill

2. In the control properties click on to open the function editor



3. Then click on "Insert Field or Group".


4. In the next window, select the data source you created


5. Expand all the folders under "DataFields" until you can see and then select the "Value" node.

6. This inserts one of the “values” we got in the web service response. Now we need to enable it to “filter” the values by the property name we want. To do so:


7. Click on "Filter Data" button. In the pop up window click "Add"


8. In the next window select the following options


9. And select the “Name” node from our service data source:



10. Click "Ok". Then Select "Type Text" and enter the property you copied in the previous section as the value


11.Click "Ok" to confirm and close all the pop-ups.


12. Click "Preview" in the tool bar to see the results.



Now your form displays the user preferred name as it was entered in the AD and all that without writing a single line of code!

Important:
Your document must be fully trusted in order to execute the web service correctly. To do make sure they are, please check the "Tools-Forms Options" form security options.

This is a great demonstration how you can combine several Microsoft products to create excellent customer-specific solutions utilizing the out of the box features and capabilities, with no need for any extras!

Thursday, March 26, 2009

SharePoint Best Practices For Begginers

SPSiteDataQuery Class
Imagine a scenario in which you want to run a single query against every list in the current site collection that has been created from the Announcements list type and return all list items that were created today. The following code sample demonstrates how to do this by creating an SPSiteDataQuery object, initializing it with the necessary CAML statements, and then passing it to the current SPWeb object’s GetSiteData method.

SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = @"";
query.ViewFields = @"";
query.Webs = "";

string queryText = @" ";


query.Query = queryText;

DataTable table = site.GetSiteData(query);

foreach (DataRow row in table.Rows) {
Console.WriteLine(row["Title"].ToString());
}



Using SPQuery to query specific items in the list

To get back specific results within a list, you can use the SPQuery object. When you use an SPQuery object, you will create CAML statements to select specific data within the target list. To select announcements that have expired, you may want to use a query built with CAML statements, as shown in the following example:

SPQuery query = new SPQuery();
query.ViewFields = @"";
query.Query =
@"
";

SPList list = site.Lists["Litware News"];
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem expiredItem in items) {
Console.WriteLine(expiredItem["Title"]);
}
You must specify the fields you want returned in the query by using the ViewFields property. Also note that you must specify the fields in terms of the field Name, and not DisplayName. If you attempt to access fields without specifying them in ViewFields, you will experience an exception of type ArgumentException

Enumerating thought the Fields excluding Hidden and read only fields
foreach (SPListItem item in list.Items) {
foreach (SPField field in list.Fields) {
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine("{0} = {1}", field.Title, item[field.Id]);
}
}
foreach (SPListItem item in list.Items) {
foreach (SPField field in list.Fields) {
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine("{0} = {1}", field.Title, item[field.Id]);
}
}
Checking if the List Exists and Adding a new list if it does not Exists

using System;
using Microsoft.SharePoint;

class Program {
static void Main() {
using (SPSite site = new SPSite("http://localhost")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "Litware News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;
break;
}
}

if (list == null) {
Guid listID = web.Lists.Add(listName,
"List for big news items",
SPListTemplateType.Announcements);
list = web.Lists[listID];
list.OnQuickLaunch = true;
list.Update();
}
}
}
}
}

Check if list is of the type Document Library or Not

public bool CkechIfListisDocLib(SPList list) {
if (list is SPDocumentLibrary)
return true;
else
return false;
}

Running a Code with Elevated Permissions

Use this in ur code. if u want to run a portion of the code with elevated permissions


SPSecurity.RunWithElevatedPrivileges(delegate()
{
// do something
});

Download a file from Document Library and Save it locally

private static void DownloadAFile()
{
SPSite site = new SPSite("http://wwdevserver:3000/"); //site url

SPWeb web = site.OpenWeb(@"/Admin"); //web url

SPList list = web.Lists["PDF Form Templates"]; //list name



File.WriteAllBytes(@"c:\m.pdf", list.Items[0].File.OpenBinary()); //downloading first items file

}

SPWebConfigModification Class - Editing Sharepoint Web.Config

I have seen some of the code where in if a "SafeControl" entry is need to be done in the web.config, through code, then we use
"XMLDocument" class to load the web.config and make changes . there is trouble in doing so as you need to manually get the path of the web.config and all.

But Sharepoint object model provides a class called "SPWebConfigModification" which can be used to play around with the web.config of the site.

Sample Code where in --Safe Control Entry is Made for the Webparts in the feature activation



public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = (SPSite)properties.Feature.Parent;

if (site != null)
{
SPWebApplication webApp = site.WebApplication;

SPWebConfigModification ModDesc = new SPWebConfigModification();
ModDesc.Path = "configuration/SharePoint/SafeControls";
ModDesc.Name = "SafeControl[@Assembly='Description'][@Namespace='Description'][@TypeName='*'][@Safe='True'] [@AllowRemoteDesigner='True']";
ModDesc.Sequence = 0;
ModDesc.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
ModDesc.Value = "";


webApp.WebConfigModifications.Add(ModDesc);

webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
webApp.Update();

}