Tuesday, December 10, 2013

remove an class object from a List in C# using IEqualityComparer

While removing simple datatypes(int, string, datetime etc) from List is quite simple it is not the case with Complex data types (some custom class) if it has to be removed from needs to be done using IEqualityComparer
 
I had this requirement where I needed to compare two set of Lists to identify which are the new sets of records to be created and which are the one already existing and therefore needs to be just updated.
 
A had a custom class called LookupNameValue which has certain name , value properties , now in order to compare two set of Lists in C# to find out I had to implement the IEqualityComparer for the LookupNameValue class
 
Sample code to implement IEqualityComparer : note that we have to implement method Equals and GetHashCode to use IEqualityComparer
public class ValueComparer : IEqualityComparer<LookupNameValue>
    {
 
        public bool Equals(LookupNameValue x,LookupNameValue y)
        {
            if (x.Value.Equals(y.Value))
                {
                    return true;
                }
                else
                {
                    return false;
                }
        }
        public int GetHashCode(LookupNameValue obj)
        {
            return obj.Name.GetHashCode();
        }
    }
 
Sample LookUpNameAndValue class
public class LookupNameValue : IComparable
    {
        private Guid _value;
        private string _name;
public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }
 
        public Guid Value
        {
            get
            {
                return _value;
            }
            set
            {
                _value = value;
            }
        }
}
 
Now once we have implemented the IEqualityComparer interface we need to use the same for filtering out the existing dataset.This is done by using Except method of the List
Sample Code to use the custom comparer
 
ValueComparer comparer = new ValueComparer();
IEnumerable<LookupNameValue> finalCreateTeamDataset = createTeamDatasetTemp.Except(updateDatasetToBeRemoved, comparer);
 
Where createTeamDatasetTemp and updateDatasetToBeRemoved are List of my generic class LookupNameValue
List<LookupNameValue> createTeamDatasetTemp = new List<LookupNameValue>();
List<LookupNameValue> updateDatasetToBeRemoved = new List<LookupNameValue>();
The filtered dataset could then be used as following
 
foreach (var data in finalCreateTeamDataset)
{
 //do ur job
}
 
Hope this is helpful to you all  

Thursday, June 13, 2013

How to write a Regular expression for case insensitive search for email with fixed domain in MVC4

I was trying to search for a way to write a regular expression which can validate my email string. My email string is something of the kind xxx@gmail.com which means while the first part of the string may change the later part is a fixed domain. I wanted this to be case insensitive validation so that an email XxXx@GmaIL.com is also validated properly.

To achieve the same we need to do it in three steps

First we need to define a custom attribute which will be used to validate the expression

Step 1 :

public class IgnorecaseRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable

 
 
{
 
public IgnoreCaseRegularExpressionAttribute(string pattern)

: base("(?i)" + pattern)
 
 

{ }
 
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
 
 

{
 
var rule = new ModelClientValidationRule

 
 
{
 
ValidationType = "ignorecaseregex",
 
 

ErrorMessage = ErrorMessage

};
 
 
rule.ValidationParameters.Add("pattern", Pattern.Substring(4));

yield return rule;
 
 

}

}

Step 2:
The validation mentioned in the step 1 need to be registered in a script file


jQuery.validator.unobtrusive.adapters.add('ignorecaseregex', ['pattern'], function (options) {

options.rules['icregex'] = options.params;

options.messages['icregex'] = options.message;



});
jQuery.validator.addMethod('ignorecaseregex', function (value, element, params) {

var match;

if (this.optional(element)) {

return true;



}
match = new RegExp(params.pattern, 'i').exec(value);

return (match && (match.index === 0) && (match[0].length === value.length));

}, '');

this script file needs to be loaded on the form where your property is used.

Step 3 :This is the final step where you are now ready to use the  IgnorecaseRegularExpressionAttribute attribute.This can be used on the property where we want to do a case insensitive validation for e.g.

[IgnorecaseRegularExpression("^[a-zA-Z0-9_-]+(\\.[a-zA-Z0-0_]+)*@gmail+(\\.com)", ErrorMessage = "Not a valid email.")]

public string DemoPropertyName { get; set; }


 



Wednesday, June 12, 2013

Case in-sensitive search in MSCRM 2011

To do a case insensitive search in MSCRM 2011 we need to tweak the query a little bit ,for e.g.

if (!String.IsNullOrEmpty(fieldname)) query.Criteria.AddCondition("fieldname".ToLower(), ConditionOperator.Equal, fieldname.ToLower());
EntityCollection col = service.RetrieveMultiple(query);
Here I am setting the schema name to ToLower() which actually does the trick, hope this help.Leave your comments.

Tuesday, June 4, 2013

Hitting backspace on the jquery datetime control hides it on MSCRM 2011 form/ How to capture the keypress event on a jquery control and overcome the default behavior


I have used jquery hour’s picker/Date picker control on the MSCRM form. It was working perfectly fine till the time I used to press the backspace. As soon as we press backspace it used to hide the control for some reason.

To overcome this we need to override the default behavior of the “backspace” and “delete” keys.

As shown below I am using the “keydown” event, please do not use KeyPress event as it does not gives the required result

$("#timepickerControl").keydown(function (e) {

            switch (e.keyCode) {

                case 46:  // delete

                    e.preventDefault();

                    alert("Del Key Pressed ,Please use slider to enter valid input");

                    break;

                case 8:  // backspace

                    e.preventDefault();

                    alert("Backspace Key Pressed ,Please use slider to enter valid input");

                    break;

            }

        });
The above code will stop the hiding if I click on the text box provided for the control.
In order to disable the backspace on the complete document and the parent document we need to have two extra pair of functions as below


 // Prevent the backspace key from navigating back on the webresource.

        $(document).unbind('keydown').bind('keydown', function (event) {

            var doPrevent = false;

            if (event.keyCode === 8) {

                var d = event.srcElement || event.target;

                if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD'))

             || d.tagName.toUpperCase() === 'TEXTAREA') {

                    doPrevent = d.readOnly || d.disabled;

                }

                else {

                    doPrevent = true;

                }

            }

 

            if (doPrevent) {

                event.preventDefault();

            }

        });

 

    });

 

    //Prevent the backspace key from navigating back on the parent form containing the webresource.

    $(window.parent.document).unbind('keydown').bind('keydown', function (event) {

        var doPrevent = false;

        if (event.keyCode === 8) {

            var d = event.srcElement || event.target;

            if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD'))

            || d.tagName.toUpperCase() === 'TEXTAREA') {

                doPrevent = d.readOnly || d.disabled;

            }

            else {

                doPrevent = true;

            }

        }

 

        if (doPrevent) {

            event.preventDefault();

        }

    });

 

Monday, May 27, 2013

How to access a field in an Iframe or a HTML webresource from the CRM form

Here I am trying to access a field on the webresource that I have placed on the mscrm 2011 form.
First we get to the web resource and then get to the field within it
 
 
window.document.getElementById("WebResource_TimePicker").contentWindow.document.getElementById("wrapper").style.visibility = 'visible';

Friday, April 26, 2013

How to refresh grid from an open record in MSCRM 2011

This is a simple single line of code


window.parent.opener.document.getElementById("crmGrid").control.refresh();
 
In case the above line does not work another way to achieve the same is the code of line below where we are calling the click event of the refresh button on the crm grid

window.parent.opener.document.getElementById("grid_refresh").click();


Convert from one time zone to another time zone - convert Source DateTime to UTC and will then convert UTC timezone to destination timezone code




The function below will first convert Source DateTime to UTC and will then convert UTC timezone to destination timezone code


  

# region "ConvertFromSourceTimeZoneToDestinationTimeZone"

/// <summary>
       
/// </summary>

/// <param name="sourceDateTime"></param>

/// <param name="sourceTimeZoneCode"></param>

/// <param name="destinationTimeZoneCode"></param>

/// <param name="organizationServ"></param>

/// <returns></returns>

private DateTime ConvertFromSourceTimeZoneToDestinationTimeZone(DateTime sourceDateTime, int sourceTimeZoneCode, int destinationTimeZoneCode, IOrganizationService organizationServ)



{

DateTime destinationDateTime = DateTime.UtcNow;

try



{

//Convert Source DateTime to UTC

UtcTimeFromLocalTimeRequest utcFromLocalRequest = new UtcTimeFromLocalTimeRequest();



utcFromLocalRequest.LocalTime = sourceDateTime;

utcFromLocalRequest.TimeZoneCode = sourceTimeZoneCode;

UtcTimeFromLocalTimeResponse utcFromLocalResponse = (UtcTimeFromLocalTimeResponse)organizationServ.Execute(utcFromLocalRequest);

//Convert UTC DateTime to Destination TimeZone

LocalTimeFromUtcTimeRequest localFromUtcRequest = new LocalTimeFromUtcTimeRequest();



localFromUtcRequest.UtcTime = utcFromLocalResponse.UtcTime;

localFromUtcRequest.TimeZoneCode = destinationTimeZoneCode;

LocalTimeFromUtcTimeResponse localFromUtcResponse = (LocalTimeFromUtcTimeResponse)organizationServ.Execute(localFromUtcRequest);



destinationDateTime = localFromUtcResponse.LocalTime;

}

catch (FaultException<OrganizationServiceFault>)



{

throw;



}

catch (Exception)



{

}

return destinationDateTime;



}

# endregion