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

Get User Local Time From UTC Time in MSCRM 2011

The following piece of code will return user's local time from utc time , the user time zone will be retrieved by another function which I have posted in another of my blogs , iam pasting the code here also for making it easy to understand
 
 
 

        private DateTime GetUserLocalTimeFromUTCTime(IOrganizationService service, DateTime utcDate, Guid userId)

        {

            Entity loggedInUser = null;

            int timeZoneCode = 0;

            DateTime returnDateTime = DateTime.UtcNow;

            try

            {

                loggedInUser = GetUserTimeZone(service, userId);

                if (loggedInUser != null && loggedInUser.Attributes.Contains("timezonecode"))

                {

                    timeZoneCode = ((int)loggedInUser.Attributes["timezonecode"]);

                }

                LocalTimeFromUtcTimeRequest request = new LocalTimeFromUtcTimeRequest();

                request.UtcTime = utcDate;

                request.TimeZoneCode = timeZoneCode;

                LocalTimeFromUtcTimeResponse response = (LocalTimeFromUtcTimeResponse)service.Execute(request);

                returnDateTime = response.LocalTime;

                return returnDateTime;

            }

            catch (FaultException<OrganizationServiceFault>)

            {

                //return UtcNow when the corresponding userId doesn't have any local time zone settings (for example "Network Service")

                //throw;

                return returnDateTime;

            }

            catch (Exception)

            {

                //return UtcNow when the corresponding userId doesn't have any local time zone settings (for example "Network Service")

                //throw;

                return returnDateTime;

            }

        }

 
 
 
 
        private Entity GetUserTimeZone(IOrganizationService service, Guid userId)
        {
            try
            {
 
                RetrieveUserSettingsSystemUserRequest request = new RetrieveUserSettingsSystemUserRequest();
                request.ColumnSet = new ColumnSet("timezonecode");
                request.EntityId = userId;
                RetrieveUserSettingsSystemUserResponse response = (RetrieveUserSettingsSystemUserResponse)service.Execute(request);
                return response.Entity;
            }
            catch (FaultException<OrganizationServiceFault>)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }