Wednesday, August 17, 2016

Count total number of records – what is the issue

Count total number of records – what is the issue



How simple can that be to count total number of records – just use linq query using EntitySetobject like the one below
?
1
var contactCounter = new ServiceContext(_service).ContactSet.Select(item => item).Count();
and that’s it. But no – you will get an exception:
Invalid ‘count’ condition. An entity member is invoking an invalid property or method.

Why?

If we use var as variable type (rather than strongly typed) then Select linq statement will useIQueryable as a default output type. Simple trick is to declare variable type and use CreateQuerystatement when using OrganizationServiceContext

Solution

?
1
2
IEnumerable<Entity> contacts = new ServiceContext(_service).CreateQuery(Contact.EntityLogicalName).Select(item => item);
           var contactCountere = contacts.Count();

Tuesday, August 16, 2016

Impersonate using the ActOnBehalfOf privilege

https://msdn.microsoft.com/en-us/library/gg309629.aspx



// Connect to the Organization service. 
// The using statement ensures 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();

    // Retrieve the system user ID of the user to impersonate.
    OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy);
    _userId = (from user in orgContext.CreateQuery<SystemUser>()
              where user.FullName == "Kevin Cook"
              select user.SystemUserId.Value).FirstOrDefault();

    // To impersonate another user, set the OrganizationServiceProxy.CallerId
    // property to the ID of the other user.
    _serviceProxy.CallerId = _userId;

    // Instantiate an account object.
    // See the Entity Metadata topic in the SDK documentation to determine 
    // which attributes must be set for each entity.
    Account account = new Account { Name = "Fourth Coffee" };

    // Create an account record named Fourth Coffee.
    _accountId = _serviceProxy.Create(account);
    Console.Write("{0} {1} created, ", account.LogicalName, account.Name

On Change and Fire On Change in CRM 2016

The OnChange event doesn’t occur if the field is changed programmatically using the setValue method. If you want event handlers for the OnChange event to run after you set the value, you must use the fireOnChange method in your code.

https://msdn.microsoft.com/en-us/library/gg334481.aspx#BKMK_FieldOnChangeEvent


Xrm.Page.getAttribute(arg).fireOnChange()
https://msdn.microsoft.com/en-us/library/gg334409.aspx

Monday, August 8, 2016

Date and Time operators in CRM Explained

When you add conditions to Advanced Find in CRM to filter records based on a DateTime field, some operators such as “Today” are quite clear, while others such as “Next X Weeks” are trickier (e.g. When does the week start?). This post explains in detail what these operators mean and how to combine them to create more powerful filters.

https://community.dynamics.com/crm/b/gonzaloruiz/archive/2012/07/29/date-and-time-operators-in-crm-explained

Day Operators

Next X Days: Starts now and includes the next X days (regardless of time). E.g. If it is 3:30PM, “Next 1 Days” includes today after 3:30 PM and goes until the end of the day tomorrow (11:59PM). Note that this is not the same as “Next 24 hours”. When the field is only Date (no Time particle) then usually the time is set to 12AM (hidden) so this operator will not include today.

Last X Days: Includes all values that are before now and on/after X days ago. E.g. If it is 3:30PM, “Last 1 Days” includes today (before 3:30 PM) as well as yesterday the entire day (12AM-11:59PM). Note that this is not the same as “Last 24 hours”. Also note that when you have DateTime fields without a time component, the time will usually be se to 12AM (hidden) so this operator would include today in that case.

Next 7 Days: Behaves the same as “Next X Days” when X == 7.




Hour Operators

Next X Hours: Behaves like “Next 60*X Minutes”. It starts now and it includes X hours ahead. E.g. If it is 3:30PM then “Next 1 Hours” includes from 3:30PM – 4:30PM.

Last X Hours: Includes all values in the current hour before now, as well as all values in the past X hours. (NOT the same as “Last 60*X Minutes). E.g. If it is 3:30PM then “Last 1 Hours” includes from 2:00PM to 3:29PM).




Week Operators

Next Week: This is NOT the same as “Next X Weeks” where X == 1. It includes all values starting on the first day of next week and includes the 6 days after that one. The first day of next week is configurable in the System Settings section. For example, the week can start next Sunday (Default for U.S.) or next Monday (Default for U.K.).

image

This operator uses a “calendar week”. As an example, if it is Friday and the first day of the week is Sunday then “Next Week” means all values from next Sunday until next Saturday.

Last Week: This is NOT the same as “Last X Weeks” where X == 1. This operator includes all values before the current calendar week. The calendar week depends on the “Frist Day of Week” system setting. For example, if today is Saturday and the “First Day of Week” is Sunday then “Last Week” would include all values starting 2 Sundays ago and until last Saturday.

This Week: Includes all values of the current calendar week.

Next X Weeks: Same behaviour as “Next X*7 Days”. (Not the same as “Next Week” when X == 1). E.g. “Next 2 Weeks” is the same as “Next 14 Days”.

Last X Weeks: Same behaviour as “Last X*7 Days”. (Not the same as “Last Week” when X == 1). E.g. “Last 2 Weeks” is the same as “Last 14 Days”.




Month Operators

Next Month: Includes all values of the next calendar month. If we’re in August then it includes all values in September (same year).

Last Month: Includes all values of the last calendar month (before the current month). If we’re in August then it includes all values in July (same year).

This Month: Includes all values of the current calendar month. If we’re in August then it includes all values in August (same year).

Last X Months: This operator does not use the calendar year. It includes all values before now and on/after the same calendar day on the previous month. E.g. if it is 3:30PM on August 3rd then “Last 1 Months” includes all values between July 3rd all day (since 12AM) and today at 3:29PM. When X == 1, this is NOT the same as “Last Month”. Also note that when you have DateTime fields without a time component, the time will usually be se to 12AM (hidden) so this operator would include today in that case.

Next X Months: This operator does not use the calendar year. It includes all values starting now and until the same calendar day on the next month (inclusive). E.g. if it is 3:30PM on August 3rd then “Next 1 Months” includes all values between now (3:30PM) and September 3rd (until 11:59PM). When X == 1, this is NOT the same as “Next Month”.Also note that when you have DateTime fields without a time component, the time will usually be se to 12AM (hidden) so this operator would not include today in that case.

Older than X Months: This operator does not use the calendar year. It includes all values before the current calendar day of the previous month. E.g. if it is 3:30PM on August 3rd then “Older than 1 Months” operator would include all values on or before July 2nd at 11:59PM.




Year Operators

Next Year: Includes all values of the next calendar year.

Last Year: Includes all values of the last calendar year.

This Year: Includes all values of the current calendar year.

Last X Years: This operator does not use the calendar year. It includes all values before now and on/after the same calendar day on the previous year. E.g. if it is 3:30PM on August 3rd 2012 then “Last 1 Years” includes all values between August 3rd 2011 all day (since 12AM) and today at 3:29PM. When X == 1, this is NOT the same as “Last Year”. Also note that when you have DateTime fields without a time component, the time will usually be se to 12AM (hidden) so this operator would include today in that case.

Next X Years: This operator does not use the calendar year. It includes all values starting now and until the same calendar day on the next year (inclusive). E.g. if it is 3:30PM on August 3rd 2012 then “Next 1 Year” includes all values between now (3:30PM) and August 3rd 2013 (until 11:59PM). When X == 1, this is NOT the same as “Next Year”. Also note that when you have DateTime fields without a time component, the time will usually be se to 12AM (hidden) so this operator would not include today in that case.




Other Operators

Any Time: Same as “Contains Data”. It will return all values which are not blank.




Composite (logical) Operators

Given the operators in Advanced Find, you can combine them and group them to achieve more complex operators. These are some typical examples:

Older Than X Years: Simply multiple X by 12. E.g. “Older than 2 years” is the same as “Older than 24 Months” which is a supported operator.

On Year 2008: This is equivalent to combining “On Or After” 2008-01-01 and “On Or Before” 2008-12-31. You can use the same logic for filters such as “In January 2010

In the Past: You can combine “Last 1 Months” and “Older than 1 Months” to include all the values in the past.

Next 3 Calendar Weeks/Months: Unfortunately you cannot build such a query from DateTime fields. You would have to either store the week/month in a separate numeric field or otherwise build a report that applies additional Datetime expressions to filter the results. CRM only supports filtering by calendar week/month for last, this and next week/month. (same applies to year).



Note: Most of these operators depend on the user’s time zone. For example, a DateTime field value can be “Today” for users in Italy, but “Tomorrow” for users in Canada.

Email Router Demystified – Tools for Troubleshooting - Fiddler

Author note: As you’ll notice with most of my blog posts, they tend to have a lot of information and are a bit long.  Instead of sacrificing content, I’ll break up the posts into a series for posts.  This way people don’t get overwhelmed with the amount of content but for those that want the deep technical details, they get that as well.
This article covers Fiddler and is the second article within the Email Router Demystified – Tools for Troubleshooting blog series.  To get to a list of the other tools, go HERE.
Reference-
 https://community.dynamics.com/crm/b/dynamicscrmsupportblog/archive/2016/05/26/email-router-demystified-tools-for-troubleshooting-fiddler
I could, literally, spend hours on how we use Fiddler to capture data and then how to analyze the data in various different ways.  On the surface, the tool seems so simple but it can really give you some very deep data if you understand how to mine the data.
Again, we will simply focus on how to use it as it relates to the Email Router.  First, you need to know where to get Fiddler.  Well, oddly, this is one of the only non-Microsoft tools that I use.  It’s a Telerik tool which you can find here:

What is Fiddler?

Fiddler is a web proxy debugger.  What does that mean?  Well, in simplistic terms, the http and https requests all go through Fiddler.  Fiddler hooks into the Internet Options and configures itself as a proxy.  Since it’s a proxy, all of that traffic will go through the application so we can monitor the requests and responses being made.

When should we use Fiddler?

Again, Fiddler will capture http and https traffic.  So this means we should only capture this if we want to monitor the request and response for http/https traffic.  In the case of the Email Router, there are only a few things we are able to capture Fiddler data:
  1. Load Data
  2. Test Access (Only if using Exchange Web Services (EWS))
  3. Incoming processing using EWS
  4. Outgoing processing for Exchange Online
  5. Connectivity to Microsoft Dynamics
That’s it!  This tool will not capture SMTP or POP3 traffic.  It will only capture EWS traffic.  We will talk about other tools to help us with capturing SMTP and POP3 traffic next.
One big gotcha here.  Even though Fiddler will capture HTTP traffic, the information you are going to see from the request and response is going to be “encrypted” from WCF.  For us to get data from CRM and Exchange, they must both be configured for HTTPS.

How do we use this tool?

This is extremely important to understand.  Fiddler will only capture the http/https traffic of the account that ran Fiddler or of services that is using Fiddler as a proxy.  This means that if I am logged into a workstation as Alan Jackson and launch Fiddler, it will only capture traffic for Alan Jackson. Ok, that makes sense but why does this matter?  Well, by default, the Email Router service is set to run with the Local System account. 
To capture the traffic for the Email Router service, we must do one of two things:
  1. Run the service as the logged on user
  2. Create the Microsoft.Crm.Tools.EmailAgent.exe.config file and define the Fiddler proxy

Run the service as the logged on user

What we need to do is to change the Log On As to the logged on user.  Now there are a couple of caveats here for CRM on premises customers.  The account that is running the Email Router service needs to be a CRM user or it needs to be a member of the PrivUserGroup.  The reason is that the service is the one responsible for retrieving the users and queues within CRM.  If the service account is not a CRM user or not a member of the PrivUserGroup, we will fail to actually connect to CRM EVEN if the Deployment tab is set to use a CRM user.

Create the Microsoft.Crm.Tools.EmailAgent.exe.config file and define the Fiddler proxy

If we are not able to run the service as the logged on user, we can configure the Email Router service to send all the traffic to the Fiddler proxy.  To do that, we must first stop the Email Router service and then create the Microsoft.Crm.Tools.EmailAgent.exe.config file found here:
C:\Program Files\Microsoft CRM Email\Service
After creating the file, we set the following information within the file:
<configuration>
<system.net>
  <defaultProxy>
    <proxy bypassonlocal="False" usesystemdefault="True" proxyaddress="http://127.0.0.1:8888" />
  </defaultProxy>
</system.net>
</configuration>
Before this can work, you must have Fiddler installed and configured properly otherwise the Email Router service will fail to connect.  It’s important that you either delete or rename this config file after you are done capturing trace data with Fiddler.
Now we have the Email Router service configured to be able to capture traffic through Fiddler, what do we do next?

Configuring Fiddler for HTTPS

The first thing we need to do is install Fiddler.  However, that process is pretty straight forward so we won’t go into that.   After that, we need to configure Fiddler.  The configuration depends on what you did in the previous step.  If you created the config file, then you need to be sure to configure Fiddler to Reverse proxy.  
Everyone then needs to go through this next step.  For standard HTTP traffic, there is no additional configuration.  However, for HTTPS traffic, we need to make sure that Fiddler can decrypt the SSL traffic by being a certificate proxy.  We do that by:
  1. Open Fiddler
  2. Go to Tools > Fiddler Options
  3. Click on HTTPS tab
  4. Ensure “Capture HTTPS CONNECTs” is checked and then check “Decrypt HTTPS traffic”
After doing this, it’s going to prompt you with some interesting pop ups about trusting the Fiddler Root certificate.  Simply click on Yes on each prompt.  
At this point, click on OK to close any remaining windows and close and re-launch Fiddler.

Capture traffic using Fiddler

Now that Fiddler is installed and configured, we are ready to capture our HTTP/HTTPS traffic.  When Fiddler is launched, it will automatically start capturing HTTP/HTTPS data for the logged in user.  There are a few things to review about Fiddler that can make it easier to review and correlate the data.  These are:
  • Result – This is the HTTP response code back from the server.  You can review what each response code means in this article.
  • Host – This is the server that the request was sent to
  • URL – This is the actual page that the client is trying to access
  • Process – This is the process making the requests
Unless you are putting in filters in the Fiddler trace capture, you may capture a lot of other traffic that is not relevant to the issue at hand.  Using these fields, we can validate the request is coming from the Email Router and what service is handling that part of the router request.

Request/Response Bodies

After we have isolated a particular line we want to learn more about, we can look at some really good details of the request being made by the email router and then the response back from the server.  We do this in Fiddler within the right-hand pane and by clicking on Inspectors tab.
The messages that are going to be important to us are going to be the ones that have a result of success (2xx) or of server failure (5xx).  If the client is failing, it will have a result of 4xx and that is something like authentication failures or certificate problems.  While we could gain more from those request/responses, the more important things we focus in on are 2xx and 5xx result HTTP codes.
So the important thing to know here is that not all errors are going to be logged as a 5xx result code.  5xx really means that the server was unable to process the request.  However, most of the time, the server is able to process the request and provides a response back to the client as a 200.  We have to actually look into the response body to determine what the failure was when the server handled the request.

Request Bodies

The proper request bodies can tell us EXACTLY what was asked of the server.  Since we are connecting to service endpoints for both Exchange and CRM, the request should contain XML details that help quickly parse through the data.
 
We can then take the details we have pulled from the request XML and use it in the next tool we will cover, EWS Editor. 

Response Bodies

So now that we know what the client requested of the server, what did the server give us back in a response.  Now, as long as we got a 200 result, we will see the response from the server within an XML format.  Again, this helps us easily parse through data.
 
Now this is good information when the response result was 200.  However, if we get an error message, it’s possible we may need to look at the raw data to get more details of what may be going on:

EWS Editor

What happens when the email router fails to access a mailbox or it fails to retrieve an email from the mailbox?  The problem is typically an issue with Exchange.  To help confirm the issue with Exchange and to test some configurations without having to make changes in CRM or the email router, we can use EWS Editor.  EWS Editor will allow us to make the same calls to Exchange and see what the response back from Exchange is.  It helps narrow and isolate the issue.
You can get EWS Editor from CodePlex
The part of EWS that is most helpful to us is the EWS POST tool:
At first, this may be overwhelming.  The fact of the matter is that it’s very easy.  Essentially what we need to do is provide some basic information.

Authentication

The authentication details are based off of what you are providing in the Email Router Configuration Manager for the profile using EWS:

Headers

We pull the headers from the Fiddler trace.  Really the only thing we need is the verb which is always a POST:

Request Text

Finally, we enter in the Request text which we get from the Request Headers in Fiddler
Now when we click on Run, we SHOULD get the same response back from the server from EWS Editor that we got back from the Email Router within Fiddler:
If we are not getting the same message back, then we should be focusing on a possible load balance scenario in which one server may be out of date or may be down.