Punditor

Share what you do best

Microsoft Lync gets unresponsive

Working with Lync can be a pain sometimes … Why not use Skype? Why is Microsoft trying to push so hard to use Lync as Skype for Business vs using Original Skype for Business.  Skype, I feel is a more reliable software and it’s already proven over many years in it stability. I have a lot of Whys when I deal with Lync ….

The Issue/Behavior

For the past couple of days I have been fighting with Lync. After I changed my password for some reason Lync stopped working, at least that’s what I’m thinking caused the issue.  The behavior was each time when I tried to start Lync, it kept becoming unresponsive after 5-7 seconds. So I would have to kill the process and start over.

First thing I checked the Application Logs to see if I could locate anything related to Lync and of course there was nothing, so who knows why it doesn’t work.  The next troubleshooting step for me was to try to repair Lync. My Lync was installed as a part of Microsoft Office 365 ProPlus. For that reason I couldn’t uninstall or repair Lync by itself, at least I couldn’t figure out how to.

I ran the repair process for whole Microsoft Office Suite a couple of times and I still couldn’t resolve the problem with Lync. It continued to behave the same way, after few seconds it continued to be unresponsive. Very bad user experience.

Because the steps above didn’t address the issue I tried to sign out of Lync and Delete my sign-in info. I was assuming by deleting my sign-in info the next time I start Lync it would ask me to provide my credentials, my assumptions was wrong. I started Lync and it automatically signed me in again. I tried it a couple more times and had the same user experience.  On the other side Skype works perfectly fine without any issues. In any case the issue with Lync couldn’t stop me from performing my duties ,however, it sure did make me waste my time.

Solution

Long story short and a day after. To resolve this issue I figured I needed to disable IDT High Definition Audio Codec in the Device Manager. Lync had a hard time trying to use it and that’s why it was getting unresponsive.

Right Click My Computer -> Manage -> Device Manager -> Sound, video and game controllers

Conclusion

In the end the issue wasn’t related to Lync itself it just couldn't use the default audio device. Lync's problem is a  user experience and not working properly built in functionality in this case. Honestly, How hard is it to display a descriptive error if something goes wrong behind the scene?

Just in case you stumble upon the same issue I hope my experience will save you time.

Feel free to contact me if you have any questions.


How to create a custom C# Dynamics CRM Data access libraries?

This is the first article in a series of four. In these sets of articles I’m going to cover the topics below:

  1. How to create a custom C# Dynamics CRM Data access libraries?
  2. How to add a DI to a custom Dynamics CRM Data Access layer?
  3. How to unit test Business and custom CRM Data access layer with Unity and Mocking?
  4. How to share the same code across multiple applications, CRM plugins and workflow activities?

High level overview of the complete project.

The main idea of this project is to create a testable, expandable and maintainable code that can be easily shared across multiple applications, CRM Plugins and CRM Workflow activities.


In my first article I’m going to show you how to create C# libraries for managing CRM data. In the following articles, we are going to create a Business layer and implement Dependency Injection using Microsoft Unity framework. In the third article we are going to cover one of the most important topics in Software Development, Unit Testing, as well as techniques for mocking Dynamics CRM repository.


How to create a custom C# CRM Data access layer?


I think that's enough talking. Now let’s create a custom C# data access layer for Dynamics CRM. First we need to create a new solution using Visual Studio.


Steps: File->New-> Project Under Installed -> Templates -> Other Project Types select Visual Studio Solutions -> Blank Solution.




For this example I’m going to name the solution ReusableCode, but you can name it the way you want.  Now, let’s add a few folders. This way our solution visually will be better organized.


  • Shared

  • Console


Let’s create the projects below and add them to the solution:

  • ReusableCode.Repository - Data Access Classes/Methods (Root folder);

  • ReusableCode.IRepository - Metadata for our Data Access layer (Root folder);

  • ReusableCode.Console - Debugging/Testing (Console folder)

  • ReusableCode.Constants - (Shared folder)


We need to add references from ReusableCode.IRepository project to ReusableCode.Repository.


Now let’s add two classes to keep our Repository responses consistent. The first class is going to contain CRUD action type statuses.  The second is going to serve as a wrapper to return results, statuses and exceptions, if any. A bit off topic but very important in Software Development is to be consistent and when you create something new it's the best time to adapt those standards. Okay now we are ready to code.


public enum RepositoryActionStatus
{
        Ok,
        Created,
        Updated,
        NotFound,
        Deleted,
        NothingModified,
        Error
}
public class RepositoryActionResult<T> where T : class
{
        public T Entity { get; private set; }
        public RepositoryActionStatus Status { get; private set; }
        public Exception Exception { get; private set; }

        public RepositoryActionResult(T entity, RepositoryActionStatus status)
        {
            Entity = entity;
            Status = status;
        }

        public RepositoryActionResult(T entity, RepositoryActionStatus status, Exception exception) : this(entity, status)
        {
            Exception = exception;
        }
}

In this article I’m going to use an Account entity, but feel free to use any entity you would like. We need to create an IAccountRepository interface where we define our 4 CRUD methods like; Create, Update, Delete and Retrieve. Next, we need to create an AccountRepository class that will implement an IAccountRepository interface. To make it work with CRM Service we need to add references to Microsoft.Xrm.Sdk.dll library that comes with CRM SDK framework and System.Runtime.Serialization which is part of .Net Framework to both ReusableCode.IRepository and ReusableCode.Repository projects.


In addition, let’s create a ReusableCode.Constants project under the Shared folder. We need it to be able to reuse the same constants across multiple projects. We will kill two birds with one stone, avoid code duplication and misspelling entity names. (if you decide to use an early bound approach it will be only partially applicable).






First we need to initialize IOrganizationService. You can do it by using constructor like in the screenshot below. Just a tip you can use a shortcut to create a constructor in Visual Studio, by typing ctor + Tab.



Second, let’s add implementation for each method Create, Retrieve, Update and Delete. Create methods like on the screenshots below. They are all basic examples and you can modify them depending on your needs, but it gives you a starting point.


Create



Retrieve



Update



Delete



After creating the methods we need to test them. For this example we are going to use a Console application. We need to add references to the Dlls below. The first two libraries are part of CRM SDK and last one is of .Net Framework.


  • Microsoft.XRM.Client - for CrmConnection

  • Microsoft.Xrm.Sdk - for IOrganizationService

  • System.Configuration - for CrmConnection

  • System.Runtime.Serialization - for serialization, Entity class required it.

We also need to add reference to our Repository,IRepository and Constants projects.

Next it’s time to add an App.config file and specify a connection string to connect to your CRM Organization and we need to initialize IOrganizationService and CrmConnection. Your code should look like the code below:




Okay, now we’ve finished with setting everything up and we are ready to test our repository methods. We are going to make an instance of our AccountRepository class and call Create, Update, Retrieve and Delete methods.


Here are an examples for each action.






Okay ... so it wasn’t very hard. I think we accomplished a lot in this example. The most important thing this code will serve us as a base for the following articles.

Feel free to leave you comments or suggestions or shoot me an email if you have any questions.

How to add a button to the ribbon navigation and call JavaScript function in CRM?

In this article we are going to go over the steps required for adding a button to the Ribbon Navigation. The goal is to add a button to the Ribbon navigation and upon clicking that button it will execute a JavaScript function. Below is the high level steps we would need to take. I will go into more details further in the article.

Steps:

  1. Create a new solution;
  2. Add an Entity and required web resources (icon, JavaScript file);
  3. Save, Publish and Export as Unmanaged solution;
  4. Unzip files;
  5. Modify customizations.xml file;
  6. Save and Zip all files;
  7. Import solution back to CRM;
  8. Publish. 

At first we need to create a new solution where we are going to combine all customization we need for this task. After we created the solution let's add an Entity we would like to add a Ribbon Navigation button. In my case it's Inventory entity but you can add any entity you would like. Now we are ready to add an icon and JavaScript web resources. 

Steps:

Go to Settings->Solutions double click your CRM Solution. After solution is opened you need to click New->Web Resource.

Fill out the form and specify the file you would like to upload and click Save. Next step is to add a JavaScript file with a function. New->Web ResourceClick Text Editor and type simple function to display alert on Click.

function updateInventory(){ 
       alert("Inventory Updated"); 
}
Now we are ready to Export our solution. After solution export is complete we need to unzip files and modify customizations.xml file. You can use any type of text editor to modify, notepad or Notepad ++. Customizations.xml file contains customization and configuration for your system. Let's add a reference to a new button, icon, JavaScript web resources and specify the name of the function we execute on button click.

After we modify the customizations.xml file we have to zip all files and import back to CRM. After this import process is completed we would need to publish our customization. Click Publish ll Customizations button.

RibbonDiffXML Attributes and Elements Definitions
  • <CustomActions> - Contains a collection of actions that can add, replace, or remove items from the ribbon.
  • <Templates> - Contains a collection of ribbon templates.
  • <CommandDefinitions> - Contains a collection of commands that can be referenced by ribbon controls.
  • <RuleDefinitions> - Contains a collection of rule definitions.
  • <LocLabels> - Contains a collection of LocLabel elements.

You can find more details about RibbonDiffXml section on MSDN Microsoft site.

This how ribbondiffxml section looks before and after our customizations.

Before

ribbondiffxml_before.txt (290B)

ribbondiffxml_after.txt (1.1KB)


Use ExecuteMultipleRequest for a better performance when you work with bulk data load

In some of the cases you will need to create a bunch of records and for a better performance, consider using ExecuteMultpleRequest class that comes as part of CRM SDK. It allows you to execute multiple requests as a single batch operation. You can use it for Create, Update and Delete requests.


Some of the settings you can specify are

  • Continue on Error;
  • Return Responses.

Continue on Error. If you set this setting to True it will execute all requests even if an error occurs during the execution. If you set it to False it will stop execution for all requests in case of the error.


Return Response. When this setting is set to True you will get a response for each request and False if not. However, if an error occurs it will still return a response with a fault error. If you don’t need a response set it to False it will execute all requests much faster.

Settings = new ExecuteMultipleSettings()
{
      ContinueOnError = false,
      ReturnResponses = true
}

ExecuteMultipleRequests Limitations 

  • No recursion is allowed - ExecuteMultipleRequest cannot invoke ExecuteMultipleRequest
  • Maximum Batch Size. Limit 1000 requests. 
  • Throttling of concurrent calls. There is a limit of 2 concurrent ExecuteMultipleRequest executions per organization.

For the purpose of this article let’s assume that we need to Create 100 Accounts in CRM. First we are going to try to create individual one by one and after that we are going to build a collection of the requests and execute them as a batch operation.

First, let’s create a Console application and add reference to CRM SDK libraries. For our example we need:
  • Microsoft.XRM.Client - for CrmConnection
  • Microsoft.Xrm.Sdk - for IOrganizationService
  • System.Configuration - for CrmConnection
Now we are going to create two main methods to create entity sequentially and as a bulk request.
public static void SequentialCreate(List<Entity> entities)
{
     foreach (var entity in entities)
          _service.Create(entity);
}
public static void BulkCreate(List<Entity> entities)
{
    var multipleRequest = new ExecuteMultipleRequest
    {
        Settings = new ExecuteMultipleSettings
        {
              ContinueOnError = true,
              ReturnResponses = false
        },
        Requests = new OrganizationRequestCollection()
    };

    try
    {
        foreach (var entity in entities)
        {
               var createRequest = new CreateRequest { Target = entity };
               multipleRequest.Requests.Add(createRequest);
         }

          var multipleResponse = (ExecuteMultipleResponse)_service.Execute(multipleRequest);

          foreach (var responseItem in multipleResponse.Responses)
          {
                    DisplayResponse(multipleRequest.Requests[responseItem.RequestIndex], responseItem.Response);
          }
      }
      catch (FaultException fault)
      {
           if (fault.Detail.ErrorDetails.Contains("MaxBatchSize"))
           {
               var maxBatchSize = Convert.ToInt32(fault.Detail.ErrorDetails["MaxBatchSize"]);
               if (maxBatchSize < multipleRequest.Requests.Count)
               {

               }
            }
           throw;
      }
}
To support our example we also need a method to generate entity and some code to measure the time for processing requests.
private static List<Entity> GenerateData()
{
     var entities = new List<Entity>();
     for (var i = 0; i < 100; i++)
     {
           var account = new Entity("account");
           account["name"] = String.Format("Account Name - {0}", i);
           entities.Add(account);
     }
     return entities;
}

The DisplayResponse method is optional in case you would like to receive a response for each request.
private static void DisplayResponse(OrganizationRequest organizationRequest, OrganizationResponse organizationResponse)
{
    Console.WriteLine("Request: " + organizationRequest.RequestName + " " + organizationResponse.Results["id"]);
}

Okay. Now we are ready to run our application and see the time difference between first and second approach. If for some reason you code doesn’t compile feel free to download source code for this example.



As you can see ExecuteMultipleRequests is almost 3 times faster than sequential execution. Keep in mind if you enable ReturnResponses setting the timing will be slower but it should still have a better performance than sequential request execution.

I hope you find this example helpful and easy to follow. Feel free to leave your comments and suggestions.
ExecuteMultpleRequestExample.7z (236.8KB)

Early vs Late bound entities and how to use them

In this article I would like to go over  Early and Late bound entities in CRM. We are going to cover the differences and some advantages of using one or another approach. I’m going to show  how you can generate Early Bound classes from your metadata using CRM SDK.

Late Bound Entities

First and the most common approach of working with data in CRM is to use late bound entities. The Late Bound approach is a slightly faster way of working with data in CRM. When you work with small chunks you won’t see the difference, only if you retrieve thousands of records you will see a better performance by using Late Bound Entities.

Example:
Entity account = new Entity("account");
account["name"] = "Business Name";

Early Bound Entities

The second way is Early Bound Classes. There are multiple ways of how you can start working with Early Bound Classes. One of them is to use CRM SDK crmsvcutil to generate classes and another way is to use CRM Developer Toolkit. In both cases it creates one class per CRM Entity, both custom and default entities. Most of the time I use  crmsvcutil.

Based on my experience  when you work with CRM system that are highly customized I would recommend to use other utils to generate strongly named classes, because the generated file will be very large and it will be very hard to work with. In addition, with tools like XRM Tool Box you can exclude the entities you don’t need or you can generate one file per entity. At the end of the day it's your choice whatever streamlines your work process.

Keep in mind each time you change metadata in CRM you will need to re-generate classes. To automate it you can configure Build process to update your classes as an option.

Example:
Account account = new Account();
account.Name = "Business Name";

How to generate Early Bound Classes?

Now we are going to go over the steps that are required to generate early bound classes. For that you would need to download CRM SDK. Click Here to download CRM SDK. After you download extract files somewhere on your hard drive.


Now we would need to get an Organization Services URL from your CRM. Go to Settings -> Customizations -> Developer Resources and in Service Endpoints section you should see three services Discovery, Organization and Organization Data Services. Copy Organization Service URL.


Open CMD (Windows Key + R and type CMD) navigate to the folder where you extracted CRM SDK files SDK\Bin and type the command below. Don’t forget to replace username, password and namespace you would like to use.


crmsvcutil /url:http://dcrm.carvelocity.com/professionalservices/XRMServices/2011/Organization.svc /out:CRMEntities.cs /username:[username] /password:[password] /namespace:[namespace]

After you run the command it should not take long to create file with classes. Of course it depends on how customized your system is and how many Entities you have.


For example, one of the organizations I had  the pleasure of working with was highly customized. The CRM Organization had a lot of custom entities. It took almost 1-2 minutes to generate the file with classes. The size of the file was about 11 MB and it was almost impossible to work with. So think about all advantages and disadvantages before you start using Early Binding approach.


As I mentioned above you can use a third party software like XRM Tool Box, Early Bound Generator tool. You can download it here. Click Here to download XrmToolBox. This tool is much more robust than CRMSVCUtil and you would have more control over the process.  


I hope you found this article helpful. Feel free to contact me if you have any questions.

Main rules for keeping your code clean and maintainable

Below you can find the main rules on how to keep your code clean, maintainable and anger free. When you code always remember the quote below. It will help you to remember the rules.

"Always code as if the person who will maintain your code is a maniac serial killer that knows where you live."

  1. Don't use comments. If you feel like your code needs explanation rewrite it. Most of the time when the code needs comments it is a bad code. Keep it simple.
  2. Keep all your methods very simple and small. Stick to the single responsibility rule. Basically each method should handle only one thing and do it very well. The purpose of the method usually is to perform an action, verify or validate something. Don't ever mix both, because it will lead to confusion.
  3. Name your methods well. Name should be descriptive. Don't rush, think about a good name. Sleep on it. Always remember if you choose a bad name the developer who is going to maintain your code will think about you and not in a good way.
  4. If you use a source control, don't comment out your code. It should be obvious, but I see it all the time. If you need to restore a previous version of your code, use View History in Source Control.
  5. Boy-scout rule. Check in code a bit cleaner than you found it. If we all would do it we would end up with a perfect code.
  6. Use nouns to name your classes. Examples: Profile, User, Account etc.
  7. Use verbs or verb phrases to name your methods. Examples: UpdateProfile, CreateProfile, DeleteProfile, etc.
  8. Be consistent. Use the same naming per concept. If you use a Retrieve verb in your methods use it everywhere. Don't mix it with Get or other synonyms.
  9. Minimize a number of parameters you pass to your method. The less you pass the better. If you need to pass more than 3 parameters create a class. Don't use a Boolean as a parameter. It's a sign that method does more than one thing and its time to refactor it.
Happy coding.