Summary

Class:FakeXrmEasy.Extensions.FetchXml.XmlExtensionsForFetchXml
Assembly:FakeXrmEasy
File(s):F:\Git\fake-xrm-easy\FakeXrmEasy.Shared\Extensions\XmlExtensionsForFetchXml.cs
Covered lines:511
Uncovered lines:29
Coverable lines:540
Total lines:859
Line coverage:94.6%
Branch coverage:59.1%

Metrics

MethodCyclomatic ComplexitySequence CoverageBranch Coverage
IsAttributeTrue(...)4100100
IsAggregateFetchXml(...)1100100
IsDistincFetchXml(...)1100100
IsFetchXmlNodeValid(...)2710062.07
GetAttribute(...)1100100
ToColumnSet(...)5100100
ToTopCount(...)387.580
ToCount(...)3100100
ToReturnTotalRecordCount(...)387.580
ToPageNumber(...)387.580
ToColumnSet(...)1100100
ToTopCount(...)1100100
ToCount(...)1100100
ToReturnTotalRecordCount(...)1100100
ToPageNumber(...)1100100
ToCriteria(...)2100100
GetAssociatedEntityNameForConditionExpression(...)490.9180
ToLinkEntity(...)7100100
ToLinkEntities(...)2100100
ToOrderExpressionList(...)3100100
ToFilterExpression(...)8100100
ToValue(...)1100100
ToConditionExpression(...)16598.2154.39
GetValueBasedOnType(...)3273.2475.61
ValueNeedsConverting(...)1100100
GetConditionExpressionValueCast(...)1192.8685.71
.cctor()1100100

File(s)

F:\Git\fake-xrm-easy\FakeXrmEasy.Shared\Extensions\XmlExtensionsForFetchXml.cs

#LineLine coverage
 1using Microsoft.Xrm.Sdk.Query;
 2using System;
 3using System.Collections.Generic;
 4using System.Text;
 5using System.Linq;
 6using System.Xml.Linq;
 7using Microsoft.Xrm.Sdk;
 8using System.Globalization;
 9
 10namespace FakeXrmEasy.Extensions.FetchXml
 11{
 12    public static class XmlExtensionsForFetchXml
 13    {
 614        private static IEnumerable<ConditionOperator> OperatorsNotToConvertArray = new[]
 615        {
 616#if FAKE_XRM_EASY_2015 || FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365 || FAKE_XRM_EASY_9
 617            ConditionOperator.OlderThanXWeeks,
 618            ConditionOperator.OlderThanXYears,
 619            ConditionOperator.OlderThanXDays,
 620            ConditionOperator.OlderThanXHours,
 621            ConditionOperator.OlderThanXMinutes,
 622#endif
 623            ConditionOperator.OlderThanXMonths,
 624            ConditionOperator.LastXDays,
 625            ConditionOperator.LastXHours,
 626            ConditionOperator.LastXMonths,
 627            ConditionOperator.LastXWeeks,
 628            ConditionOperator.LastXYears,
 629            ConditionOperator.NextXHours,
 630            ConditionOperator.NextXDays,
 631            ConditionOperator.NextXWeeks,
 632            ConditionOperator.NextXMonths,
 633            ConditionOperator.NextXYears,
 634            ConditionOperator.NextXWeeks,
 635            ConditionOperator.InFiscalYear
 636        };
 37
 38        public static bool IsAttributeTrue(this XElement elem, string attributeName)
 406939        {
 406940             var val = elem.GetAttribute(attributeName)?.Value;
 41
 406942            return "true".Equals(val, StringComparison.InvariantCultureIgnoreCase)
 406943                || "1".Equals(val, StringComparison.InvariantCultureIgnoreCase);
 406944        }
 45
 46        public static bool IsAggregateFetchXml(this XDocument doc)
 225147        {
 225148            return doc.Root.IsAttributeTrue("aggregate");
 225149        }
 50
 51        public static bool IsDistincFetchXml(this XDocument doc)
 126852        {
 126853            return doc.Root.IsAttributeTrue("distinct");
 126854        }
 55
 56        public static bool IsFetchXmlNodeValid(this XElement elem)
 831957        {
 831958             switch (elem.Name.LocalName)
 59            {
 60                case "filter":
 105261                    return true;
 62
 63                case "value":
 64                case "fetch":
 138865                    return true;
 66
 67                case "entity":
 129868                    return elem.GetAttribute("name") != null;
 69
 70                case "all-attributes":
 1871                    return true;
 72
 73                case "attribute":
 288874                    return elem.GetAttribute("name") != null;
 75
 76                case "link-entity":
 18277                    return elem.GetAttribute("name") != null
 18278                            && elem.GetAttribute("from") != null
 18279                            && elem.GetAttribute("to") != null;
 80
 81                case "order":
 34682                     if (elem.Document.IsAggregateFetchXml())
 2483                    {
 2484                        return elem.GetAttribute("alias") != null
 2485                            && elem.GetAttribute("attribute") == null;
 86                    }
 87                    else
 32288                    {
 32289                        return elem.GetAttribute("attribute") != null;
 90                    }
 91
 92                case "condition":
 114193                    return elem.GetAttribute("attribute") != null
 114194                           && elem.GetAttribute("operator") != null;
 95
 96                default:
 697                    throw new Exception(string.Format("Node {0} is not a valid FetchXml node or it doesn't have the requ
 98            }
 831399        }
 100
 101        public static XAttribute GetAttribute(this XElement elem, string sAttributeName)
 30698102        {
 96434103            return elem.Attributes().FirstOrDefault((a => a.Name.LocalName.Equals(sAttributeName)));
 30698104        }
 105
 106        public static ColumnSet ToColumnSet(this XElement el)
 1450107        {
 1450108            var allAttributes = el.Elements()
 5876109                    .Where(e => e.Name.LocalName.Equals("all-attributes"))
 1450110                    .FirstOrDefault();
 111
 1450112             if (allAttributes != null)
 18113            {
 18114                return new ColumnSet(true);
 115            }
 116
 1432117            var attributes = el.Elements()
 5840118                                .Where(e => e.Name.LocalName.Equals("attribute"))
 4308119                                .Select(e => e.GetAttribute("name").Value)
 1432120                                .ToArray();
 121
 122
 1432123            return new ColumnSet(attributes);
 1450124        }
 125
 126        public static int? ToTopCount(this XElement el)
 1238127        {
 1238128            var countAttr = el.GetAttribute("top");
 2460129             if (countAttr == null) return null;
 130
 131            int iCount;
 16132             if (!int.TryParse(countAttr.Value, out iCount))
 0133                throw new Exception("Top attribute in fetch node must be an integer");
 134
 16135            return iCount;
 1238136        }
 137
 138        public static int? ToCount(this XElement el)
 1238139        {
 1238140            var countAttr = el.GetAttribute("count");
 2440141             if (countAttr == null) return null;
 142
 143            int iCount;
 36144             if (!int.TryParse(countAttr.Value, out iCount))
 6145                throw new Exception("Count attribute in fetch node must be an integer");
 146
 30147            return iCount;
 1232148        }
 149
 150
 151        public static bool ToReturnTotalRecordCount(this XElement el)
 1232152        {
 1232153            var returnTotalRecordCountAttr = el.GetAttribute("returntotalrecordcount");
 2446154             if (returnTotalRecordCountAttr == null) return false;
 155
 156            bool bReturnCount;
 18157             if (!bool.TryParse(returnTotalRecordCountAttr.Value, out bReturnCount))
 0158                throw new Exception("returntotalrecordcount attribute in fetch node must be an boolean");
 159
 18160            return bReturnCount;
 1232161        }
 162
 163        public static int? ToPageNumber(this XElement el)
 1232164        {
 1232165            var pageAttr = el.GetAttribute("page");
 2440166             if (pageAttr == null) return null;
 167
 168            int iPage;
 24169             if (!int.TryParse(pageAttr.Value, out iPage))
 0170                throw new Exception("Count attribute in fetch node must be an integer");
 171
 24172            return iPage;
 1232173        }
 174
 175        public static ColumnSet ToColumnSet(this XDocument xlDoc)
 1268176        {
 177            //Check if all-attributes exist
 1268178            return xlDoc.Elements()   //fetch
 1268179                    .Elements()
 1268180                    .FirstOrDefault()
 1268181                    .ToColumnSet();
 1268182        }
 183
 184
 185        public static int? ToTopCount(this XDocument xlDoc)
 1238186        {
 187            //Check if all-attributes exist
 1238188            return xlDoc.Elements()   //fetch
 1238189                    .FirstOrDefault()
 1238190                    .ToTopCount();
 1238191        }
 192
 193        public static int? ToCount(this XDocument xlDoc)
 1238194        {
 195            //Check if all-attributes exist
 1238196            return xlDoc.Elements()   //fetch
 1238197                    .FirstOrDefault()
 1238198                    .ToCount();
 1232199        }
 200
 201        public static bool ToReturnTotalRecordCount(this XDocument xlDoc)
 1232202        {
 1232203            return xlDoc.Elements()   //fetch
 1232204                    .FirstOrDefault()
 1232205                    .ToReturnTotalRecordCount();
 1232206        }
 207
 208
 209        public static int? ToPageNumber(this XDocument xlDoc)
 1232210        {
 211            //Check if all-attributes exist
 1232212            return xlDoc.Elements()   //fetch
 1232213                    .FirstOrDefault()
 1232214                    .ToPageNumber();
 1232215        }
 216
 217        public static FilterExpression ToCriteria(this XDocument xlDoc, XrmFakedContext ctx)
 1268218        {
 1268219            return xlDoc.Elements()   //fetch
 1268220                    .Elements()     //entity
 1268221                    .Elements()     //child nodes of entity
 5382222                    .Where(el => el.Name.LocalName.Equals("filter"))
 2230223                    .Select(el => el.ToFilterExpression(ctx))
 1268224                    .FirstOrDefault();
 1238225        }
 226
 227        public static string GetAssociatedEntityNameForConditionExpression(this XElement el)
 1141228        {
 229
 2342230             while (el != null)
 2342231            {
 2342232                var parent = el.Parent;
 2342233                 if (parent.Name.LocalName.Equals("entity") || parent.Name.LocalName.Equals("link-entity"))
 1141234                {
 1141235                    return parent.GetAttribute("name").Value;
 236                }
 1201237                el = parent;
 1201238            }
 239
 0240            return null;
 1141241        }
 242
 243        public static LinkEntity ToLinkEntity(this XElement el, XrmFakedContext ctx)
 182244        {
 245            //Create this node
 182246            var linkEntity = new LinkEntity();
 247
 182248            linkEntity.LinkFromEntityName = el.Parent.GetAttribute("name").Value;
 182249            linkEntity.LinkFromAttributeName = el.GetAttribute("to").Value;
 182250            linkEntity.LinkToAttributeName = el.GetAttribute("from").Value;
 182251            linkEntity.LinkToEntityName = el.GetAttribute("name").Value;
 252
 182253             if (el.GetAttribute("alias") != null)
 159254            {
 159255                linkEntity.EntityAlias = el.GetAttribute("alias").Value;
 159256            }
 257
 258            //Join operator
 182259             if (el.GetAttribute("link-type") != null)
 110260            {
 110261                 switch (el.GetAttribute("link-type").Value)
 262                {
 263                    case "outer":
 30264                        linkEntity.JoinOperator = JoinOperator.LeftOuter;
 30265                        break;
 266                    default:
 80267                        linkEntity.JoinOperator = JoinOperator.Inner;
 80268                        break;
 269                }
 110270            }
 271
 272            //Process other link entities recursively
 182273            var convertedLinkEntityNodes = el.Elements()
 460274                                .Where(e => e.Name.LocalName.Equals("link-entity"))
 200275                                .Select(e => e.ToLinkEntity(ctx))
 182276                                .ToList();
 277
 582278            foreach (var le in convertedLinkEntityNodes)
 18279            {
 18280                linkEntity.LinkEntities.Add(le);
 18281            }
 282
 283            //Process column sets
 182284            linkEntity.Columns = el.ToColumnSet();
 285
 286            //Process filter
 182287            linkEntity.LinkCriteria = el.Elements()
 460288                                        .Where(e => e.Name.LocalName.Equals("filter"))
 242289                                        .Select(e => e.ToFilterExpression(ctx))
 182290                                        .FirstOrDefault();
 291
 182292            return linkEntity;
 182293        }
 294
 295        public static List<LinkEntity> ToLinkEntities(this XDocument xlDoc, XrmFakedContext ctx)
 1232296        {
 1232297            return xlDoc.Elements()   //fetch
 1232298                    .Elements()     //entity
 1232299                    .Elements()     //child nodes of entity
 5308300                    .Where(el => el.Name.LocalName.Equals("link-entity"))
 1396301                    .Select(el => el.ToLinkEntity(ctx))
 1232302                    .ToList();
 1232303        }
 304
 305        public static List<OrderExpression> ToOrderExpressionList(this XDocument xlDoc)
 1124306        {
 1124307            var orderByElements = xlDoc.Elements()   //fetch
 1124308                                .Elements()     //entity
 1124309                                .Elements()     //child nodes of entity
 5044310                                .Where(el => el.Name.LocalName.Equals("order"))
 1124311                                .Select(el =>
 1434312                                         new OrderExpression
 1434313                                        {
 1434314                                            AttributeName = el.GetAttribute("attribute").Value,
 1434315                                            OrderType = el.IsAttributeTrue("descending") ? OrderType.Descending : OrderT
 1434316                                        })
 1124317                                .ToList();
 318
 1124319            return orderByElements;
 1124320        }
 321
 322        public static FilterExpression ToFilterExpression(this XElement elem, XrmFakedContext ctx)
 1052323        {
 1052324            var filterExpression = new FilterExpression();
 325
 1052326            var filterType = elem.GetAttribute("type");
 1052327             if (filterType == null)
 58328            {
 58329                filterExpression.FilterOperator = LogicalOperator.And; //By default
 58330            }
 331            else
 994332            {
 994333                 filterExpression.FilterOperator = filterType.Value.Equals("and") ?
 994334                                                  LogicalOperator.And : LogicalOperator.Or;
 994335            }
 336
 337            //Process other filters recursively
 1052338            var otherFilters = elem
 1052339                        .Elements() //child nodes of this filter
 2223340                        .Where(el => el.Name.LocalName.Equals("filter"))
 1082341                        .Select(el => el.ToFilterExpression(ctx))
 1052342                        .ToList();
 343
 344
 345            //Process conditions
 1052346            var conditions = elem
 1052347                        .Elements() //child nodes of this filter
 2223348                        .Where(el => el.Name.LocalName.Equals("condition"))
 2193349                        .Select(el => el.ToConditionExpression(ctx))
 1052350                        .ToList();
 351
 5288352            foreach (var c in conditions)
 1111353                filterExpression.AddCondition(c);
 354
 3126355            foreach (var f in otherFilters)
 30356                filterExpression.AddFilter(f);
 357
 1022358            return filterExpression;
 1022359        }
 360
 361        public static object ToValue(this XElement elem, XrmFakedContext ctx, string sEntityName, string sAttributeName,
 96362        {
 96363            return GetConditionExpressionValueCast(elem.Value, ctx, sEntityName, sAttributeName, op);
 84364        }
 365
 366        public static ConditionExpression ToConditionExpression(this XElement elem, XrmFakedContext ctx)
 1141367        {
 1141368            var conditionExpression = new ConditionExpression();
 369
 1141370            var conditionEntityName = "";
 371
 1141372            var attributeName = elem.GetAttribute("attribute").Value;
 1141373            ConditionOperator op = ConditionOperator.Equal;
 374
 1141375            string value = null;
 1141376             if (elem.GetAttribute("value") != null)
 897377            {
 897378                value = elem.GetAttribute("value").Value;
 897379            }
 1141380             if (elem.GetAttribute("entityname") != null)
 20381            {
 20382                conditionEntityName = elem.GetAttribute("entityname").Value;
 20383            }
 384
 1141385             switch (elem.GetAttribute("operator").Value)
 386            {
 387                case "eq":
 363388                    op = ConditionOperator.Equal;
 363389                    break;
 390                case "ne":
 391                case "neq":
 24392                    op = ConditionOperator.NotEqual;
 24393                    break;
 394                case "begins-with":
 6395                    op = ConditionOperator.BeginsWith;
 6396                    break;
 397                case "not-begin-with":
 6398                    op = ConditionOperator.DoesNotBeginWith;
 6399                    break;
 400                case "ends-with":
 6401                    op = ConditionOperator.EndsWith;
 6402                    break;
 403                case "not-end-with":
 6404                    op = ConditionOperator.DoesNotEndWith;
 6405                    break;
 406                case "in":
 7407                    op = ConditionOperator.In;
 7408                    break;
 409                case "not-in":
 7410                    op = ConditionOperator.NotIn;
 7411                    break;
 412                case "null":
 16413                    op = ConditionOperator.Null;
 16414                    break;
 415                case "not-null":
 12416                    op = ConditionOperator.NotNull;
 12417                    break;
 418                case "like":
 36419                    op = ConditionOperator.Like;
 420
 36421                     if (value != null)
 36422                    {
 36423                         if (value.StartsWith("%") && !value.EndsWith("%"))
 6424                            op = ConditionOperator.EndsWith;
 30425                         else if (!value.StartsWith("%") && value.EndsWith("%"))
 6426                            op = ConditionOperator.BeginsWith;
 24427                         else if (value.StartsWith("%") && value.EndsWith("%"))
 24428                            op = ConditionOperator.Contains;
 429
 36430                        value = value.Replace("%", "");
 36431                    }
 36432                    break;
 433                case "not-like":
 48434                    op = ConditionOperator.NotLike;
 48435                     if (value != null)
 48436                    {
 48437                         if (value.StartsWith("%") && !value.EndsWith("%"))
 36438                            op = ConditionOperator.DoesNotEndWith;
 12439                         else if (!value.StartsWith("%") && value.EndsWith("%"))
 6440                            op = ConditionOperator.DoesNotBeginWith;
 6441                         else if (value.StartsWith("%") && value.EndsWith("%"))
 6442                            op = ConditionOperator.DoesNotContain;
 443
 48444                        value = value.Replace("%", "");
 48445                    }
 48446                    break;
 447                case "gt":
 30448                    op = ConditionOperator.GreaterThan;
 30449                    break;
 450                case "ge":
 12451                    op = ConditionOperator.GreaterEqual;
 12452                    break;
 453                case "lt":
 36454                    op = ConditionOperator.LessThan;
 36455                    break;
 456                case "le":
 18457                    op = ConditionOperator.LessEqual;
 18458                    break;
 459                case "on":
 18460                    op = ConditionOperator.On;
 18461                    break;
 462                case "on-or-before":
 12463                    op = ConditionOperator.OnOrBefore;
 12464                    break;
 465                case "on-or-after":
 6466                    op = ConditionOperator.OnOrAfter;
 6467                    break;
 468                case "today":
 6469                    op = ConditionOperator.Today;
 6470                    break;
 471                case "yesterday":
 6472                    op = ConditionOperator.Yesterday;
 6473                    break;
 474                case "tomorrow":
 6475                    op = ConditionOperator.Tomorrow;
 6476                    break;
 477                case "between":
 24478                    op = ConditionOperator.Between;
 24479                    break;
 480                case "not-between":
 24481                    op = ConditionOperator.NotBetween;
 24482                    break;
 483                case "eq-userid":
 12484                    op = ConditionOperator.EqualUserId;
 12485                    break;
 486                case "ne-userid":
 12487                    op = ConditionOperator.NotEqualUserId;
 12488                    break;
 489                case "olderthan-x-months":
 30490                    op = ConditionOperator.OlderThanXMonths;
 30491                    break;
 492                case "last-seven-days":
 12493                    op = ConditionOperator.Last7Days;
 12494                    break;
 495                case "eq-businessid":
 12496                    op = ConditionOperator.EqualBusinessId;
 12497                    break;
 498                case "neq-businessid":
 0499                    op = ConditionOperator.NotEqualBusinessId;
 0500                    break;
 501                case "next-x-weeks":
 12502                    op = ConditionOperator.NextXWeeks;
 12503                    break;
 504                case "next-seven-days":
 12505                    op = ConditionOperator.Next7Days;
 12506                    break;
 507                case "this-year":
 6508                    op = ConditionOperator.ThisYear;
 6509                    break;
 510                case "last-year":
 6511                    op = ConditionOperator.LastYear;
 6512                    break;
 513                case "next-year":
 6514                    op = ConditionOperator.NextYear;
 6515                    break;
 516                case "last-x-hours":
 18517                    op = ConditionOperator.LastXHours;
 18518                    break;
 519                case "last-x-days":
 18520                    op = ConditionOperator.LastXDays;
 18521                    break;
 522                case "last-x-weeks":
 18523                    op = ConditionOperator.LastXWeeks;
 18524                    break;
 525                case "last-x-months":
 18526                    op = ConditionOperator.LastXMonths;
 18527                    break;
 528                case "last-x-years":
 18529                    op = ConditionOperator.LastXYears;
 18530                    break;
 531                case "next-x-hours":
 18532                    op = ConditionOperator.NextXHours;
 18533                    break;
 534                case "next-x-days":
 18535                    op = ConditionOperator.NextXDays;
 18536                    break;
 537                case "next-x-months":
 18538                    op = ConditionOperator.NextXMonths;
 18539                    break;
 540                case "next-x-years":
 18541                    op = ConditionOperator.NextXYears;
 18542                    break;
 543                case "this-month":
 6544                    op = ConditionOperator.ThisMonth;
 6545                    break;
 546                case "last-month":
 6547                    op = ConditionOperator.LastMonth;
 6548                    break;
 549                case "next-month":
 6550                    op = ConditionOperator.NextMonth;
 6551                    break;
 552                case "last-week":
 12553                    op = ConditionOperator.LastWeek;
 12554                    break;
 555                case "this-week":
 12556                    op = ConditionOperator.ThisWeek;
 12557                    break;
 558                case "next-week":
 12559                    op = ConditionOperator.NextWeek;
 12560                    break;
 561                case "in-fiscal-year":
 6562                    op = ConditionOperator.InFiscalYear;
 6563                    break;
 564#if !FAKE_XRM_EASY && !FAKE_XRM_EASY_2013
 565                case "olderthan-x-minutes":
 12566                    op = ConditionOperator.OlderThanXMinutes;
 12567                    break;
 568                case "olderthan-x-hours":
 12569                    op = ConditionOperator.OlderThanXHours;
 12570                    break;
 571                case "olderthan-x-days":
 12572                    op = ConditionOperator.OlderThanXDays;
 12573                    break;
 574                case "olderthan-x-weeks":
 12575                    op = ConditionOperator.OlderThanXWeeks;
 12576                    break;
 577                case "olderthan-x-years":
 12578                    op = ConditionOperator.OlderThanXYears;
 12579                    break;
 580#endif
 581#if FAKE_XRM_EASY_9
 582                case "contain-values":
 2583                    op = ConditionOperator.ContainValues;
 2584                    break;
 585                case "not-contain-values":
 2586                    op = ConditionOperator.DoesNotContainValues;
 2587                    break;
 588#endif
 589                default:
 0590                    throw PullRequestException.FetchXmlOperatorNotImplemented(elem.GetAttribute("operator").Value);
 591            }
 592
 593            //Process values
 1141594            object[] values = null;
 595
 596
 1141597            var entityName = GetAssociatedEntityNameForConditionExpression(elem);
 598
 599            //Find values inside the condition expression, if apply
 1141600            values = elem
 1141601                        .Elements() //child nodes of this filter
 1237602                        .Where(el => el.Name.LocalName.Equals("value"))
 1237603                        .Select(el => el.ToValue(ctx, entityName, attributeName, op))
 1141604                        .ToArray();
 605
 606
 607            //Otherwise, a single value was used
 1129608             if (value != null)
 897609            {
 610#if FAKE_XRM_EASY_2013 || FAKE_XRM_EASY_2015 || FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365 || FAKE_XRM_EASY_9
 760611                 if (string.IsNullOrWhiteSpace(conditionEntityName))
 750612                {
 750613                    return new ConditionExpression(attributeName, op, GetConditionExpressionValueCast(value, ctx, entity
 614                }
 615                else
 10616                {
 10617                    return new ConditionExpression(conditionEntityName, attributeName, op, GetConditionExpressionValueCa
 618                }
 619
 620#else
 137621                return new ConditionExpression(attributeName, op, GetConditionExpressionValueCast(value, ctx, entityName
 622
 623#endif
 624            }
 625
 626#if FAKE_XRM_EASY_2013 || FAKE_XRM_EASY_2015 || FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365 || FAKE_XRM_EASY_9
 627
 196628             if (string.IsNullOrWhiteSpace(conditionEntityName))
 186629            {
 186630                return new ConditionExpression(attributeName, op, values);
 631            }
 632            else
 10633            {
 10634                return new ConditionExpression(conditionEntityName, attributeName, op, values);
 635            }
 636#else
 36637            return new ConditionExpression(attributeName, op, values);
 638#endif
 639
 640
 641
 1111642        }
 643
 644
 645        public static object GetValueBasedOnType(Type t, string value)
 563646        {
 563647             if (t == typeof(int)
 563648                || t == typeof(int?)
 563649                || t.IsOptionSet()
 563650#if FAKE_XRM_EASY_9
 563651                || t.IsOptionSetValueCollection()
 563652#endif
 563653            )
 72654            {
 72655                int intValue = 0;
 656
 72657                 if (int.TryParse(value, out intValue))
 72658                {
 72659                     if (t.IsOptionSet())
 54660                    {
 54661                        return new OptionSetValue(intValue);
 662                    }
 18663                    return intValue;
 664                }
 665                else
 0666                {
 0667                    throw new Exception("Integer value expected");
 668                }
 669            }
 670
 491671             else if (t == typeof(Guid)
 491672                || t == typeof(Guid?)
 491673                || t == typeof(EntityReference)
 491674#if FAKE_XRM_EASY
 491675                    || t == typeof(Microsoft.Xrm.Client.CrmEntityReference)
 491676#endif
 491677                )
 59678            {
 59679                Guid gValue = Guid.Empty;
 680
 59681                 if (Guid.TryParse(value, out gValue))
 59682                {
 59683                     if (t == typeof(EntityReference)
 59684#if FAKE_XRM_EASY
 59685                    || t == typeof(Microsoft.Xrm.Client.CrmEntityReference)
 59686#endif
 59687                        )
 29688                    {
 29689                        return new EntityReference() { Id = gValue };
 690                    }
 30691                    return gValue;
 692                }
 693                else
 0694                {
 0695                    throw new Exception("Guid value expected");
 696                }
 697            }
 432698             else if (t == typeof(decimal)
 432699                || t == typeof(decimal?)
 432700                || t == typeof(Money))
 12701            {
 12702                decimal decValue = 0;
 12703                 if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out decValue))
 12704                {
 12705                     if (t == typeof(Money))
 12706                    {
 12707                        return new Money(decValue);
 708                    }
 0709                    return decValue;
 710                }
 711                else
 0712                {
 0713                    throw new Exception("Decimal value expected");
 714                }
 715            }
 716
 420717             else if (t == typeof(double)
 420718                || t == typeof(double?))
 54719            {
 54720                double dblValue = 0;
 54721                 if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out dblValue))
 54722                {
 54723                    return dblValue;
 724                }
 725                else
 0726                {
 0727                    throw new Exception("Double value expected");
 728                }
 729            }
 730
 366731             else if (t == typeof(float)
 366732                || t == typeof(float?))
 0733            {
 0734                float fltValue = 0;
 0735                 if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out fltValue))
 0736                {
 0737                    return fltValue;
 738                }
 739                else
 0740                {
 0741                    throw new Exception("Float value expected");
 742                }
 743            }
 744
 366745             else if (t == typeof(DateTime)
 366746                || t == typeof(DateTime?))
 84747            {
 84748                DateTime dtValue = DateTime.MinValue;
 84749                 if (DateTime.TryParse(value, out dtValue))
 84750                {
 84751                    return dtValue;
 752                }
 753                else
 0754                {
 0755                    throw new Exception("DateTime value expected");
 756                }
 757            }
 758            //fix Issue #141
 282759             else if (t == typeof(bool)
 282760                || t == typeof(bool?))
 36761            {
 36762                bool boolValue = false;
 36763                 if (bool.TryParse(value, out boolValue))
 6764                {
 6765                    return boolValue;
 766                }
 767                else
 30768                {
 30769                     switch (value)
 770                    {
 18771                        case "0": return false;
 0772                        case "1": return true;
 773                        default:
 12774                            throw new Exception("Boolean value expected");
 775                    }
 776                }
 777            }
 778
 779            //Otherwise, return the string
 246780            return value;
 551781        }
 782
 783        public static bool ValueNeedsConverting(ConditionOperator conditionOperator)
 833784        {
 833785            return !OperatorsNotToConvertArray.Contains(conditionOperator);
 833786        }
 787
 788        public static object GetConditionExpressionValueCast(string value, XrmFakedContext ctx, string sEntityName, stri
 993789        {
 993790             if (ctx.ProxyTypesAssembly != null)
 833791            {
 792                //We have proxy types so get appropiate type value based on entity name and attribute type
 833793                var reflectedType = ctx.FindReflectedType(sEntityName);
 833794                 if (reflectedType != null)
 833795                {
 833796                    var attributeType = ctx.FindReflectedAttributeType(reflectedType, sEntityName, sAttributeName);
 833797                     if (attributeType != null)
 833798                    {
 799                        try
 833800                        {
 833801                             if (ValueNeedsConverting(op))
 563802                            {
 563803                                return GetValueBasedOnType(attributeType, value);
 804                            }
 805
 806                            else
 270807                            {
 270808                                return int.Parse(value);
 809                            }
 810                        }
 12811                        catch (Exception e)
 12812                        {
 12813                            throw new Exception(string.Format("When trying to parse value for entity {0} and attribute {
 814                        }
 815
 816                    }
 0817                }
 0818            }
 819
 820
 821            //Try parsing a guid
 160822            Guid gOut = Guid.Empty;
 160823             if (Guid.TryParse(value, out gOut))
 6824                return gOut;
 825
 826            //Try checking if it is a numeric value, cause, from the fetchxml it
 827            //would be impossible to know the real typed based on the string value only
 828            // ex: "123" might compared as a string, or, as an int, it will depend on the attribute
 829            //    data type, therefore, in this case we do need to use proxy types
 830
 154831            bool bIsNumeric = false;
 154832            bool bIsDateTime = false;
 154833            double dblValue = 0.0;
 154834            decimal decValue = 0.0m;
 154835            int intValue = 0;
 836
 154837             if (double.TryParse(value, out dblValue))
 6838                bIsNumeric = true;
 839
 154840             if (decimal.TryParse(value, out decValue))
 6841                bIsNumeric = true;
 842
 154843             if (int.TryParse(value, out intValue))
 0844                bIsNumeric = true;
 845
 154846            DateTime dtValue = DateTime.MinValue;
 154847             if (DateTime.TryParse(value, out dtValue))
 18848                bIsDateTime = true;
 849
 154850             if (bIsNumeric || bIsDateTime)
 18851            {
 18852                throw new Exception("When using arithmetic values in Fetch a ProxyTypesAssembly must be used in order to
 853            }
 854
 855            //Default value
 136856            return value;
 963857        }
 858    }
 859}