public static void SavedQueries(XrmServiceContext svcContext) { QueryExpression mySavedQuery = new QueryExpression { ColumnSet = new ColumnSet("savedqueryid", "name", "querytype", "isdefault", "returnedtypecode", "isquickfindquery"), EntityName = SavedQuery.EntityLogicalName, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "querytype", Operator = ConditionOperator.Equal, Values = {0} }, new ConditionExpression { AttributeName = "returnedtypecode", Operator = ConditionOperator.Equal, Values = {SalesOrder.EntityTypeCode} } } } }; RetrieveMultipleRequest retrieveSavedQueriesRequest = new RetrieveMultipleRequest { Query = mySavedQuery }; RetrieveMultipleResponse retrieveSavedQueriesResponse = (RetrieveMultipleResponse)svcContext.Execute(retrieveSavedQueriesRequest); DataCollection<Entity> savedQueries = retrieveSavedQueriesResponse.EntityCollection.Entities; using (StreamWriter sw = new StreamWriter(crmPath + "SavedQueries.txt")) { //Display the Retrieved views String oo = "Open Orders (Support)"; SavedQuery sq = new SavedQuery(); sw.WriteLine("rsq.SavedQueryId;rsq.Name;rsq.QueryType;rsq.IsDefault;rsq.ReturnedTypeCode;rsq.IsQuickFindQuery"); foreach (Entity ent in savedQueries) { SavedQuery rsq = (SavedQuery)ent; sw.WriteLine("{0};{1};{2};{3};{4};{5}", rsq.SavedQueryId, rsq.Name, rsq.QueryType, rsq.IsDefault, rsq.ReturnedTypeCode, rsq.IsQuickFindQuery); if (rsq.Name.Equals(oo)) sq = rsq; } sw.WriteLine("*****************"); sw.WriteLine("FetchXml: " + sq.FetchXml); sw.WriteLine("ColumnSetXml: " + sq.ColumnSetXml); //sw.WriteLine("CreatedBy: " + sq.CreatedBy.Name); sw.WriteLine("Description: " + sq.Description); sw.WriteLine("QueryAPI: " + sq.QueryAPI); sw.WriteLine("ReturnedTypeCode: " + sq.ReturnedTypeCode); ExecuteByIdSavedQueryRequest executeSavedQueryRequest = new ExecuteByIdSavedQueryRequest() { EntityId = sq.Id }; // Execute the request sw.WriteLine(" Executing Saved Query"); ExecuteByIdSavedQueryResponse executeSavedQueryResponse = (ExecuteByIdSavedQueryResponse)svcContext.Execute(executeSavedQueryRequest); // Check results if (String.IsNullOrEmpty(executeSavedQueryResponse.String)) throw new Exception("Saved Query did not return any results"); sw.WriteLine(executeSavedQueryResponse.String); } }
public static List <Person> GetPeopleFromFetch( OrganizationServiceContext organizationServiceContext, IOrganizationService organizationService, string findName) { // Find the correct Fetch XML var findResults = organizationServiceContext.CreateQuery <SavedView>() .Where(x => x.Name == findName).ToList(); if (findResults.Count() != 1) { throw new Exception( $"Expected exactly one Advanced Find name \"{findName}\", but found {findResults.Count()}"); } SavedView find = findResults.First(); // Create the request ExecuteByIdSavedQueryRequest executeSavedQueryRequest = new ExecuteByIdSavedQueryRequest() { EntityId = find.Id }; // Execute the request var results = organizationService.RetrieveMultiple(new FetchExpression(find.FetchXML)) .ToProxies <Person>(); return(results); }
/// <summary> /// This method first creates a series of Accounts to query over, a user query /// that retrieves the names of all Accounts with a name of 'Coho Winery' and /// a system query that retrieves all Account names. Then it validates the system /// query, executes the system query and displays the results, and finally /// executes the user query and displays the results. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetUserQueryAndSavedQuery1> // 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(); CreateRequiredRecords(); #region Validate saved query // Create the request ValidateSavedQueryRequest validateRequest = new ValidateSavedQueryRequest() { FetchXml = _savedQuery.FetchXml, QueryType = _savedQuery.QueryType.Value }; // Send the request Console.WriteLine(" Validating Saved Query"); try { // executing the request will throw an exception if the fetch xml is invalid var validateResponse = (ValidateSavedQueryResponse)_serviceProxy.Execute(validateRequest); Console.WriteLine(" Saved Query validated successfully"); } catch (Exception) { Console.WriteLine(" Invalid Saved Query"); throw; } #endregion #region Execute saved query // Create the request ExecuteByIdSavedQueryRequest executeSavedQueryRequest = new ExecuteByIdSavedQueryRequest() { EntityId = _savedQuery.Id }; // Execute the request Console.WriteLine(" Executing Saved Query"); ExecuteByIdSavedQueryResponse executeSavedQueryResponse = (ExecuteByIdSavedQueryResponse)_serviceProxy.Execute(executeSavedQueryRequest); // Check results if (String.IsNullOrEmpty(executeSavedQueryResponse.String)) { throw new Exception("Saved Query did not return any results"); } PrintResults(executeSavedQueryResponse.String); #endregion #region Execute user query // Create the request ExecuteByIdUserQueryRequest executeUserQuery = new ExecuteByIdUserQueryRequest() { EntityId = _userQuery.ToEntityReference() }; // Send the request Console.WriteLine(" Executing User Query"); ExecuteByIdUserQueryResponse executeUserQueryResponse = (ExecuteByIdUserQueryResponse)_serviceProxy.Execute(executeUserQuery); if (String.IsNullOrEmpty(executeUserQueryResponse.String)) { throw new Exception("User Query did not return any results"); } // validate results PrintResults(executeUserQueryResponse.String); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetUserQueryAndSavedQuery1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code ////////////////////////////////////////////// #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Create the request var validateRequest = new ValidateSavedQueryRequest() { FetchXml = savedQuery.FetchXml, QueryType = savedQuery.QueryType.Value }; // Send the request Console.WriteLine(" Validating Saved Query"); try { // executing the request will throw an exception if the fetch xml is invalid var validateResponse = (ValidateSavedQueryResponse)service.Execute(validateRequest); Console.WriteLine(" Saved Query validated successfully"); } catch (Exception) { Console.WriteLine(" Invalid Saved Query"); throw; } #endregion #region Execute saved query // Create the request var executeSavedQueryRequest = new ExecuteByIdSavedQueryRequest() { EntityId = savedQuery.Id }; // Execute the request Console.WriteLine(" Executing Saved Query"); var executeSavedQueryResponse = (ExecuteByIdSavedQueryResponse)service.Execute(executeSavedQueryRequest); // Check results if (String.IsNullOrEmpty(executeSavedQueryResponse.String)) { throw new Exception("Saved Query did not return any results"); } PrintResults(service, executeSavedQueryResponse.String); #endregion #region Execute user query // Create the request var executeUserQuery = new ExecuteByIdUserQueryRequest() { EntityId = userQuery.ToEntityReference() }; // Send the request Console.WriteLine(" Executing User Query"); var executeUserQueryResponse = (ExecuteByIdUserQueryResponse)service.Execute(executeUserQuery); if (String.IsNullOrEmpty(executeUserQueryResponse.String)) { throw new Exception("User Query did not return any results"); } // validate results PrintResults(service, executeUserQueryResponse.String); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } #endregion Sample Code catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// This method first creates a series of Accounts to query over, a user query /// that retrieves the names of all Accounts with a name of 'Coho Winery' and /// a system query that retrieves all Account names. Then it validates the system /// query, executes the system query and displays the results, and finally /// executes the user query and displays the results. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetUserQueryAndSavedQuery1> // 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(); CreateRequiredRecords(); #region Validate saved query // Create the request ValidateSavedQueryRequest validateRequest = new ValidateSavedQueryRequest() { FetchXml = _savedQuery.FetchXml, QueryType = _savedQuery.QueryType.Value }; // Send the request Console.WriteLine(" Validating Saved Query"); try { // executing the request will throw an exception if the fetch xml is invalid var validateResponse = (ValidateSavedQueryResponse)_serviceProxy.Execute(validateRequest); Console.WriteLine(" Saved Query validated successfully"); } catch (Exception) { Console.WriteLine(" Invalid Saved Query"); throw; } #endregion #region Execute saved query // Create the request ExecuteByIdSavedQueryRequest executeSavedQueryRequest = new ExecuteByIdSavedQueryRequest() { EntityId = _savedQuery.Id }; // Execute the request Console.WriteLine(" Executing Saved Query"); ExecuteByIdSavedQueryResponse executeSavedQueryResponse = (ExecuteByIdSavedQueryResponse)_serviceProxy.Execute(executeSavedQueryRequest); // Check results if (String.IsNullOrEmpty(executeSavedQueryResponse.String)) throw new Exception("Saved Query did not return any results"); PrintResults(executeSavedQueryResponse.String); #endregion #region Execute user query // Create the request ExecuteByIdUserQueryRequest executeUserQuery = new ExecuteByIdUserQueryRequest() { EntityId = _userQuery.ToEntityReference() }; // Send the request Console.WriteLine(" Executing User Query"); ExecuteByIdUserQueryResponse executeUserQueryResponse = (ExecuteByIdUserQueryResponse)_serviceProxy.Execute(executeUserQuery); if (String.IsNullOrEmpty(executeUserQueryResponse.String)) throw new Exception("User Query did not return any results"); // validate results PrintResults(executeUserQueryResponse.String); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetUserQueryAndSavedQuery1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
private static void getInfoByGUID(XrmServiceContext svcContext) { var request = new ExecuteByIdSavedQueryRequest { EntityId = new Guid("00000000-0000-0000-00AA-000010001002")//Account //EntityId = new Guid("B1605B89-3BFE-E411-B185-6C3BE5A6CB54") //EntityId = new Guid("b053a39a-041a-4356-acef-ddf00182762b")//&id=%7bB1605B89-3BFE-E411-B185-6C3BE5A6CB54%7d&pagetype }; var response = (ExecuteByIdSavedQueryResponse)svcContext.Execute(request); string resultset = response.String; }