Fetch Global option set over ssrs report and resolution to OOB values

There are many scenarios where you have to map your ssrs paramter to Global option set of ms crm. To fetch that from Sql database use below define query.

SELECT OS.NAME, L.LABEL, AV.VALUE FROM ATTRIBUTEPICKLISTVALUEASIFPUBLISHEDLOGICALVIEW AV
JOIN OPTIONSETASIFPUBLISHEDLOGICALVIEW OS
ON AV.OPTIONSETID = OS.OPTIONSETID
JOIN LOCALIZEDLABELASIFPUBLISHEDLOGICALVIEW L
ON L.OBJECTID = AV.ATTRIBUTEPICKLISTVALUEID
WHERE OS.ISGLOBAL = 1 AND OS.ISCUSTOMOPTIONSET = 0
AND L.OBJECTCOLUMNNAME = 'DisplayName'
AND OS.NAME ='incident_caseorigincode'

In a where condition pass your global option set name. In my case i have pass caseOriginCode.

If we talk about case orgin code, we get certain value in this field which out of the box, such as:

phone, Email, Website, Facebook and twitter.

If you tries to delete these values from crm,save and publish. New global option set values reflect in MS crm application but the old value continues to show in SSRS report.

result1.png (351×235)

That is because MS crm do a soft delete with an out of box Values. To obtain an updated global optionset MS CRM, use the below define query

SELECT OS.NAME, L.LABEL, AV.VALUE FROM ATTRIBUTEPICKLISTVALUEASIFPUBLISHEDLOGICALVIEW AV
JOIN OPTIONSETASIFPUBLISHEDLOGICALVIEW OS
ON AV.OPTIONSETID = OS.OPTIONSETID
JOIN LOCALIZEDLABELASIFPUBLISHEDLOGICALVIEW L
ON L.OBJECTID = AV.ATTRIBUTEPICKLISTVALUEID WHERE OS.ISGLOBAL = 1 AND OS.ISCUSTOMOPTIONSET = 0 AND L.OBJECTCOLUMNNAME = 'DisplayName' AND OS.NAME ='incident_caseorigincode' and
AV.ComponentState=0

Basically when you perform a deletion of out of the box values from global option set in ms crm. CRM at a background update the component state attribute value to 2 which means that particular value has been deleted from system. To understand further about this attribute and their values,kindly go through a below link.

you can get the theory about this attribute from the MSDN link

https://docs.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg328546(v=crm.8)#bkmk_componentstate

So once you put a component state =0. Query will only give you the values which are in published state in CRM.

Thanks

MS CRM Security Roles Audit

To fetch all security role entity vise its and security level. Paste below query it can help you to fetch all the information from MS CRM.

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]

Result will be in below specefied format:

entity nameAccess levelsecurity level
Security test 1PhoneCallAPPENDParent: Child Business Unit
Security test 2PhoneCallAPPENDTOParent: Child Business Unit
Security test 3PhoneCallCREATEUser
Security test 4PhoneCallDELETEUser
Security test 5PhoneCallREADOrganisation
Security test 6PhoneCallSHAREUser
Security test 7PhoneCallWRITEUser

Thanks.

Microsoft Developer toolkit for Dynamics 365

The Developer Toolkit is a set of Microsoft Visual Studio Integration tools, focused on accelerating the development of custom code for Microsoft Dynamics 365(CRM).

Below URL can be used to download:

https://marketplace.visualstudio.com/items?itemName=DynamicsCRMPG.MicrosoftDynamicsCRMDeveloperToolkit

Microsoft Developer toolkit for Dynamics 365 / CRM has traditionally lagged behind Visual Studio in terms of releases, but with a few tweaks, it’s possible to get it up and running.

Step 1 – Download the VSIX for Dynamics 365.

This can be downloaded from here. Save it somewhere locally.

1

Step 2 – Extract the VSIX.

The VSIX is an archive. We need to update a file in there to get it to install. My tool of choice for doing this is 7zip. Right click and extract to a subfolder.

2

Step 3 – Update the VSIX Manifest

With a text editor, update the extension.vsixmanifest file. The existing VSIX will only work up to Visual Studio 2015 (14.0), so you need to update the references from version 14 to version 15. Once complete as shown below, save the file.

3

Step 4 – Install the VSIX

Because the VSIX was compiled by and for VS 2015, you will get a warning when installing, but it should still install successfully. We won’t be able to get rid of this warning, but just click OK, close and Restart Visual Studio.

4

Step 5 – Set your  Dynamics 365 SDK Paths in Visual Studio

If you haven’t already installed the SDK, download and extract it now. Then go to Tools -> Options -> Dynamics 365 Developer Toolkit -> Tool Paths. Set the paths to point to the plugin registration tool folder and bin folder where you extracted your SDK.

7

Once installed.

You can create New project selecting the MS dynamics 365 tool. Create a new solution which will get create in CRM as a solution.

Benefit of having toolkit is it gives you the base class. It contains all necessary service initalized.

such as:

PluginExecutionContext

OrganizationService

TracingService

Code Samples:

 internal LocalPluginContext(IServiceProvider serviceProvider)

            {

                if (serviceProvider == null)

                {

                    throw new InvalidPluginExecutionException(“serviceProvider”);

                }

                // Obtain the execution context service from the service provider.

                PluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                // Obtain the tracing service from the service provider.

                TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

                // Get the notification service from the service provider.

                NotificationService = (IServiceEndpointNotificationService)serviceProvider.GetService(typeof(IServiceEndpointNotificationService));

                // Obtain the organization factory service from the service provider.

                IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                // Use the factory to generate the organization service.

                OrganizationService = factory.CreateOrganizationService(PluginExecutionContext.UserId);

            }

Post that it also gives you an entity explorer through which you can select an entity and create new plugin steps.

Once created it will give you all necessary class method to start with custom code.

Code sample:

protected override void ExecuteCrmPlugin(LocalPluginContext localContext)

        {

            if (localContext == null)

            {

                throw new InvalidPluginExecutionException(“localContext”);

            }

            // TODO: Implement your custom Plug-in business logic.

          Entity entity = (Entity)localContext.PluginExecutionContext.InputParameters[“Target”];

            if (localContext.PluginExecutionContext.MessageName.ToUpper() == “UPDATE”)

            {

                localContext.OrganizationService.Update(entity);

            }

        }

Developer toolkit is one of the helpful tool to write and deploy plugins,custom activity and Web resource directly to CRM as solution component.

Thanks.

IIS Web Server

This is an “All in One” article for IIS. This will help beginners know what IIS is, how to install IIS, how to deploy sites on IIS, create an Application Pool, web garden, etc. 

Web Server

A web server is responsible for providing a response to requests that come from clients. So when multiple users come in, multiple requests also come in and the web server will have a response for each of them. IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host ASP.NET web applications. IIS has its own ASP.NET Process to handle ASP.NET requests. 

Overview of IIS

Internet Information Server is one of the most powerful web servers provided by Microsoft that is able to host and run your web applications. IIS supports the following protocols: FTP, FTPS, SMTP, NNTP, HTTP/HTTPS. We can host our web sites on IIS, we can use it as an FTP site also. 

How to Install IIS

Control Panel > Add/Remove Programs, then select Add/Remove Windows Component. 

Select “Application Server” from the checkbox list. This will open a new window, select IIS, and click on OK.

This will initiate IIS installation. The OS will show a continuous progress bar during installation and will show a final message after installation is complete.

IIS Process Model and Request Processing

We can divide the whole architecture into two layers.

·       Kernel Mode

        HTTP.SYS

·       User Mode

        Web Admin Service

        Virtual Directory

        Application Pool

As per the above diagram, IIS has two modes, Kernel and User. HTTP.SYS is the heart of kernel mode which accepts raw requests from the client and pass it to a particular application pool. Below are the steps of IIS request processing.

1.     Client requests for a page from the browser by hitting the site URL.

2.     Request comes to kernel level. HTTP.SYS catches the requests and creates a separate queue for each and every application pool.

Note: Whenever we create an application pool, IIS automatically registers the pool with HTTP.SYS to identify it during request processing.

Then HTTP.SYS forwards the request to the Application Pool.

3.     A request coming to the application pool means the worker process (w3wp.exe) starts action by loading the ISAPI Filter.

4.     The HttpRuntime creates a pool of HttpApplication objects.

5.     The request passes through the HTTP Pipeline.

6.     HTTP Modules are executed against the request until the request hits the ASP.NET page HTTP Handler.

7.     Once the request leaves the HTTP Pipeline, the Page life cycle starts.

Deploying Your Web Sites on IIS

Creating a Virtual Directory

There are various way to host a web application on IIS. Visual Studio has some inbuilt features to host and create a virtual directory on IIS directly. Here is one of my articles on hosting a site on IIS from Visual Studio. But in this section, Idiscuss the basic steps for creating a virtual directory.

First, right click on Default web sites > New > Virtual Directory.

By selecting “Virtual Directory…”, the virtual directory creation wizard will start. Click on “Next”.

Give the “Alias” name and proceed for “Next”. The alias name is your virtual directory name.

As its name implies, a “virtual directory” does not contain any physical file. We need to define the physical file path that it will refer to. We have to browse the physical path over here

Now based on your requirements, you can select the check boxes and click on “Next”. Generally, we select only the “Read” option.

Below is a list of permissions that we can use:

·       Read: It is the most basic and is mandatory to access webpages of your application.

·       Run Scripts: It is required for ASPX pages, not for static HTML pages because ASPX pages need more permissions so they could conceivably perform operations.

·       Execute: This allows the user to run an ordinary executable file or CGI application. This can be a security risk so only allow when it is really needed.

·       Write: It allows to add, modify, or remove files from the web server. This should never be allowed.

·       Browse: This allows one to retrieve a full list of files in a virtual directory even if the contents of the files are restricted. It is generally disabled.

You are done! The virtual directory has been created successfully. You will get a final message. Click on “Finish” to close the window and move forward.

There are other alternative options that you can use for creating a virtual directory.

1.     Copy the physical directory to the wwwroot folder.

2.     Physical Folder Properties > Web Sharing.

Configure Virtual Directory

The items listed below are very important for the configuration of any web application.

·       Virtual Directory

·       Documents

·       Documents

·       ASP.NET

·       Directory Security

·       Custom Errors

I have explained each of them step by step. Apart from them, a Virtual Directory can have settings like BITS Server Extension, HTTP Header, etc. I haven’t covered those in this article. Let us start with the “Virtual Directory” tab.

Virtual Directory

This is the most important configuration section for a virtual directory. To open this tab, we need to select the newly created virtual directory.

Right click on it > Properties. The below screen will come up:

Here we can change the local path (physical path). Before looking into other stuff, first look into the “Application Settings” section. It seems the application name is disabled. So first we need to click the “Create” button, which will enable the rest of the settings. Check the below image.

Here we can change the execution setting and application pool name. Choosing “None” for Execute Permission will restrict the access to the web site. Now we will move to the “Documents” tab.

Documents

The Documents tab is used to set the default page of your web application. We can add or remove the page name in this section. To configure, we have to move to the “Documents” tab.

This is useful when you want to access the site directly with the virtual directory name. For example, if your virtual directory name is “mywebsite” and your home page name is “home.aspx“, then you can access the page as follows:

but if you define home.aspx in the Documents section, you need to only use this at the address bar to access the site:

Directory Security

Directory security enables all kinds of security access for your web application. For directory, we need to move to the “Directory Security” tab.

Click on the “Edit” button to modify the directory security settings. After clicking on the Edit button, the below screen will come up.

Below are the commonly used IIS security settings:

·       Anonymous

·       Integrated Windows Authentication

·       Basic Authentication

·       Digest Authentication

Anonymous

Anonymous authentication means the site is accessible to all. This is the default authentication mode for any site that is hosted on IIS, and it runs under the “IUSR_[ServerName]” account. We can change it by clicking on the “Browse” button.

Integrated Windows Authentication

This authentication mode is generally used for Intranet sites. Users are authenticated from the Active Directory. Integrated Windows authentication is also known as NTLM authentication. If browser settings automatically login for trusted sites for Windows authentication then the site will be logged in automatically with the Windows user credentials.

Basic Authentication

This is supported by all browsers and is a part of the HTTP standard. This shows a login dialog control which accepts the user name and password. The user ID and password are passed to IIS to authenticate the user from the Windows credentials.

Digest Authentication

The disadvantages of Basic authentication mode is that it sends a password as plain text. Digest authentication does almost the same thing as basic authentication but it sends the “hash” of the password rather than sending plain text.

Integrated Windows, Basic Authentication, and Digest Authentication use Active Directory to authenticate the user.

Note: There are many things related with IIS and ASP.NET Security configuration. I am not covering all these in detail. I am just giving a brief overview so that you are comfortable with all this stuff.

For configuring SSL, please read the reference link that I have provided in the References section.

Custom Errors

The Custom Errors tab allows us to specify the error page that will be displayed for any specific type of HTTP Error.

Directory security settings

We can also customize the setting at our application level by configuring the web.config settings or changing the htm file path by clicking on the “Edit” button.

This is all about the basic overview of creation of virtual directories and setting up. Hope you are now comfortable with all this stuff.

Application Pool

Application pool is the heart of a website. An Application Pool can contain multiple web sites. Application pools are used to separate sets of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability. The worker process serves as the process boundary that separates each application pool so that when a worker process or application is having an issue or recycles, other applications or worker processes are not affected.

How to Create an Application Pool?

Application pool creation in IIS 6.0 is a very simple task. There are two different ways by which we can create an application pool. There is a pre-defined application pool available in IIS 6.0, called “DefaultApplicationPool”. Below are the two ways to create an application pool:

·       Create New Application Pool

·       Create From Existing Configuration File

Create a New Application Pool

First of all, we need to open the IIS Configuration Manager. Then right click on Application Pool and go to New > Application Pool.

The below screen will appear, where we need to mention the application pool name.

When we create a new application pool, we can use the default application setting for it. The selection of “Default Settings” means by default the application pool setting will be the same as the IIS default settings. If we want to use the configuration of an existing application pool, we need to select the section option “Use existing application pool as template”. Selecting this option will enable the application pool name dropdown.

If we select an existing application pool as a template, the newly created application pool should have the same configuration of the template application pool. This reduces the time for application pool configuration.

That is all about creating a new application pool. Now let us have a look at the creation of an application pool from an existing XML configuration file.

Configure Application Pool Properties

This is one of the most important tasks for web server configuration and this is important when we are hosting on a production server. As I have already discussed, the application pool is the heart of any web application hosted on IIS. We need to know each and every configuration of the application pool. To start configuration, we need to go to the Properties of the application pool.

We need to configure the following things in the application pool:

·       Recycling

·       Performance

·       Health

·       Identity

Recycling

Recycling the application pool means recycling the worker process (w3wp.exe) and the memory used for the web application. It is a very good practice to recycle the worker process periodically, which wll keep the application running smooth. There are two types of recycling related with the application pool:

·       Recycling Worker Process – Predefined settings

·       Recycling Worker Process – Based on memory

Recycling Worker Process – Predefined Settings

Worker process recycling is the replacing of the instance of the application in memory. IIS 6.0 can automatically recycle worker processes by restarting the worker processes that are assigned to an application pool and associated with websites. This improves web site performance and keeps web sites up and running smoothly.

Application pool recycling- Worker process

There are three types of settings available for recycling worker processes:

·       In minutes

·       Number of requests

·       At a given time

Recycle Worker Process (In Minutes)

We can set a specific time period after which a worker process will be recycled. IIS will take care of all the current running requests.

Recycle Worker Process (Number of Requests)

We can configure an application with a given number of requests. Once IIS reaches that limit, the worker process will be recycled automatically.

Recycle Worker Process (In Minutes)

If we want to recycle the worker process at any given time, we can do that configuration on IIS. We can also set multiple times for this.

Application pool recycling – Worker process: Time setting

Recycling Worker Process – Based on Memory

Server memory is a big concern for any web application. Sometimes we need to clean up a worker process based on the memory consumed by it. There are two types of settings that we can configure in the application pool to recycle a worker process based on memory consumption. These are:

·       Maximum virtual memory used

·       Maximum used memory

At any time, if the worker process consumes the specified memory (at memory recycling settings), it will be recycled automatically.

What Happens During Application Pool Recycling

This is quite an interesting question. Based on the above settings, an application pool can be recycled any time. So what happens to the users who are accessing the site at that time? We do not need to worry about that. This process is transparent from the client. When you recycle an application pool, HTTP.SYS holds onto the client connection in kernel mode while the user mode worker process recycles. After the process recycles, HTTP.SYS transparently routes the new requests to the new worker process.

Performance

Moving to the Performance tab in the Properties dialog box results in the following output.

Application pool performance

To improve the performance of a web application, we can setup the performance settings of the application pool. We can set the shut down time of the worker process based on the ideal time. The worker process will be shut down at a given time period if it is ideal. Whenever a new requests comes, it will live again. Another important thing for improving the performance is “Web Garden”.

Web Garden
Overview of Web Garden

By default, each application pool runs with a single worker process (W3Wp.exe). We can assign multiple worker processes with a single application pool. An application pool with multiple worker processes is called a Web Garden. Many worker processes with the same application pool can sometimes provide better throughput performance and application response time. And each worker process should have its own thread and memory space.

Web Garden (Application pool with multiple worker processes)

As Shown in the picture, in IIS Server, there may be multiple application pools and each application pool has at least a single worker process. A Web Garden should contain multiple worker processes.

There are certain restrictions in using a Web Garden with your web application. If we use Session Mode as “in proc”, our application will not work correctly because the Session will be handled by a different worker process. To avoid this, we should use Session Mode as “out proc” and we can use “Session State Server” or “SQL-Server Session State”.

How to Create a Web Garden?

We need to increase the number of worker processes on the Performance tab.

Main advantage: The worker processes in a web garden share the requests that arrive for that particular application pool. If a worker process fails, another worker process can continue processing the requests.

Health

Now we move to the “Health” tab. When wel select the “Health” tab, it will show the following screen:

Health monitoring setting

IIS provides a couple of settings to improve the health of an application pool. There are also a few settings for measuring the worker process health. These are:

·       Enable Pinging

·       Enable Rapid-fail protection

·       Startup time limit

·       Shutdown time limit

Enable Pinging

This property specifies whether the WWW Publishing Service should periodically monitor the health of a worker process. Checking this option indicates to the WWW service to monitor the worker processes to ensure that worker processes are running and healthy. By default, it sets to 30s. This is also needed to check if a service is staying ideal or not. If it is ideal it can be shutdown until the next request comes. The Windows Activation Process maintains all this stuff.

Enable Rapid-fail Protection

When enabling Rapid Fail Protection, the application pool is shut down if there are a specified number of worker process crashing within a specified time period. When this happens, the WWW Publishing Service puts all applications in the application pool “out of service”.

Failure Count: The default value for failure count is 5 minutes. This property specifies the maximum number of failures allowed within the number of minutes specified by the “Time Period” property before the application pool is shut down by Rapid Fail Protection. If the number of failure is more than the specified in a given time, the application pool should be put on “out of service mode”.

Time period: This property specifies the number of minutes before the failure count for a process is reset. By default, it is set to 5 minutes.

Startup time limit

The Start up time limit property specifies the amount of time that the WWW Publishing Service should wait for a worker process to finish starting up and reporting to the WWW Service. In general it means the time taken to start a worker process.

Shutdown time limit

This is the shutdown time for a worker process. This is the time required to execute all old running worker process requests before it shuts down during recycle time.

Identity

This is the last and final setting for an application pool. An application pool has three types of identity: “Network Service” is the default Identify. “defaultappPool” also runs under the “Network Service” Identity. Below are the listed application pool identities with description:

IdentityDescription
LocalSystemA built-in account that has administrative privileges on the server. It can access both local and remote resources. For any kind accessing of server files or resources, we have to set the Identity of the application pool to Local System.
LocalServicesBuilt-in account has privileges of an authenticated local user account. It does not have any network access permission.
NetworkServicesThis is the default Identity of an application pool. NetworkServices has privileges of an authenticated local user account.

Navigating to the Identity tab will show the following screen:

We can also configure the application pool under a given user account. For that, we need to select the “Configurable” option on “Identity” tab.

This is all about the application pool. Hope now you have a very good understanding on what application pool is, how to create and configure the application pool.

Q: You are using a file upload control in your web application and it is working fine on Visual Studio but when you host the same code on IIS, it is not working. This is a very common problem in web hosting when file upload is involved.

A: When a web application runs under Visual Studio – ASP.NET engine integrated with visual studio takes care of all the executions. And this engine has sufficient rights so that it can write data on your disk. But when you host the site on IIS, as I have already mentioned, it runs under the “Network Services” Identity, which has very minimum rights on your system. The user can only have read access on the site. So for resolving file upload issues, you need to change the Identity of the application pool from “Network Service” to “Local System”. Local System identity means the client can have write access on your hard drive. This will resolve your issue of file uploading on the server.

Thanks.

Virtual Entity In D365

A virtual entity is a custom entity in Dynamics 365 that has fields containing data from an external data source. Virtual entities appear in Dynamics 365 to users as regular Dynamics 365 entity records, but contain data that is sourced from an external database, such as an Azure SQL Database. Records based on virtual entities are available in all Dynamics 365 clients including custom clients developed using the Dynamics 365 Customer Engagement Web Services.

Steps to configure:

 1) Configure CRM based on available Odata webAPI. For this step, there is one Odata API Available over the net. http://services.odata.org/V4/OData/OData.svc/

To start with, you first need to create Virtual Entity Data source. Direction setting ->Administration->Virtual Entity Administration

Post this configuration, you need to create virtual entity with below configurations.

Steps require to create virtual entity

a) Mark check box virtual entity.

b) Select the Data source which is created in above steps.

c) There is a field know as External Name and External Collection Name. So we are implementing for Entity Advertisement. If you browse API, You will see collection name as Advertisements and external name as Advertisement.

If you can see the above snapshot, Entity know as Person has a id of type as Int which will not be able to sync with CRM as CRM only understands the Id of type Guid(visible in Entity Advertisement).

d) Next process is to Create fields and map to the fields specified in API.

There are two out of Box field Id and Name which you can directly map to ID and Name of API(Copy from API Metadata)

For Field AirDate, we can create one more field of type Date and Time and map to AirDate field of API.(Refer to below snapshot.)

Once publish, the above entity view come like below.

Some of the drawback of virtual entity are:

a) Entity are organization Owned. So no Security Role can be played.

b) Only privileges you have is to Reads, Append and Append to.

c) So as the form is in read Only mode – No update or delete of record can perform.

2) To Create OData Api, you can follow the step by step process of below given URI

http://www.c-sharpcorner.com/article/virtual-entity-new-way-of-integration-part-22/

It also contains source code, which you can download to refer.

Things to remember:

a) The Api need to be deployed, on Azure. As Dynamics 365 doesn’t understand Localhost Api.

b) You need to install Odata dll in the API, as the application doesn’t come with prepackage dll.

Just go to Tool ->Nuget pakage manager and run below command: Install-Package Microsoft.AspNet.OData

c) Do add the OData v4 scaffolding over the API as CRM doesn’t understand the version V2. To do that Go Tools ->Extension and Updates->Install Odata v4 Scaffolding.

Thanks.

PartyList

PartyList : This is a  data type available in MS crm.

It  is almost  a lookup  that can have references to more than one records of an entity for a single field.

A partylist  has certain attributes like   name, id, type,typename etc.

To retrieve values by jscript: var partylistItem = new Array; //get the items/values in a field named”resources”partylistItem  = Xrm.Page.getAttribute(“resources”).getValue(); Thus now the array  holds all the items/record  referenced for a single field .we may  have a  loop through this array  to retrieve the values like, partylistItem.length – gives how many records are referenced.partylistItem[0].id – the guid of the item.

To set values by  jscript :To set  values we also  need to  get an  array.var partlistset= new Array();
partlistset[0] = new Object();
partlistset[0].id = id; // provide a guid type value
partlistset[0].name = name; // provide a suitable name
partlistset[0].entityType = entityType; // provide the entity  name  of the item  ie account/ contact etc .
Xrm.Page.getAttribute(“resource”).setValue(partlistset);


The following table lists the activity party types that are supported for each activity, and the corresponding activity properties to specify those activity party types.

Activity entity nameSupported activity party typeActivity attributeAppointmentOptionalAttendeeOrganizerRequiredAttendeeAppointment.OptionalAttendeesAppointment.OrganizerAppointment.RequiredAttendeesCampaignActivityPartnerSenderCampaignActivity.PartnersCampaignActivity.FromCampaignResponseCustomerPartnerFromCampaignResponse.CustomerCampaignResponse.PartnerCampaignResponse.FromEmailBccRecipientCcRecipientSenderToRecipientEmail.BccEmail.CcEmail.FromEmail.ToFaxSenderToRecipientFax.FromFax.ToLetterBccRecipientSenderToRecipientLetter.BccLetter.FromLetter.ToPhoneCallSenderToRecipientPhoneCall.FromPhoneCall.ToRecurringAppointmentMasterOptionalAttendeeOrganizerRequiredAttendeeRecurringAppointmentMaster.OptionalAttendeesRecurringAppointmentMaster.OrganizerRecurringAppointmentMaster.RequiredAttendeesServiceAppointmentCustomerResourceServiceAppointment.CustomersServiceAppointment.Resources 
Thanks.

Get and Set lookup value using javascript in CRM 2011

In this article , I am going to explain how to set and get CRM lookup attribute value using javascript

Get a lookup value

var lookup = new Array();

lookup = Xrm.Page.getAttribute(“attributename”).getValue();

if (lookup != null) {

    var name = lookup[0].name;

    var id = lookup[0].id;

    var entityType = lookup[0].entityType;

}

Set a lookup value

var lookup = new Array();

lookup[0] = new Object();

lookup[0].id = recorid;

lookup[0].name = recordname;

lookup[0].entityType = entityname;

Xrm.Page.getAttribute(“attributename”).setValue(lookup);

Alternate method to set lookup value

Xrm.Page.getAttribute(“attributename”).setValue([{ id: recorid, name: recordname, entityType: entityname}]);

Thanks.

Query FetchXml thorugh Soap Request

FetchXml can be query using Soap call. There are plenty of libraries available that you can use to make this task work but i will explain you how to make it own library.

There are three steps to that, which are as follows:

1) Build your XML and Encode them in XML Document object, for example

 var fetchQuery=”<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=\”account\” from=\”accountid\” to=\”parentaccountid\” alias=\”ad\”><filter type=\”and\”><condition attribute=\”accountid\” operator=\”eq\” uiname=\”A. Datum Corporation (sample)\” uitype=\”account\” value=\”{A9D32F2F-58D4-E411-

80F0-C4346BAC094C}\” /></filter></link-entity></entity></fetch>”;

    var encodedFetchQuery = _xmlEncode(fetchQuery);

 function _xmlEncode(strInput) {

  var c;

  var XmlEncode = ”;

  if (strInput == null) {

   return null;

  }

  if (strInput == ”) {

   return ”;

  }

  for (var cnt = 0; cnt < strInput.length; cnt++) {

   c = strInput.charCodeAt(cnt);

   if (((c > 96) && (c < 123)) ||

            ((c > 64) && (c < 91)) ||

            (c == 32) ||

            ((c > 47) && (c < 58)) ||

            (c == 46) ||

            (c == 44) ||

            (c == 45) ||

            (c == 95)) {

    XmlEncode = XmlEncode + String.fromCharCode(c);

   }

   else {

    XmlEncode = XmlEncode + ‘&#’ + c + ‘;’;

   }

  }

  return XmlEncode;

 }

2) Make a Soap Envelop, for example

var request = [

        ‘<s:Envelope xmlns:s=”http://schemas.xmlsoap.org/soap/envelope/“><

s:Body>’,

            ‘<Execute xmlns=”http://schemas.microsoft.com/xrm/2011/Contracts/Services” xmlns:i=”http://www.w3.org/2001/XMLSchema-instance” >’,

                ‘<request i:type=”a:RetrieveMultipleRequest” xmlns:a=”http://schemas.microsoft.com/xrm/2011/Contracts“>’,

                    ‘<a:Parameters xmlns:b=”http://schemas.datacontract.org/2004/07/System.Collections.Generic“>’,

                        ‘<a:KeyValuePairOfstringanyType>’,

                            ‘<b:key>Query</b:key>’,

                            ‘<b:value i:type=”a:FetchExpression”>’,

                                ‘<a:Query>’, encodedFetchQuery , ‘</a:Query>’,

                            ‘</b:value>’,

                        ‘</a:KeyValuePairOfstringanyType>’,

                    ‘</a:Parameters>’,

                    ‘<a:RequestId i:nil=”true”/>’,

                    ‘<a:RequestName>RetrieveMultiple</a:RequestName>’,

                ‘</request>’,

            ‘</Execute>’,

        ‘</s:Body></s:Envelope>’

    ].join(“”);

3) Make a soap Request, for example

//Synchronous XMLHttpRequest to retrieve contact records

    var req = new XMLHttpRequest();

    req.open(“POST”, encodeURI(Xrm.Page.context.

getClientUrl() + “/XRMServices/2011/Organization.svc/web”), false);

    try { req.responseType = ‘msxml-document’ } catch (e) { }

    req.setRequestHeader(“Accept”, “application/xml, text/xml, */*”);

    req.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);

    req.setRequestHeader(“SOAPAction”,     “http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute“);  

      req.onreadystatechange = function () {

        if (this.readyState == 4 /* complete */) {

            req.onreadystatechange = null; //Addresses potential memory leak issue with IE

            if (this.status == 200  /*success*/) {

                var doc = req.responseXML;

                successCallback(doc);

            }

            else {

                errorCallback(accountId);

            }

        }

    }

    req.send(request);

You will get your output in  req.responseXML.xml in XML format. its your choice how you wish to use it.

Thanks.

Calling Actions through java script

Action is a new and very powerful feature of Microsoft Dynamics CRM. Action can be called through Soap Call which goes like following some steps which goes like this.

            1) You are require create soap envelop.

            2) calling soap service.

Complete Js to call your Action

function CallActionFromJavaScript() {

   debugger;

    var entityId = Xrm.Page.data.entity.getId();;

    var entityName = Entity name;

    var requestName = Action Name;

    ExecuteActionCreateProject(entityId, entityName, requestName);

}

function ExecuteActionCreateProject(EntityId,entityId, entityName, requestName) {

    // Creating the request XML for calling the Action

    var requestXML = “”

    requestXML += “<s:Envelope xmlns:s=\”http://schemas.xmlsoap.org/soap/envelope/\”>”;

    requestXML += ”  <s:Body>”;

    requestXML += ”    <Execute xmlns=\”http://schemas.microsoft.com/xrm/2011/Contracts/Services\” xmlns:i=\”http://www.w3.org/2001/XMLSchema-instance\”>”;

    requestXML += ”      <request xmlns:a=\”http://schemas.microsoft.com/xrm/2011/Contracts\”>”;

    requestXML += ”        <a:Parameters xmlns:b=\”http://schemas.datacontract.org/2004/07/System.Collections.Generic\”>”;

    requestXML += ”          <a:KeyValuePairOfstringanyType>”;

    requestXML += ”            <b:key>Target</b:key>”;

    requestXML += ”            <b:value i:type=\”a:EntityReference\”>”;

    requestXML += ”              <a:Id>”+entityId+”</a:Id>”;

    requestXML += ”              <a:LogicalName>”+entityName+”</a:LogicalName>”;

    requestXML += ”              <a:Name i:nil=\”true\”>”;

    requestXML += ”            </a:Name></b:value>”;

    requestXML += ”          </a:KeyValuePairOfstringanyType>”;

    requestXML += ”          <a:KeyValuePairOfstringanyType>”;

    requestXML += ”            <b:key>EntityId</b:key>”;

    requestXML += ”            <b:value i:type=\”c:string\” xmlns:c=\”http://www.w3.org/2001/XMLSchema\”>”+EntityId+”</b:value>”;

    requestXML += ”          </a:KeyValuePairOfstringanyType>”;

    requestXML += ”        </a:Parameters>”;

    requestXML += ”        <a:RequestId i:nil=\”true\”>”;

    requestXML += ”         </a:RequestId>”;

    requestXML += ”        <a:RequestName>”+requestName+”</a:RequestName>”;

    requestXML += ”      </request>”;

    requestXML += ”    </Execute>”;

    requestXML += ”  </s:Body>”;

    requestXML += “</s:Envelope>”;

    var req = new XMLHttpRequest();

    req.open(“POST”, GetClientUrl(), false)

    req.setRequestHeader(“Accept”, “application/xml, text/xml, */*”);

    req.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);

    req.setRequestHeader(“SOAPAction”,     “http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute&#8221;);

    req.send(requestXML);

    //Get the Response from the CRM Execute method

    //var response = req.responseXML.xml;

    req.onerror = function (e) {

        alert(req.statusText);

    };

    if (req.status === 200) {

        alert(req.responseText);

    }

}

function GetClientUrl() {

    if (typeof Xrm.Page.context == “object”) {

        clientUrl = Xrm.Page.context.getClientUrl();

    }

    var ServicePath = “/XRMServices/2011/Organization.svc/web”;

    return clientUrl + ServicePath;

}

Thanks.

Web Resource creation through SDK message

For a web resource creation through SDK, i referred one msdn page click. In this page they read a text file convert them into binary content and then converted into base64 string.

In my case i had HTML on CRM form Fields, so i fetch the field in Plugin and converted its content into binary format and finally into base64 string. the code for which goes as follows

               string JSContent = TileConfiguration.Attributes[“livetile_jscontent”].ToString();

                string HTMLContent = TileConfiguration.Attributes[“livetile_htmlcontent”].ToString();

                var bytes = Encoding.UTF8.GetBytes(JSContent + HTMLContent);

                var base64 = Convert.ToBase64String(bytes);

                //Set the Web Resource properties

                WebResource wr = new WebResource

                {

                    Content = base64,

                    DisplayName = “Test1”,

                    Description =”Sample Test”,

                    Name = “livetile_” +”test1″,

                    LogicalName = WebResource.EntityLogicalName,

                   //you can specify type for web resource format

                   Webpage (HTML).htm, .html1
                    Style Sheet (CSS).css2
                    Script (JScript).js3
                    Data (XML).xml4
                    Image (PNG).png5
                    Image (JPG).jpg6
                    Image (GIF).gif7
                    Silverlight (XAP).xap8
                   StyleSheet (XSL).xsl, .xslt9
                     Image (ICO).ico10

                    WebResourceType = new OptionSetValue(1)

                };

                CreateRequest cr = new CreateRequest

                {

                    Target = wr

                };

                //Set the SolutionUniqueName optional parameter so the Web Resources will be

                // created in the context of a specific solution.

                //cr.Parameters.Add(“SolutionUniqueName”, _ImportWebResourcesSolutionUniqueName);

                CreateResponse cresp = (CreateResponse)service.Execute(cr);

To update the same web resource, You can do it using UpdateRequest, the code for which goes like below

                WebResource wr = new WebResource

                {

                   //Just pass the web resource ID

                    Id = new Guid(TileConfiguration.Attributes[“livetile_webresourceid”].ToString()),

                    Content = base64,

                    DisplayName = “Test1”,

                    Description = “Sample Test”,

                    Name = “livetile_” + “test1”,

                    LogicalName = WebResource.EntityLogicalName,

                    WebResourceType = new OptionSetValue(1)

                };

                UpdateRequest up = new UpdateRequest

                {

                    Target = wr

                };

                service.Execute(up);

Thanks.