<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Can I use FetchXML with a paging cookie (C#) to import data to power bi desktop? in Developer</title>
    <link>https://community.fabric.microsoft.com/t5/Developer/Can-I-use-FetchXML-with-a-paging-cookie-C-to-import-data-to/m-p/164640#M5503</link>
    <description>&lt;P&gt;Too bad &lt;SPAN&gt;Power BI desktop doesn't support using C# code to retrieve data&lt;/SPAN&gt;.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Yes, Dynamics 365 online, but I am not sure where the limitation is coming from. &amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;A href="https://msdn.microsoft.com/en-us/library/gg328046.aspx" target="_blank"&gt;https://msdn.microsoft.com/en-us/library/gg328046.aspx&lt;/A&gt;&lt;/P&gt;</description>
    <pubDate>Wed, 26 Apr 2017 03:55:54 GMT</pubDate>
    <dc:creator>hxkresl</dc:creator>
    <dc:date>2017-04-26T03:55:54Z</dc:date>
    <item>
      <title>Can I use FetchXML with a paging cookie (C#) to import data to power bi desktop?</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/Can-I-use-FetchXML-with-a-paging-cookie-C-to-import-data-to/m-p/163684#M5475</link>
      <description>&lt;P&gt;Because there is a 5000 record limit when using fetchXML to retrieve&amp;nbsp;datasets from CRM into Power BI Desktop&amp;nbsp;I am faced with need to use 'a paging cookie" (C# code&amp;nbsp;to overcome 5000 record limit and return complete dataset)&lt;/P&gt;&lt;P&gt;Assuming I can get a developer to write the C# code, &lt;STRONG&gt;which Power BI Desktop&amp;nbsp;Get Data option would I use if I wished to use code, such sample code below?&lt;/STRONG&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;PRE&gt;using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;

// These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
// found in the SDK\bin folder.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;

// This namespace is found in Microsoft.Crm.Sdk.Proxy.dll assembly
// found in the SDK\bin folder.
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Messages;


namespace Microsoft.Crm.Sdk.Samples
{
    /// &amp;lt;summary&amp;gt;
    /// Demonstrates how to use the Fetch XML method with a paging
    /// cookie to retrieve a batch of records.
    /// If you want to run this sample repeatedly, you have the option to 
    /// delete all the records created at the end of execution.
    /// &amp;lt;/summary&amp;gt;
    class FetchPagingWithCookie
    {
        #region Class Level Members

        /// &amp;lt;summary&amp;gt;
        /// Stores the organization service proxy.
        /// &amp;lt;/summary&amp;gt;
        private OrganizationServiceProxy _serviceProxy;
        private IOrganizationService _service;

        // Define the IDs needed for this sample.
        public Guid _parentAccountId;
        public Guid[] _childAccountIds;

        #endregion Class Level Members

        #region How To Sample Code
        /// &amp;lt;summary&amp;gt;
        /// Create and configure the organization service proxy.
        /// Create a parent account record and subsequent 10 child account records.
        /// Retrieve batch of records using RetrieveMultiple message with paging cookie.
        /// Optionally delete any entity records that were created for this sample.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name="serverConfig"&amp;gt;Contains server connection information.&amp;lt;/param&amp;gt;
        /// &amp;lt;param name="promptForDelete"&amp;gt;When True, the user will be prompted to delete all
        /// created entities.&amp;lt;/param&amp;gt;
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    // Define the fetch attributes.
                    // Set the number of records per page to retrieve.
                    int fetchCount = 3;
                    // Initialize the page number.
                    int pageNumber = 1;
                    // Initialize the number of records.
                    int recordCount = 0;
                    // Specify the current paging cookie. For retrieving the first page, 
                    // pagingCookie should be null.
                    string pagingCookie = null;

                    // Create the FetchXml string for retrieving all child accounts to a parent account.
                    // This fetch query is using 1 placeholder to specify the parent account id 
                    // for filtering out required accounts. Filter query is optional.
                    // Fetch query also includes optional order criteria that, in this case, is used 
                    // to order the results in ascending order on the name data column.
                    string fetchXml = string.Format(@"&amp;lt;fetch version='1.0' 
                                                    mapping='logical' 
                                                    output-format='xml-platform'&amp;gt;
                                                    &amp;lt;entity name='account'&amp;gt;
                                                        &amp;lt;attribute name='name' /&amp;gt;
                                                        &amp;lt;attribute name='emailaddress1' /&amp;gt;
                                                        &amp;lt;order attribute='name' descending='false'/&amp;gt;
                                                        &amp;lt;filter type='and'&amp;gt;
				                                            &amp;lt;condition attribute='parentaccountid' 
                                                                operator='eq' value='{0}' uiname='' uitype='' /&amp;gt;
                                                        &amp;lt;/filter&amp;gt;
                                                    &amp;lt;/entity&amp;gt;
                                                &amp;lt;/fetch&amp;gt;",
                                                    _parentAccountId);

                    Console.WriteLine("Retrieving data in pages\n"); 
                    Console.WriteLine("#\tAccount Name\t\t\tEmail Address");

                    while (true)
                    {
                        // Build fetchXml string with the placeholders.
                        string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);

                        // Excute the fetch query and get the xml result.
                        RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                        {
                            Query = new FetchExpression(xml)
                        };

                        EntityCollection returnCollection = ((RetrieveMultipleResponse)_service.Execute(fetchRequest1)).EntityCollection;

                        foreach (var c in returnCollection.Entities)
                        {
                            System.Console.WriteLine("{0}.\t{1}\t\t{2}", ++recordCount, c.Attributes["name"], c.Attributes["emailaddress1"] );
                        }                        

                        // Check for morerecords, if it returns 1.
                        if (returnCollection.MoreRecords)
                        {
                            Console.WriteLine("\n****************\nPage number {0}\n****************", pageNumber);
                            Console.WriteLine("#\tAccount Name\t\t\tEmail Address");

                            // Increment the page number to retrieve the next page.
                            pageNumber++;

                            // Set the paging cookie to the paging cookie returned from current results.                            
                            pagingCookie = returnCollection.PagingCookie;
                        }
                        else
                        {
                            // If no more records in the result nodes, exit the loop.
                            break;
                        }
                    }

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException&amp;lt;Microsoft.Xrm.Sdk.OrganizationServiceFault&amp;gt;)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
            return;
        }


        public string ExtractNodeValue(XmlNode parentNode, string name)
        {
            XmlNode childNode = parentNode.SelectSingleNode(name);

            if (null == childNode)
            {
                return null;
            }
            return childNode.InnerText;
        }

        public string ExtractAttribute(XmlDocument doc, string name)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;
            XmlAttribute attr = (XmlAttribute)attrs.GetNamedItem(name);
            if (null == attr)
            {
                return null;
            }
            return attr.Value;
        }

        public string CreateXml(string xml, string cookie, int page, int count)
        {
            StringReader stringReader = new StringReader(xml);
            XmlTextReader reader = new XmlTextReader(stringReader);

            // Load document
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            return CreateXml(doc, cookie, page, count);
        }

        public string CreateXml(XmlDocument doc, string cookie, int page, int count)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

            if (cookie != null)
            {
                XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
                pagingAttr.Value = cookie;
                attrs.Append(pagingAttr);
            }

            XmlAttribute pageAttr = doc.CreateAttribute("page");
            pageAttr.Value = System.Convert.ToString(page);
            attrs.Append(pageAttr);

            XmlAttribute countAttr = doc.CreateAttribute("count");
            countAttr.Value = System.Convert.ToString(count);
            attrs.Append(countAttr);

            StringBuilder sb = new StringBuilder(1024);
            StringWriter stringWriter = new StringWriter(sb);

            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            doc.WriteTo(writer);
            writer.Close();

            return sb.ToString();
        }

        /// &amp;lt;summary&amp;gt;
        /// This method creates any entity records that this sample requires.
        /// Create a parent account record.
        /// Create 10 child accounts to the parent account record.
        /// &amp;lt;/summary&amp;gt;
        public void CreateRequiredRecords()
        {
            // Instantiate a account entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation
            // to determine which attributes must be set for each entity.
            // Create the parent account.
            Account parentAccount = new Account
            {
                Name = "Root Test Account",
                EMailAddress1 = "root@root.com"
            };


            _parentAccountId = _service.Create(parentAccount);

            // Create 10 child accounts.
            _childAccountIds = new Guid[10]; 
            int count = 1;
            while (true)
            {
                Account childAccount = new Account
                {
                    Name = "Child Test Account " + count.ToString(),
                    EMailAddress1 = "child" + count.ToString() + "@root.com",
                    EMailAddress2 = "same@root.com",
                    ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId)
                };

                _childAccountIds[count - 1] = _service.Create(childAccount);

                // Jump out of the loop after creating 10 child accounts.
                if (count == 10)
                    break;
                // Increment the count.
                count++;
            }            
            return;
        }

        /// &amp;lt;summary&amp;gt;
        /// Deletes any entity records that were created for this sample.
        /// &amp;lt;param name="prompt"&amp;gt;Indicates whether to prompt the user to delete the records created in this sample.&amp;lt;/param&amp;gt;
        /// &amp;lt;/summary&amp;gt;
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these entity records deleted? (y/n)");
                String answer = Console.ReadLine();

                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                // Remove the test parent account.
                _service.Delete(Account.EntityLogicalName, _parentAccountId);

                // Remove 10 test child accounts.
                int deleteCount = 0;
                while (deleteCount &amp;lt; 10)
                {
                    _service.Delete(Account.EntityLogicalName, _childAccountIds[deleteCount]);
                    ++deleteCount;
                }

                Console.WriteLine("Entity records have been deleted.");
            }
        }

        #endregion How To Sample Code

        #region Main

        /// &amp;lt;summary&amp;gt;
        /// Standard Main() method used by most SDK samples.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name="args"&amp;gt;&amp;lt;/param&amp;gt;
        static public void Main(string[] args)
        {
            try
            {
                // Obtain the target organization's Web address and client logon 
                // credentials from the user.
                ServerConnection serverConnect = new ServerConnection();
                ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                FetchPagingWithCookie app = new FetchPagingWithCookie();
                app.Run(config, true);
            }
            catch (FaultException&amp;lt;Microsoft.Xrm.Sdk.OrganizationServiceFault&amp;gt; ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                    null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                    null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException&amp;lt;Microsoft.Xrm.Sdk.OrganizationServiceFault&amp;gt; fe = ex.InnerException
                        as FaultException&amp;lt;Microsoft.Xrm.Sdk.OrganizationServiceFault&amp;gt;;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                            null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                Console.WriteLine("Press &amp;lt;Enter&amp;gt; to exit.");
                Console.ReadLine();
            }

        }
        #endregion Main

    }
}&lt;/PRE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;above code sample taken from &lt;A href="https://msdn.microsoft.com/en-us/library/gg328046.aspx" target="_blank"&gt;https://msdn.microsoft.com/en-us/library/gg328046.aspx&amp;nbsp;&lt;/A&gt;&lt;/P&gt;</description>
      <pubDate>Mon, 24 Apr 2017 18:31:18 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/Can-I-use-FetchXML-with-a-paging-cookie-C-to-import-data-to/m-p/163684#M5475</guid>
      <dc:creator>hxkresl</dc:creator>
      <dc:date>2017-04-24T18:31:18Z</dc:date>
    </item>
    <item>
      <title>Re: Can I use FetchXML with a paging cookie (C#) to import data to power bi desktop?</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/Can-I-use-FetchXML-with-a-paging-cookie-C-to-import-data-to/m-p/164538#M5500</link>
      <description>&lt;BLOCKQUOTE&gt;&lt;HR /&gt;&lt;a href="https://community.fabric.microsoft.com/t5/user/viewprofilepage/user-id/16318"&gt;@hxkresl&lt;/a&gt; wrote:&lt;BR /&gt;
&lt;P&gt;Because there is a 5000 record limit when using fetchXML to retrieve&amp;nbsp;datasets from CRM into Power BI Desktop&amp;nbsp;I am faced with need to use 'a paging cookie" (C# code&amp;nbsp;to overcome 5000 record limit and return complete dataset)&lt;/P&gt;
&lt;P&gt;Assuming I can get a developer to write the C# code, &lt;STRONG&gt;which Power BI Desktop&amp;nbsp;Get Data option would I use if I wished to use code, such sample code below?&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;above code sample taken from &lt;A href="https://msdn.microsoft.com/en-us/library/gg328046.aspx" target="_blank"&gt;https://msdn.microsoft.com/en-us/library/gg328046.aspx&amp;nbsp;&lt;/A&gt;&lt;/P&gt;
&lt;HR /&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;&lt;a href="https://community.fabric.microsoft.com/t5/user/viewprofilepage/user-id/16318"&gt;@hxkresl&lt;/a&gt;&lt;/P&gt;
&lt;P&gt;Power BI desktop doesn't support using C# code to feed data. However you can make a console application running in certain interval and save/refresh the data in csv, excel or even in database, then consume data from files or database from Power BI desktop.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;By the way, when saying the limitation, do you mean the "Dynamica 365(online)" connector?&lt;/P&gt;</description>
      <pubDate>Wed, 26 Apr 2017 01:01:17 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/Can-I-use-FetchXML-with-a-paging-cookie-C-to-import-data-to/m-p/164538#M5500</guid>
      <dc:creator>Eric_Zhang</dc:creator>
      <dc:date>2017-04-26T01:01:17Z</dc:date>
    </item>
    <item>
      <title>Re: Can I use FetchXML with a paging cookie (C#) to import data to power bi desktop?</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/Can-I-use-FetchXML-with-a-paging-cookie-C-to-import-data-to/m-p/164640#M5503</link>
      <description>&lt;P&gt;Too bad &lt;SPAN&gt;Power BI desktop doesn't support using C# code to retrieve data&lt;/SPAN&gt;.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Yes, Dynamics 365 online, but I am not sure where the limitation is coming from. &amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;A href="https://msdn.microsoft.com/en-us/library/gg328046.aspx" target="_blank"&gt;https://msdn.microsoft.com/en-us/library/gg328046.aspx&lt;/A&gt;&lt;/P&gt;</description>
      <pubDate>Wed, 26 Apr 2017 03:55:54 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/Can-I-use-FetchXML-with-a-paging-cookie-C-to-import-data-to/m-p/164640#M5503</guid>
      <dc:creator>hxkresl</dc:creator>
      <dc:date>2017-04-26T03:55:54Z</dc:date>
    </item>
  </channel>
</rss>

