Monday, June 15, 2009

Using Embedded Files for FetchXML Queries

FetchXML is a proprietary language that it is used in Microsoft Dynamics CRM. All examples that I've seen so far, always show the FetchXML query hard coded into the C# file. Instead of keeping the queries mixed with the source code, a bad practice IMHO, I prefer placing queries in separate XML files. These files can be embedded resources of the assembly. By placing them on a separate file, it isolates them from the code, making easier to locate, share and test them. In order to embed your query in the assembly, you will need to add an XML file with the query into your project. Make sure to change its build action to Embedded Resource. Then, use the following code to read the embedded XML file. The code below assumes that the file was placed in the subfolder Queries of the project. It refers to the embedded file by using the assembly name and the related path to the file. Notice that it uses "." instead of "\" to refer to the embedded file.

// Read the embedded fetch xml query file.
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream("MyAssembly.Queries.MyQuery.xml");

if (stream == null)
    throw new FileLoadException("Cannot load fetchXML embedded file");

// Gets the Fetch XML query string.
var reader = new StreamReader(stream);
string query = reader.ReadToEnd();

// Removing leading spaces to reduce the size of the xml request.
query = Regex.Replace(fetchXml, @"\s+", @" ");

// Fetches the results.
string results = crmService.Fetch(query);

The code above uses a static query. If you need to use a dynamic query, then the XML can contain the string format of the query, and you can use String.Format to pass the parameters needed to build your dynamic query.

No comments: