Development Desk

Just another WordPress.com site

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

Solution for Exception: System.InvalidOperationException: Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource.

This exception occurs when we assign DataSource to some DataGrid or Calender and after that try to bind that DataSource with that Control.  Actually the  Problem is, Control like Gridview requires a collection to be bound with them instead of on single Object

suppose you have a Person class you fetch 1 single person from database like in below case person data is fetched by the method in the business Logic layer on the base of person id

Person singlePerson = new personBL().getSinglePerson(personId);

and then

personGridView.DataSource = singlePerson;

personGridView.DataBind(); // on this point exception will be thrown because single Instance of class is assigned to Gridview

it can be resolved, if you have only single object to assign you can simply add it to the list then assign to the DataSource like

 

Person singlePerson = new personBL().getSinglePerson(personId);

List <Person> personList = new List<Person>();

personList.Add(singlePerson );

personGridView.DataSource = personList;

personGridView.DataBind();

or

simply assign a collection instead of on single instance of object to resolve it

it just simple is that.

thank you

Convert String to GUID in C#

string can be converted to GUID just by

Guid stringToGuid = new Guid(“GUID value in the form of String”);

for example

Guid stringToGuid = new Guid(“91a61ee7-48bb-4371-ad33-72oI67c9b3e”); 

it will give same Guid in return but in the form of GUID

 

Follow

Get every new post delivered to your Inbox.