Saturday 2 December 2017

C# Code to Retrieve System and Custom Views from Dynamics 365 (Version 9.0)

There are times we write utilities to retrieve CRM data/information using C#. My favorite is a .NET console application which I always create for my projects. In this console app I dump useful code snippets which makes my work very productive.

In this blog I will provide C# code to retrieve System and Custom views.

Code:

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Configuration;
using System.Linq;
using System.ServiceModel;

namespace ConsoleUtilities
{
    class GetViews
    {
        public static void Main(string[] args)
        {
            try
            {
                CrmServiceClient crmConn = new
                    CrmServiceClient(ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString);

                IOrganizationService crmService = crmConn.OrganizationServiceProxy;

                OrganizationServiceContext orgContext = new OrganizationServiceContext(crmService);

                var objCRMViews = from crmView in orgContext.CreateQuery("savedquery")
                                  select new
                                  {
                                      savedQuery_SavedQueryId = crmView["savedqueryid"],
                                      savedQuery_Name = crmView["name"]
                                  };

                foreach (var localObjCRMViews in objCRMViews)
                {
                    System.Console.WriteLine("savedQuery_savedqueryid: "
                        + localObjCRMViews.savedQuery_SavedQueryId.ToString());
                    System.Console.WriteLine("savedQuery_name: "
                        + localObjCRMViews.savedQuery_Name.ToString());
                    System.Console.WriteLine();
                }

                // exit
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                string message = ex.Message;
                throw;
            }
        }
    }
}

Explanation:

1) Use the following types in a namespace.

"using" Directive - Namespace

2) Connect to Dynamics 365 V 9.0 online or on premise. Write a LINQ query to retrieve all views. Loop through and display all the views. At the end exit the console app.

LINQ Query to Retrieve All Views

You can also add a "Where" clause to the LINQ query to retrieve only one view. In my case I have added the where clause to retrieve a view named "Payments with No Taxes".

LINQ Query to Retrieve One View

3) Add Try/Catch to handle any exceptions.

Try/Catch
You can use this utility to get a list of all views or get information on just one view. This is useful when developing and customizing a CRM application.

No comments:

Post a Comment