Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Query in c#

Posted on by 12,070 Super User 2024 Season 1

Hi all,

I need to make this query in c#

select CreatedOn, * from Lead
where CreatedOn between '2017-01-31T00:00:00.000' AND '2017-08-31T00:00:00.000'
and OwnerIdName = 'Abdul Wahab'

 

I wrote the following code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query; //QueryExpression
using System.ServiceModel.Description;

namespace ConnectionWithCRM
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("XXXXXXXXX", "XXXXX", "XXXXXXXXXXXXXXXXXXXX");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
if (userid != Guid.Empty)
{
//Console.WriteLine("Connection Established Successfully");
//Console.ReadKey();
EntityCollection ec = null;
string Id = Data.id.ToString();
ec = GetEntityCollection(service, EntityName.Template, TemplateAttributes.Id, Id, new ColumnSet(TemplateAttributes.Id));
if (ec.Entities.Count == 0) //Check for EntityCollection count
{

Entity Entity = new Entity(EntityName.Template);
Entity[TemplateAttributes.Id] = Id;
Entity[TemplateAttributes.Name] = Data.name;
service.Create(Entity);
}
}
}
public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}
private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}
}
}

I am stuck on this condition logic. How do I make conditions as my sql query have, using this code.?

 

Thank You

 

*This post is locked for comments

  • Suggested answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,397 on at
    RE: Query in c#

    Hi

    When using date fields you may have to convert from UTC, accordingly.

    develop1.net/.../Dynamics-CRM-DateTimes-the-last-word.aspx

    Check for similar articles.

  • Abdul Wahab Profile Picture
    Abdul Wahab 12,070 Super User 2024 Season 1 on at
    RE: Query in c#

    Hi Gopalan

    Thank You very much

  • Verified answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,397 on at
    RE: Query in c#

    Hope this would help you, after testing it successfully, replace the hard coded values with parameters:

    cols = new ColumnSet("createdon", "subject", "lastname" );

               entityName = "lead";

               QueryExpression query = new QueryExpression

               {

                   EntityName = entityName,

                   ColumnSet = cols,

                   Criteria = new FilterExpression

                   {

                       FilterOperator = LogicalOperator.And,

                       Conditions =

                           {

                               new ConditionExpression

                               (

                                   "createdon",

                               ConditionOperator.OnOrAfter,

                              "2017-01-31"

                               ),

                               new ConditionExpression

                               (

                                  "createdon",

                               ConditionOperator.OnOrBefore,

                               "2017-08-31"

                               )

                           }

                   }

                   ,

                   LinkEntities =

                   {

                   new LinkEntity("lead", "systemuser", "ownerid", "systemuserid", JoinOperator.Inner)

                   {

                       LinkCriteria =

                       {

                           Conditions =

                           {

                               new ConditionExpression("firstname", ConditionOperator.BeginsWith, "Abdul")

                           }

                       }

                   }

                   }

               };

               EntityCollection  entCol = service.RetrieveMultiple(query);

               return entCol;

  • Suggested answer
    Dynamics_Alok Profile Picture
    Dynamics_Alok 1,746 on at
    RE: Query in c#

    Criteria is not too completed .Set FilterExpresssion as AND and add Conditions for all attributes .For CreatedOn ,you can filter record by createdon ,greater than 2017-01-31T00:00:00.000 and other conditional expression for createdon ,less than 2017-08-31T00:00:00.000 .

  • Suggested answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Query in c#

    Here is the sample query using condition and filter expression. Please modify your code accordingly.

    //  Query using ConditionExpression and FilterExpression

    ConditionExpression condition1 = new ConditionExpression();

    condition1.AttributeName = "lastname";

    condition1.Operator = ConditionOperator.Equal;

    condition1.Values.Add("Brown");            

    FilterExpression filter1 = new FilterExpression();

    filter1.Conditions.Add(condition1);

    QueryExpression query = new QueryExpression("contact");

    query.ColumnSet.AddColumns("firstname", "lastname");

    query.Criteria.AddFilter(filter1);

    EntityCollection result1 = _serviceProxy.RetrieveMultiple(query);

    Console.WriteLine();Console.WriteLine("Query using Query Expression with ConditionExpression and FilterExpression");

    Console.WriteLine("---------------------------------------");

    foreach (var a in result1.Entities)

    {

       Console.WriteLine("Name: " + a.Attributes["firstname"] + " " + a.Attributes["lastname"]);

    }

    Console.WriteLine("---------------------------------------");

    for more details: msdn.microsoft.com/.../gg334688.aspx

    Note: Please mark as accepted answer, if the above answer is useful for you.

  • Suggested answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,397 on at
    RE: Query in c#

    It is not just that condition only.

    Hope, you know all the other items to be modified in this code?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,269 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,198 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans