Dev Dex

developer goals

Add more than one Entity Forms on Web Page in Dynamics 365/Powerapps Portal

Problem: one of my clients had requirements to redirect portal user to different entity form if they are primary contact. Thought hmm it is quite straight forward task and i quickly created a web template and added 2 entity forms with name using web template liquid tag on the same web template. Bingo! got the nice Red error “An entry with the same key already exists“.

Honestly, had come across this error before and after spending some more time to find whats going on. I realised, there is only one tag which was twice on the web template “Entity Form“, to make sure this tag is casuing a problem, i created another web templates and added entity forms one by one and was able replicate the issue!

Research: when i had this issue, i was under the impression that i should easily be able to find solution from community or blogs. However, i learnt “It is not possible to add more than one Entity Form on the Web page”. It actually made me ponder, there must be solution. So, i decided to test different approaches to see if any of them work because as a developer never say “No” they make it happen one way or another lol.

Solution: This solution will help to add two or more entity forms on the dynamics 365 portal or Powerapps portal web pages

I created main web template (quite basic)

1. Contact Web Template (Code)

{% extends 'Layout 1 Column' %}
{% block main %}
{% include 'Page Copy' %}

{% include 'Contact Entity Forms Web Template' %}

{% endblock %}

in the Contact Web Template I included another Web Template, to check if the logged portal user is primary contact.

2. Contact Entity Forms Web Template (Code)

{% if {{user.isPrimaryContact}} -%}
    {% include 'Primary Contact Route Template' %}
{% else -%}
    {% include 'Secondary Contact Route Template' %}
{% endif -%}

If user is a primary contact then i have included primary route Contact template

3. Primary Contact Route Template (Code)

{% entityform name: 'Primary Contact Route Entity Form' %}

and if portal user is secondary contact then inlcude other web template

4. Secondary Contact Route Template (Code)

{% entityform name: 'Secondary Contact Route Entity Form' %}

Basically one main web template is calling another web template as funtion, which has a condition based on that other web templates which contacts entity form are included in the 2nd web template, this simple solution worked Perfectly for me.

I’m not claiming this is best solution, there could be room to improvement. I hope it helps.

Severity Code Description Project File Line Suppression State Error Cannot open ” The requested operation cannot be performed on a file with a user-mapped section open.

Sometimes visual studio throw this error because it cannot open dll file to write. I fixed this issue by deleting the dll file in the debug folder. You might not be able to delete the file by going to the debug folder there it has to be deleted from Command Prompt forcefully.

  • Open Command Prompt in Admin mode
  • Navigate to debug folder like cd ‘c:\my source code\project\bin\debug\’
  • then del /f fillname

Thank you

Get Option Set Value by Option Set Text in CRM on-prem /Online

To read crm option set information from the CRM, CRM matadata call need to made and it will bring the information on the based of following input attributes. below input attributes are showing test data.
string entityName = "contact";
string fieldName = "title"; // could be any optionset entity attribute like agegroug etc
string optionSetText = "Mr"
pass these values to given method and it will return optionset value of the selected option set.
GetOptionSetValueByText(entityName , attributeName, attributeValue);

public static int? GetOptionSetValueByText(string entityName, string fieldName, string optionSetText)
 {
 var retrieveAttributeRequest = new RetrieveAttributeRequest
 {
 EntityLogicalName = entityName,
 LogicalName = fieldName,
 RetrieveAsIfPublished = true
 };

 var retrieveAttributeResponse = (RetrieveAttributeResponse)_orgService.Execute(retrieveAttributeRequest);
 var attributeMetadataList = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

 var optionSetInfo = (from optionSetDetail in attributeMetadataList.OptionSet.Options
 from labelInfo in optionSetDetail.Label.LocalizedLabels.Where(label => label.Label == optionSetText).Where(l => optionSetDetail.Value != null)
 select optionSetDetail).ToList();

 return optionSetInfo.Any() && optionSetInfo.Count > 0 && optionSetInfo[0].Value.HasValue ? optionSetInfo[0].Value : null;
 }

Connecting to CRM Online (2013/2015)

Whenever i am going to extend CRM system or developing 3rd party party for CRM or a webservice. CRM Authentication is required to perform Create, Update, Delete or retrieve operations in CRM organisation therefore connection must be established and authenticated correctly to get hands on the CRM IOrganisation Service. Below is simple code to connect to CRM. i wrote this example in C# using windows console application and reading credentials from app.config.

</pre>
<pre class="lang-cs prettyprint prettyprinted"><code><span class="pln">public static class CrmConnector
 {
 public static IOrganizationService CreateCrmService()
 {
 ConnectToMscrm();

 var userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
 if (userid != Guid.Empty)
 {
 Console.WriteLine("Connection Established Successfully");
 Console.ReadKey();
 }
 else
 {
 Console.WriteLine("Connection couldn't established Successfully");
 Console.ReadKey();
 }
 
 return _orgService;
 }

 static IOrganizationService _orgService;

 public static void ConnectToMscrm()
 {
 try
 {
 var connectorUser = ConfigurationManager.AppSettings["connectorUser"]; //test.user@crmorg.onmicrosoft.com
 var connectorPassword = ConfigurationManager.AppSettings["connectorPassword"]; //password123
 var uri = ConfigurationManager.AppSettings["crmOrgServiceUrl"]; //https://crmorg.api.crm4.dynamics.com/XRMServices/2011/Organization.svc
 //var homeRelamUrl = new Uri(ConfigurationManager.AppSettings["HomeRelamURL"]);


 var credentials = new ClientCredentials();
 credentials.UserName.UserName = connectorUser;
 credentials.UserName.Password = connectorPassword;

 var serviceUri = new Uri(uri);

 var orgProxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
 orgProxy.EnableProxyTypes();
 _orgService = (IOrganizationService)orgProxy;
 }
 catch (Exception ex)
 {
 //throw new Exception("Error Has Occurred while connecting to CRM Server " + ex.Message);
 Console.WriteLine("Error Has Occurred while connecting to CRM Server " + ex.Message);
 }
 }
 } 
</span></code></pre>
<pre>
 

Associate Many to Many Entity Record in CRM 2013

when there is many to many or n to n (n:n) relationship is created between two entities, CRM creates new table as connection or a bridge between these entities to store id’s of both entities. Suppose there is a student and he has been studied in different institutes and there could be n:n relationship between them lets say

there relationship name is (crm database table name) crm_student_institute

target entity could be student

linked entity could be institute so

//string strEntityRelationshipName = crm_student_institute
//CrmServiceProvider serviceProvider is new crm 2013 service provider which contains IOrganisationService object inside of it serviceProvider.Service
//Entity targetEntity = Student Entity
//Entity linkedEntity = institute entity
public static bool AssociateManyToManyEntityRecords(CrmServiceProvider serviceProvider, Entity targetEntity, Entity linkedEntity, string strEntityRelationshipName)
{
    AssociateRequest request = new AssociateRequest();
    EntityReference targetEntityReference = new EntityReference(targetEntity.LogicalName, targetEntity.Id);
    EntityReference linkedEntityReference = new EntityReference(linkedEntity.LogicalName, linkedEntity.Id);
    request.Target = targetEntityReference;
    request.RelatedEntities = new EntityReferenceCollection { linkedEntityReference };
    request.Relationship = new Relationship(strEntityRelationshipName);

    serviceProvider.Service.Execute(request);

    return true;
}

Get Domain Name without any Sub-domain name

Hi,

you can get domain name without any sub-domain by using below method

public string GetDom(HttpRequest Request)
{
          var fullDomain = new      Uri(Request.Url.Host.ToLower()).GetComponents(UriComponents.Host, UriFormat.SafeUnescaped);

        if (fullDomain.EndsWith(“.com”))
               return GetHostUrl(fullDomain, 2);
        else if (fullDomain.EndsWith(“.co.uk”))
               return GetHostUrl(fullDomain, 3);
        return fullDomain;
}

public string GetHostUrl(string hostUrl, int parameters)
{
         var domainParts = hostUrl
         .Split(‘.’) // [“test”, “example”, “co”,”uk”]
         .Reverse() // [“uk”,”co”, “example”, “test”]
         .Take(parameters) // [“uk”,”co” “example”]
         .Reverse(); // [“example”, “co”,”uk”]
          var domain = String.Join(“.”, domainParts);
          return domain;
}

These method can be made more generic.

Thanks

Regular Expression to check Valid UK Postcode for Upper and Lower case

It is Regular Expression to check valid post code for UK for both Upper and Lowecase

^((?i)([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]| [ABEHMNPRV-Y]))|[0-9][A-HJKS-UW]))\ ?[0-9][ABD-HJLNP-UW-Z]{2}|

(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\)?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$

 

Thanks

SQL Server Reporting–Apply Checks on Report Fields

To check null filed

=Iif(IsNothing(Fields!InvoiceName.Value,”Invoice Name Not available”, Fields!InvoiceName.Value ))

To use If statement

=Iif(Fields!IsActive.Value,”Yes”,”No”)

To use Switch statement

=switch(Fields!DateFormate.Value = “dd-mm-yyyy”, “Format: Day, month and year”,Fields!DateFormate.Value = “mm-dd-yyyy”, “Format: month, day and year”, Fields!DateFormate.Value = “yyyy-mm-dd”, “Format: year, month and date”)

Filter Collections (same as ‘Like’ operator in SQL) by using LINQ

A simple collection of objects can easily be filtered by using LINQ rather than traversing through whole collection one by one in loops with the help of complex coding.
Whenever we are using a Like operator in SQL query we perform usually three types of operations with it.

1.    Like ‘abc%’ //grab those values in particular column only starting with abc
2.    Like ‘%abc%’ //grab those values in particular column which contains abc
3.    Like ‘%abc’  //grab only those values from particular column ending with abc

Though System.Data.Linq.SqlClient.SqlMethods name space has a Like() method to filter the data but it only supports to LINQ to SQL, so it can’t be used here

Lets go step by step beginning with 1. Filter Start with ( Like ‘b%’ )

1

I had the BookInformation Table in the Database i fetch all data from the table and then Filter that data according to requirement. In above code you can see, from all collection it will only show the data which is Starting with ‘b’. I filtered the whole collection by using the StartsWith() Method

Now lets go for 2nd Option, 2. Filter Contains ( Like ‘%or%’ )

1

in above code example in above code fetched all data from the database table and then Filter that data on the basis of Books name having ‘or’ in their names by using Contains()  Method

Finally, 3. Filter Ends with ( Like ‘%k’ )

3

in above code fetched all data from the database table and then Filter that data on the basis of Books name ending ‘K’ by using the EndsWith() method

 

Note: Pleas make sure all these filter method StartsWith(), Contains() and EndsWith() are case sensitive mean if suppose the name of the Book is “Border Force” and you are trying to fetch data on the base of “b” it will return nothing, So you should “B” for that.
You may need to convert filterCollection object to List or any other collection to bind

I hope this post will be helpful for you any queries please let me know

Thank your

OnClick Event for Text Box in ASP.NET with C#

these 2 statement realy works no need to write in textbox field just write these two statements

1st one is code behind in PageLoad

TextBox1.Attributes[“onclick”] = “clearTextBox(this.id)”;

and 2nd is in aspx in header

function clearTextBox(textBoxID)
{
document.getElementById(textBoxID).value = “”;
}

thank you