Sam's Microsoft Dynamics 365 Blog

Tuesday 23 October 2018

Display SharePoint Documents on Form in MS Dynamics CRM


Here’s an easy way to embed the SharePoint document window you’d normally get by navigating to “Documents” under related records, which includes all the native functionality like search, upload, 
This might fall under the area of semi/not supported but if it happens to break one day you won’t have invested too much.

You’ll need to create an iFrame for the SharePoint content, probably within it’s own tab. Remember what you name the iFrame as you’ll need to modify with that value. 

When configuring the iFrame...

On the General tab:

  • Restrict cross-frame scripting… to Unchecked
On the Formatting tab:
  • Number of Rows to 34
  • Scrolling to Never
  • Display Border to Unchecked
You could set the rows to a lower number, you’d just end up with a scrollbar despite the never scroll setting. 

Take this code and update the iFrame name and add it to the form. Call SetDocumentFrame during the form’s OnLoad event.







function SetDocumentiFrame() {

    try {
        // Get Subgrid URL
        var url = Xrm.Page.context.getClientUrl() +
            "/userdefined/areas.aspx?formid=ab44efca-df12-432e-a74a-83de61c3f3e9&inlineEdit=1&navItemName=Documents&oId=%7b" +
            Xrm.Page.data.entity.getId().replace("{", "").replace("}", "") + "%7d&oType=" +
            Xrm.Page.context.getQueryStringParameters().etc +
            "&pagemode=iframe&rof=true&security=852023&tabSet=areaSPDocuments&theme=Outlook15White";

        ///Append subgrid in Iframe
        Xrm.Page.getControl("IFRAME_SharePointDocuments").setSrc(url);
    }
    catch (err) {

    }


}


If you’re doing this, you might also consider turning on the option to auto-create SharePoint folders. Otherwise people are going to be getting prompted. You can find this under:

Settings => Document Management => Document Management Settings and then it’s on the 2nd page. 





With any luck, you’ll end up with something like this:








Wednesday 3 October 2018

Display Image of Product in Dynamics Portal


In this blog, i am going to discuss about “Image” type attribute/field display in Dynamics Portal. Here we have an Image for a Product, we will display this image on Dynamics Portal.





I am creating a Web Template with name Display_image_Product.




Put below code in Source.

// Get Product Id from URL and assign it in pid
 {% assign pid = request.params['id'] %}
   {% fetchxml my_query %}
    <fetch version="1.0" mapping="logical">
    <entity name="product">
      <attribute name="name" />
      <attribute name="productid" />
      <attribute name="entityimage" />
      <attribute name="entityimage_url" />
<filter type="and">
<condition attribute="productid" value="{{ pid }}" uitype="product" operator="eq"/>
</filter>
     </entity>
  </fetch>
{% endfetchxml %}

 {% for result in my_query.results.entities %}
<img data-entityimage="{{ result.entityimage | join: ',' }}" />

<script type="text/javascript">

function toBase64(str) {
if (!str) return null;
var uarr = new Uint8Array(str.split(',').map(function (x) { return parseInt(x); }));
return btoa(String.fromCharCode.apply(null, uarr));
}

// Find any entity images and convert the byte string to base64
window.addEventListener('load', function () {
document.querySelectorAll('img[data-entityimage]').forEach(function (img) {
var data = img.dataset && img.dataset.entityimage;
var base64data = data ? toBase64(data) : null;
if (base64data) {
img.src = 'data:image/jpeg;base64,' + base64data;
}
});
});
</script>
          
 {% endfor %}


In above code it will get a Product Guid and will fetch its related image.



Here i have used in my Portal and it looks like:-


Wednesday 26 September 2018

Create Ads in Dynamics Portal


Create Ads in Dynamics Portal

Here is an OOB feature to Display Ads on Portal in Dynamics Portals. Here we can create text or image-based ads and have they run in multiple placements In Portal. We can choose release and expiration dates for time-sensitive, scheduled content. Ads can be hyperlinked to any destination and open in the current window or a new window. Advertisements are displayed in the portal via two Dynamics 365 entities: The Ad Placement entity and associated Ad entity.

1.      Create an Ad

Portal ==> Ads ==> New

a.       Put a Name of Ad e.g. Product Advertisment
b.      Select Website e.g. Partner Portal
c.       Publishing State as Published
d.      Also can select Release Date and Expiration Date
e.       Redirect URL to redirect after click on Ad
f.        Put your Content in Content Tab or put image in Image Detail Tab or we can put both.
g.      Save it.





2.      Create an Ad Placement

Portal ==> Ad Placement ==> New

a.       Put a Name of Ad e.g. Product Advertisment
b.      Select Website e.g. Partner Portal
c.       Select Ad inside Ads Subgrid e.g. Product Advertisment
d.      Save it.




                3.   Include created Ad in Web Page

Portal ==> Web Pages ==> Select a Web Page

a.       Inside Content Tab of Web Page (e.g. Product New) Include  an Ad


{% include 'ad' ad_name:'Product Advertisment' %}




Now we can see Ad on the Portal, as I have added on Product entity List



Monday 17 September 2018

Send Email on birthday in MS Dynamics CRM Using Azure Function App


Create an Azure Function App as explained in below steps:-

Open Visual Studio 2017, Create a new Project then Select Cloud tab and then select Azure Functions.
New Project => Cloud => Azure Functions
Name it and then click Ok.



Now select:-

a.       .Net Framework
b.      Http trigger
c.       Storage Account(AzureWebJobsStorage) :  Storage Emulator
d.      Schedule: 0 */5 * * * *


After click on Ok it will create a code. In this code it will execute every day at 8:30 AM, and print a log.  Code will look like as shown in below screenshot:


Now Run it locally. Then a Console window will open Also opens a Windows security Alert then Allow Access , looks like as shown in below screenshot:-



It will execute. Also we can debug it.


Now we can check log inside console, As shown in below screenshot.



Now we are going to put below code of sending emails, also putting TimerTrigger as 0 30 8 * * * (it will execute every day at 8: 30 AM)

Main Run method:-
var connectionString = ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString; ;
            // Connect to the CRM web service using a connection string.
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //need to add ref System.Net
            CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);
            // Cast the proxy client to the IOrganizationService interface.
            IOrganizationService _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

            var query = new QueryExpression("contact");

            ConditionExpression condition1 = new ConditionExpression();
            condition1.AttributeName = "birthdate";
            condition1.Operator = ConditionOperator.Equal;
            condition1.Values.Add(DateTime.Now);

            FilterExpression contactfilter = new FilterExpression();
            contactfilter.Conditions.Add(condition1);

           query.ColumnSet = new ColumnSet(true);
            query.Criteria.AddFilter(contactfilter);

            EntityCollection TodayBirthdayReq = _orgService.RetrieveMultiple(query);
            foreach (Entity contact in TodayBirthdayReq.Entities)
            {
                if (contact.Attributes.Contains("emailaddress1") && contact.Attributes.Contains("fullname"))
                {
                    fnsendBirthdayEmail(contact.Attributes["fullname"].ToString(), contact.Attributes["emailaddress1"].ToString());
                }
            }



fnsendBirthdayEmail:-

        public static void fnsendBirthdayEmail(string fullname, string ContactEmail)
        {
            string myEmail = "sam@gmail.com";
            string myPassword = "password";
            string subject = "Birthday Wish!";
            string body = "Dear " + fullname + " wish you a very happy birthday.!!!";
            SmtpClient client = new SmtpClient();
            client.Port = 587;
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true;
            client.Timeout = 10000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential(myEmail, myPassword);
            MailMessage _MailMessage = new MailMessage(myEmail, ContactEmail, subject, body);
            _MailMessage.BodyEncoding = UTF8Encoding.UTF8;
            _MailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            client.Send(_MailMessage);
        }


Now Publish it:-

1.       Click on Publish.


2.       Select Create New and then OK


3.       Put App Name and other field values as shown in below screenshot and then click on Create.


4.       Now we can check the function app URL in Site URL.


5.       After completion we can check in Azure.



Let check its working:-



Now let’s check email.




Web Resource vs PCF vs Canvas App - which of the one is used?

While started working on specific Business Requirements related to custom layout, there is a always common question that "where to star...