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#. A favorite is a .NET console application for projects. In this console app let's dump useful code snippets which make the work very productive.
In this blog, we 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.
https://4.bp.blogspot.com/-pZh1UAIyTIc/WiMcumUfKtI/AAAAAAAABak/HyVkfB_HtlklGp18r5gw3ajrgJxJqU2SgCLcBGAs/s1600/17.PNG |
"using" Directive - Namespace |
2) Connect to Dynamics 365 V 9.0 online or on-premises. Write a LINQ query to retrieve all views. Loop through and display all the views. At the end, exit the console app.
https://3.bp.blogspot.com/-sVKdS7zsL24/WiMcutAxwvI/AAAAAAAABao/RWi3XchbJbc68mqlvGrL_VkkbBnREXzxACEwYBhgL/s640/18.PNG |
LINQ Query to Retrieve All Views |
You can also add a "Where" clause to the LINQ query to retrieve only one view. In this case, we have added the where clause to retrieve a view named "Payments with No Taxes".
https://4.bp.blogspot.com/-3F3imybVB_k/WiMcuhIcKcI/AAAAAAAABag/qMR9qhFYYmM9iKthvaurrQnlsdjF0yFJACEwYBhgL/s1600/19.PNG |
LINQ Query to Retrieve One View |
3) Add Try/Catch to handle any exceptions.
https://1.bp.blogspot.com/-vrpRY1wAMOg/WiMcvZx3BCI/AAAAAAAABaw/BrQCD1pfTQ4bAr5rqLp0qT9hBZVCRNykACEwYBhgL/s1600/20.PNG |
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.