Aidan Garnish
MOSS 2007 and other Microsoft technologies

Using centrally managed SharePoint data connection files with InfoPath 2007

November 3, 2008 11:06 by Aidan

When deploying InfoPath forms with data connections between environments it is possible to use centrally managed data connection files to make the process a bit smoother.

To set up a centrally managed data connection do the following:

  • From your InfoPath form select Data Connections... from the Data menu
  • Select the data connection you want to make centrally managed and click the Convert button
  • A .udcx file will be created in a site collection data connections library you select so it may be necessary to set up a data connections library first
  • Navigate to the site collection data connections library and save the .udcx file locally
  • Go to SharePoint Central Administration - Application Management - Manage Data Connection Files
  • Upload the .udcx file to the central data connection files library
  • Go back to the InfoPath form and remove the existing data connections.
  • Recreate the data connections using Search for connections on a Microsoft Office SharePoint Server
  • Create the connection using the .udcx file that was saved to the site collection data connection library but make sure that you click on Connection Options... and select Centrally Managed
  • Configure the controls on the form to use the data connection as normal

The form will now use the centrally managed data connection. To deploy to another environment (eg. UAT, Production) you will need to upload the .udcx file to the relevant SharePoint Central Administraion after altering it to use the connection properties relevant to the new environment. To update the .udcx file open it in a text editor and alter the following parameters (example is for a connection to a SharePoint list):

   <udc:ListId>{175EC1CF-BF41-4848-B775-40277642B99F}</udc:ListId>
   <udc:WebUrl>https://productionurl.co.uk/</udc:WebUrl>

Where ListId is the SharePoint list id and WebUrl is the url of the site collection that holds the SharePoint list.

When you deploy your InfoPath form it will reference the centrally managed .udcx file allowing it to seamlessly connect with data in the new environment.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Generic CSV or SQL data importer for SharePoint list

September 9, 2008 17:01 by Aidan

I finally got bored of rewriting the same console application to move data from a csv or a sql table into a SharePoint list! The result is a generic console application that is capable of importing either a CSV file or some SQL data from a stored procedure. The app uses the object model so it needs to be run on the SharePoint server farm. I may get round to rewriting it using web services at some point. The CSV import parses the file so that things like line breaks and commas within fields are handled nicely. Any blank fields in the CSV do need to be filled using find and replace on blank space otherwise data ends up in the wrong columns.

To import a CSV the first row of the of the CSV file is used to define which columns the data will import to. Eg. A CSV that has one column with a header of Title will import the data into the Title column of the specified list. Modify the App.Config file to include the URL of your site collection, the list name, the path to the CSV and whether or not you want to delete all items in the list before importing.

To import SQL data create a stored procedure that returns the data as the names of the site columns

Eg. Select Name AS Title from tblPerson - will return one column of data that will import into the Title column of a list. Modify the App.Config to include the name of the stored procedure and the SQL connection string and run the app.

You can download the project from the following link:

AG.GenericSharePointListImporter.zip (41.72 kb)

This application is supplied as is and offers no guarantees feel free to use as you wish all I ask is that if you make any improvements then you share them in the comments or by email.

Technorati Profile

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Creating an InfoPath installer file with Visual Studio 2008

August 13, 2008 08:58 by Aidan

Having created an InfoPath form project using Visual Studio 2008 and adding some code behind to the form I wanted to deploy it to SharePoint. The easiest way to do this should have been to use the publishing wizard to create an installer file. However, there seems to be a bug in Visual Studio 2008 that prevents you from selecting this option in the wizard. The message displayed is that you need VS 2003 or 2005 installed to create the installer file.

There is a way around this by using the REGFORM.exe tool found in C:\Program Files\Microsoft Office\Office12. The tool allows you to create a .js file that marks the .xsn as fully trusted so that it can be added to the managed forms collection on your MOSS farm.

First you need to go to VS and the Publish option in the Build menu. Instead of selecting the create installer option publish to a network location and create the .xsn on your file system.

Next, open up a command prompt and navigate to C:\Program Files\Microsoft Office\Office12\regform.exe.

Supply the necessary parameters - these are, the /U the URN for the form which can be found in VS, File - Form Properties - ID, /T Yes to mark the form as fully trusted (this is necessary to deploy it to SharePoint) and finally the path to the .xsn file.

You should end up with something like - regform.exe /U urn:schemas-microsoft-com:office:infopath:MyForm:-myXSD-2008-08-07T13-36-16 /T Yes C:\Forms\MyForm

Running the command will create a .bak file and a .js file in the same folder as the .xsn. Run the .js file and then open SharePoint central administration. Go to the Applications tab and under the InfoPath forms services section select Manage Form Templates.

This Microsoft article explains the rest of the process to make the form available in a site collection in detail

If you run the .js in your development environment you will need to unregister the form before you will be able to open it again from Visual Studio. To do this open the .js file in Notepad and change var fInstall = true; to var fInstall = false; - Run the .js file again and this time the message prompts will tell you the form is being unregistered. You can now run the form from Visual Studio again.


Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Creating MOSS 2007 features - a reference

May 20, 2008 10:03 by Aidan

Some useful links for creating MOSS 2007 features that I have found helpful:

Creating Features

Deploying Features

Removing Features


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: MOSS 2007
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Retrieving items from a MOSS 2007 list using web services

April 15, 2008 13:32 by aidan

A quick code snippet to remind me how to access a list using the in built web services: 

                MOSSWebRef.Lists lists = new MOSSWebRef.Lists();
               
                lists.Credentials = new System.Net.NetworkCredential("username", "password");

                string exportList = "NameOfList";

                XmlNode node = lists.GetListItems(
                    exportList,                   
                    string.Empty,
                    null,
                    null,
                    ConfigurationManager.AppSettings["MaxRecords"].ToString(),
                    null);

                XmlTextReader xr = new XmlTextReader(node.OuterXml, XmlNodeType.Element, null);          
                string strValue = "";
                while (xr.Read())
                {
                    if (xr.ReadToFollowing("z:row"))
                    {
                         if (xr["ows_nodeName"] != null)
                        {
                           strValue = xr["ows_nodeName"].ToString();
                        }

                    }

               }


Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: MOSS 2007
Actions: E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Assigning url and description to a hyperlink column

January 22, 2008 15:39 by aidan

item["HyperlinkColumn"] = strUrl + ", " + strDescription;

It is important that there is a space between the comma and the description.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: MOSS 2007
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Space in column names

January 22, 2008 13:50 by aidan

When referencing columns programatically or in CAML that have a space in the name replace the spaces with _x0020_

For example "End Use" becomes "End_x0020_Use"

The format required to access non-alphanumeric column titles is this (IN LOWER CASE):

_x00[the hex code]_

Here are a few more examples:

Char         Code 

[space]      20      i.e. _x0020_
<            3C      i.e. _x003c_
>            3E
#            23
%            25
{            7B
}            7D
|            7C
\            5C
^            5E
~            7E
[            5B
]            5D
`            60
;            3B
/            2F
?            3F
:            3A
@            40
=            3D
&            26
$            24

To reference a column called “e-mail” you would need e_x002d_mail.

This page has a list of all the Hex Codes of some other symbols:http://www.asciitable.com/

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: MOSS 2007
Actions: E-mail | Permalink | Comments (4) | Comment RSSRSS comment feed

Hit enter, fire a web part event the easy way

January 11, 2008 10:33 by aidan

I have a custom web part search box that has a button next to it that directs the user to the search results page for the query that has been entered. What I also want to do is have that same code fire when the user presses enter. With the asp:textbox control this didn't look as if it was going to be very simple as the text changed event does not fire on every key press. Instead it fires when the control loses focus. 

There are a few solutions suggested on the web that use javascript that attach a javascript method to the onkeypress event of the textbox but I wanted to try and avoid adding more javascript to my page.

Fortunately pressing enter causes the control to lose focus so it turns out that it is simple as calling the executequery method in the text changed event like this:

 void txtSearch_TextChanged(object sender, EventArgs e)
        {
              btnExecuteQuery_OnClick(this, e);
        }

Now, whenever a user hits enter the execute query event fires. Testing shows that clicking away from the textbox on a link or tabbing away from the textbox do not fire the event. Result!


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: MOSS 2007
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Downloading and uploading documents to SharePoint with metadata

January 8, 2008 10:42 by aidan

I need to copy some documents from a SharePoint 2003 server to a MOSS 2007 server to make them available on our Internet sites. This is quite easily achieved using the object model but what I also need is to move the metadata associated with the document so I can filter correctly on the Internet site.

To do this I have started by creating a couple of methods. One to download the document from SharePoint to a file system folder and create an xml document that contains the metadata in the same folder. The second method uploads the document with it the metadata to a destination SharePoint document library.

private void DownloadDocumentFromLibrary()
  {
   try
   {
    //get site
    SPSite oSite = new SPSite("http://Localhost");
    
    using(oSite)
    {
     //get the rootSite
     SPWeb oWeb = oSite.RootWeb;
    
     SPList oList = oWeb.Lists["Shared Documents"];

     foreach(SPListItem oItem in oList.Items)
     {
      //get meta-data for the item
      string strXML = oItem.Xml.ToString();
      TextWriter tw = new StreamWriter("c:\\MyDownloadFolder\\"+oItem["Name"]+".xml");
      //write xml to file
      tw.WriteLine(strXML);
      tw.Close();

      //get document
      byte[] binFile = oItem.File.OpenBinary();
      System.IO.FileStream fstream = System.IO.File.Create("c:\\MyDownloadFolder\\" + oItem["Name"]); 
      
      //write document to folder
      fstream.Write(binFile, 0, binFile.Length);
     } 
    }
   }
   catch(Exception err)
   {
    Console.WriteLine(err.Message);
   }
  }

The second method then takes the downloaded files and uploads them to the Internet server document library. You may need to find a way to physically move the files across the network using FTP or something similar depending on where your Internet server is and what security surrounds it.

private void UploadDocumentFromFileShare()
  {  
   try
   {
    //get site
    SPSite oSite = new SPSite("
http://Localhost");

    // Process the list of files found in the directory.
    string [] fileEntries = Directory.GetFiles(@"c:\mydownloadfolder");
    foreach(string fileName in fileEntries)
    {
     //check file type to see if it is an xml document
     int iFileNameLength = fileName.Length;
     string strFileExtension = fileName.Substring(iFileNameLength-4,4);
    
     if(strFileExtension != ".xml")
     {
      //Load the local file into a stream
      FileStream stream = File.OpenRead(fileName);
      byte[] content = new byte[stream.Length];
 
      //Read the file into a byte array
      stream.Read(content,0,(int)stream.Length);
      stream.Close();

      using(oSite)
      {
       //Get the rootSite
       SPWeb oWeb = oSite.RootWeb;
       //Get the folder that should store the document
       SPFolder folder = oWeb.Folders["upload"];

       string[] strSplitFileName = fileName.Split('\\');
       string strFileName = strSplitFileName[strSplitFileName.Length-1];
       //add document to library
       folder.Files.Add(folder.Url + "/" + strFileName, content,true);
 
       //get list
       SPList oList = oWeb.Lists["upload"];
       //create query to get added document item
       SPQuery oQuery = new SPQuery();
       oQuery.Query = "<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='File'>"+strFileName+"</Value></Eq></Where>";
   
       SPListItemCollection oItems = oList.GetItems(oQuery);

       //get xml for document properties
       XmlTextReader reader = new XmlTextReader(fileName+".xml");
    
       XmlDocument doc = new XmlDocument();
       doc.Load(reader);
       XmlElement root = doc.DocumentElement;
       XmlNode node = root.Attributes.GetNamedItem("ows_Column1");
       string strColumn1= node.Value.ToString();

       foreach(SPListItem oItem in oItems)
       {
        string strTitle = "";
        strTitle = strFileName.Substring(0,strFileName.Length-4);
        oItem["Title"] = strTitle;
        oItem["Column1"] = strColumn1;

        oItem.Update();
       }
      }
     } 
    }
   }
   catch(Exception err)
   {
    Console.WriteLine(err.Message);
   }
  }

It is also possible to download attachments from an item using the following code:

 private void DownloadAttachmentFromItem()
  {
   //download attachment from a list to file system
   SPWeb web = new SPSite("
http://localhost").OpenWeb();
   
   //Open List
   SPList list = web.Lists["Doc List"];
      
   foreach(SPListItem oItem in list.Items)
   {
    //get meta-data for the item
    string strXML = oItem.Xml.ToString();
    TextWriter tw = new StreamWriter("c:\\MyDownloadFolder\\"+oItem["Title"]+".xml");
    tw.WriteLine(strXML);
    tw.Close();

    //Get the folder
    SPFolder folder = web.Folders["Lists"].SubFolders["Doc List"].SubFolders["Attachments"].SubFolders[oItem.ID.ToString()];
    //download attachment
    foreach(SPFile oFile in folder.Files)
    {
     byte[] binaryFile = oFile.OpenBinary();
     System.IO.FileStream fstream = System.IO.File.Create("c:\\MyDownloadFolder\\" + oItem["Title"]); 
     fstream.Write(binaryFile, 0, binaryFile.Length);
    }
   }
  }


Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: MOSS 2007
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Web part custom property - dropdown list

December 19, 2007 09:40 by aidan

It isn't immediately obvious how to include a drop down list as a custom property on a web part. To do this you simply use an enum.

Eg.

//create enum

public enum ProductByEnum

{Type = 0,

Brand,

Chemistry};

//create get/set for the property

protected ProductByEnum productsBy;

[Personalizable(PersonalizationScope.User),WebBrowsable, WebDisplayName("Products By"),WebDescription("Use this property to change web part grouping")]public ProductByEnum ProductsBy

{

get { return productsBy; }

set { productsBy = value; }

}

A dropdown list will now appear in the miscellaneous section of your web part custom properties containing the enum values.


Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5