Tuesday, 16 January 2018

How to check the status of windows service using c#

C# code to check status of a windows service


Below is the C# code which return the status of a windows service running on a machine/server on passing correct name.

One use case of it is that if we want to monitor some specific services which are critical to operation, we can schedule our application to check the status of the specific service/services and if it's ha stopped, we can do certain action like sending an email to concern people so that corrective action can be taken.


Include using System.ServiceProcess; reference in your application.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

   public static String GetWindowsServiceStatus(String SERVICENAME)
        {

            ServiceController sc = new ServiceController(SERVICENAME);

            switch (sc.Status)
            {
                case ServiceControllerStatus.Running:
                    return "Running";
                case ServiceControllerStatus.Stopped:
                    return "Stopped";
                case ServiceControllerStatus.Paused:
                    return "Paused";
                case ServiceControllerStatus.StopPending:
                    return "Stopping";
                case ServiceControllerStatus.StartPending:
                    return "Starting";
                default:
                    return "Status Changing";
            }
        }


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Below is the sample test result:




Hope it would be helpful..!!

Saturday, 13 January 2018

Microsoft Dynamics 365 v9.0 latest feature – Show Progress Indicator

Microsoft Dynamics 365 v9.0 latest feature – Show Progress Indicator

In latest release of Dynamics 365 i.e. v9.0 MS has introduces many new features to enhance the user experience, Progress indicator is one of them.

Many times we need to write client side javascript code which take some time to execute due to many reasons (further server side code running etc). In such case, in earlier version user were not able to know that if anything is happening in background and  user needed to wait for next response from crm system.

Now in this release, MS has introduced progress indicator which is can be called as showProgressIndicator function of Xrm.Utility. namespace.
It's take a text string as parameter to display on the progress indicator.
We have created an example test case of it's use in which can be utilize in more relevant cases like while calling any function from ribbon button etc to show message to user.
Here we are loading the mobile no of primary contact of an account and showing it in an alert message and during the period we want user to be informed that system is loading it:

 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getPrimaryContactMobile()
{
 Xrm.Utility.showProgressIndicator("Loading mobile no of primary contact..");
 setTimeout(delayedLoadPrimaryContactDetails, 3000);
}

function delayedLoadPrimaryContactDetails()
{
 var contact = Xrm.Page.getAttribute("primarycontactid").getValue();
 if(contact == null){
 Xrm.Utility.closeProgressIndicator();
 return;
 }
 Xrm.WebApi.retrieveRecord("contact", contact[0].id, "$select=mobilephone")
 .then(function(result) {
 var mobileno = result["mobilephone"];
 Xrm.Utility.closeProgressIndicator(); //To close the progress indicator
 alert("Mobile no of primary conatct  : " + mobileno);
 })
 .fail(function(error) {
 Xrm.Utility.closeProgressIndicator();
 var message = error.message;
 alert("Error: "+message);
 });
}
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
The result is something like this:


I'm sure it can be useful in more complex scenarios.
Hope it would be helpful.
Happy CRM..!!

Friday, 12 January 2018

How to get security privileges in excel format in MS CRM

How to get security privileges in excel format in MS CRM using sql

Ms CRM sql RolePrivileges  table

Sometimes we need to get what all privileges a security role have, quickly without going into CRM standard security roles and find out.
Or if we want to keep the copy of privileges to different security roles as a reference to be used at some point of time in future, we have following sql query running which in sql server will give you list of name of security role, entity name with access level and security level:

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

SELECT DISTINCT FilteredRole.name, EntityView.PhysicalName AS [Entity Name], CASE Privilege.AccessRight WHEN 1 THEN 'READ' WHEN 2 THEN 'WRITE' WHEN 4 THEN 'APPEND' WHEN 16 THEN 'APPENDTO' WHEN 32 THEN 'CREATE' WHEN 65536 THEN 'DELETE' WHEN 262144 THEN 'SHARE' WHEN 524288 THEN 'ASSIGN' END AS [Access Level], CASE PrivilegeDepthMask WHEN 1 THEN 'User' WHEN 2 THEN 'Business Unit' WHEN 4 THEN 'Parent: Child Business Unit' WHEN 8 THEN 'Organisation' END AS [Security Level] FROM RolePrivileges INNER JOIN FilteredRole ON RolePrivileges.RoleId = FilteredRole.roleid INNER JOIN PrivilegeObjectTypeCodes ON RolePrivileges.PrivilegeId = PrivilegeObjectTypeCodes.PrivilegeId INNER JOIN Privilege ON RolePrivileges.PrivilegeId = Privilege.PrivilegeId INNER JOIN EntityView ON EntityView.ObjectTypeCode = PrivilegeObjectTypeCodes.ObjectTypeCode ORDER BY FilteredRole.name, [Entity Name]


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Hope the results are helpful..!! :)

Happy CRMing..!!


How to find workflows running on the user context in MS CRM

How to find workflows running on the user context in MS CRM using sql

Sql query to get all workflows which are running on user's context, workflowbase table in ms crm

Recently i needed to find out all the workflows which are running in the context of  the user who made changes to the record. To quickly find out the same we need to query workflowbase
 table in crm db.

Below is the query.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Select 
distinct(W.name)
 from workflowbase as W
join SystemUser  as S
on W.OwnerId=S.SystemUserId
where S.FullName = 'CRM Admin'
and W.IsCrmUIWorkflow=1 --
and W.RunAs=1 --1 the user who made changes to the record 0-owner of the workflow
and W.ParentWorkflowId is   null --For workflow header rows only
and mode=0 --for real time workflow only 0- real time 1-background
and w.Category=0 --Category 2- Business rule and 0 is workflow
order by W.name

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Happy CRMing

Monday, 8 January 2018

Unable to connect Plugin registration tool to Latest Dynamics 365 Version 9.0

Unable to connect plugin registration tool 

Recently i created a trial D365 org (version 9.0.0.3172) and tried connecting plugin registration tool downloaded with PRT of lastes sdk (version 8.2.1.1)from downloaded form here which is latest as on date on that portal of MS.

Newly created trail org is of version 9.0. while the latest sdk available is 8.2 but i though it shouldn't be any problem (though it was) since we were used to of using older version plugin registration tools with newer version of CRM ( remember connecting CRM 2013 organisation with PRT of 2011 sdk).


On some digging i found that reason of the same:

Latest Update on Dynamics CRM V9:


Latest update in the Microsoft TSL(Transport Security Layer) Protocol in SDK assemblies.

Microsoft allowed the TSL connection 1.0  and 1.1 for the browsers or client to connect the CRM org. Now Microsoft will support only TSL 1.2 or above. Can get more information here

If you are connecting your latest dynamic CRM trial org with the old version of plugin registration tool or connecting any external application, then you may face an issue.


TSL protocol of our .Net client is usually 1.0. You can check how to check tsl protocol of your .Net client by downloading fiddler from here

Once Fiddler gets installed, Go to Tools > Options in order to check Protocol version:



To Resolve Plugin registration connection issue we need to install Latest Plugin registration tool from Nuget rather than using PRT(Plugin registration tool) available in latest sdk available on MS website which is version 8.2.1.1 :-

Resolution:

There are 2 way of installing Latest Plugin registration tool easily:-
Option A:-

1. Create/Open a project in Visual studio



2.  Navigate to Tools>NuGet Package Manager>Package manager console


3. Paste following command in Packager manager console and hit enter:
Install-Package Microsoft.CrmSdk.XrmTooling.PluginRegistrationTool -Version 9.0.0.7


once executes, this will install the package in current opened solution folder.

4. Open the folder of the solution opened in Visual studio:


5. You'll see PRT V 9.0 in package folder:


6. Now try to connect to your version 9.0 CRM trial, it'll get connected. :)


Option B:-


1. Create a new project just like step 1 of Option A.

2. Right click on the project and click manage NuGet Packages:


3. Click on browse and enter 'Microsoft.CrmSdk.XrmTooling.PluginRegistrationTool'  and click install:-


4. It'll install the package in your solution's folder:-


5. You can navigate to the installed package same as step 4 and 5 of option A mentioned above.

6. Now connect your PRT with version 9.0 crm org and enjoy plugin registration.

Happy CRM,

Sunday, 7 January 2018

Dynamics CRM How to view records shared with a user

Dynamics crm How to see records shared with current user

In Dynamics crm you can create different types of views but by oob views it's not possible to show the records shared with current user in any view.

For achieving we need to update the xml of a system view to make it show shared records.

Scenario: Let's say we have a view of lead named "my shared leads".

Following is the fetch xml of the view which can be downloaded from advanced find.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="lead">
    <attribute name="fullname" />
    <attribute name="companyname" />
    <attribute name="telephone1" />
    <attribute name="leadid" />
    <order attribute="fullname" descending="false" />
  </entity>
</fetch>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Now to make it show shred records we have to update it's fetch xml with following xml:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<link-entity name='principalobjectaccess' to='leadid' from='objectid' link-type='inner' alias='share'>
 <filter type='and'>
 <condition attribute='principalid' operator='eq-userid' />
 </filter>
</link-entity>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

principalobjectaccess table store shared records.
to: primary field of the entity for which the view is (leadid in our case)
condition: principalid
Operator: eq-userid means princinpal user should be equal to current user.

Updated XML will look like

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="lead">
    <attribute name="fullname" />
    <attribute name="companyname" />
    <attribute name="telephone1" />
    <attribute name="leadid" />
    <order attribute="fullname" descending="false" />
<link-entity name='principalobjectaccess' to='leadid' from='objectid' link-type='inner' alias='share'>
 <filter type='and'>
 <condition attribute='principalid' operator='eq-userid' />
 </filter>
</link-entity>
  </entity>
</fetch>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Now get the guid of view from database or by querying as follows

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   public Guid  GetSavedQueryId(IOrganizationService service,String viewname)
        {
            Guid result = Guid.Empty;
            QueryExpression q = new QueryExpression("savedquery");
            q.Criteria.AddCondition("name", ConditionOperator.Equal, viewname);
            EntityCollection en = service.RetrieveMultiple(q);
            if (en.Entities.Count > 0)
                result= en.Entities[0].Id;

            return result;
            
        }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Once you got the Guid of the view you can update it with the help of following code:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void UpdateSavedQuery(IOrganizationService service,Guid viewid)
 {
 Entity UpdateQuery = new Entity("savedquery");
 UpdateQuery.Id = viewid;  //new Guid("12bc926f-26c0-e111-a4f9-00155d1c5b01"); //Guid of the view to be updated
 UpdateQuery["fetchxml"] = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
  <entity name='lead'>
<attribute name='fullname' />
<attribute name='companyname' />
<attribute name='telephone1' />
<attribute name='leadid' />
<order attribute='fullname' descending='false' />
<link-entity name='principalobjectaccess' to='leadid' from='objectid' link-type='inner' alias='share'>
<filter type='and'>
<condition attribute='principalid' operator='eq-userid' />
</filter>
</link-entity>
  </entity>
</fetch>";

service.Update(UpdateQuery);
 }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Don't forget to replace " in fetch xml with ' .

Once you execute above code, you'll be able to see shared record in your view.

Happy CRM