private void RenderCurrentList(OrganizationServiceContext context, Guid viewId)
        {
            var savedQueryView = new SavedQueryView(context, viewId, LanguageCode);

            savedQueryView.FetchXml.Element("entity").Add(new XElement("filter", new XAttribute("type", "and"),
                                                                       new XElement("condition",
                                                                                    new XAttribute("attribute", PreviousStepEntityPrimaryKeyLogicalName),
                                                                                    new XAttribute("operator", "eq"),
                                                                                    new XAttribute("value", PreviousStepEntityID))));

            var viewConfiguration = new ViewConfiguration(savedQueryView)
            {
                DataPagerEnabled = false,
                FetchXml         = savedQueryView.FetchXml.ToString(),
                LanguageCode     = LanguageCode,
                PortalName       = PortalName
            };

            var crmEntityListView = new CrmEntityListView
            {
                ID                 = "CurrentList",
                LanguageCode       = LanguageCode,
                PortalName         = PortalName,
                ViewConfigurations = new List <ViewConfiguration> {
                    viewConfiguration
                },
                ListCssClass = "table table-striped",
                SelectMode   = EntityGridExtensions.GridSelectMode.Single
            };

            CurrentListPlaceholder.Controls.Add(crmEntityListView);
        }
Beispiel #2
0
        private Boolean CheckIfGlobalEntity(SavedQueryView queryView)
        {
            //Check if entity is a global entity
            QueryExpression queryGlobalEntities = new QueryExpression("gsc_globalentities");

            queryGlobalEntities.ColumnSet.AddColumns("gsc_name");
            queryGlobalEntities.Criteria.AddCondition("gsc_name", ConditionOperator.Equal, queryView.EntityLogicalName);

            EntityCollection globalEntitiesCollection = _service.ServiceContext.RetrieveMultiple(queryGlobalEntities);

            if (globalEntitiesCollection != null && globalEntitiesCollection.Entities.Count > 0)
            {
                return(true);
            }

            return(false);
        }
Beispiel #3
0
        private ActionResult GetData(ViewConfiguration viewConfiguration, string sortExpression, string search, string filter,
                                     string metaFilter, int page, int pageSize = DefaultPageSize, bool applyRecordLevelFilters = true,
                                     bool applyRelatedRecordFilter             = false, string filterRelationshipName = null, string filterEntityName = null,
                                     string filterAttributeName = null, Guid?filterValue = null, bool overrideMaxPageSize = false, string createdOnFilter = null)
        {
            if (viewConfiguration == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Invalid Request."));
            }

            if (pageSize < 0)
            {
                pageSize = DefaultPageSize;
            }

            viewConfiguration = EnableSearchForPriceList(viewConfiguration);

            if (pageSize > DefaultMaxPageSize && !overrideMaxPageSize)
            {
                Tracing.FrameworkInformation(GetType().FullName, "GetData",
                                             "pageSize={0} is greater than the allowed maximum page size of {1}. Page size has been constrained to {1}.",
                                             pageSize, DefaultMaxPageSize);
                pageSize = DefaultMaxPageSize;
            }

            var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: viewConfiguration.PortalName);

            #region - DMS Custom Filtering -
            CustomFetchXml converter = new CustomFetchXml(dataAdapterDependencies.GetServiceContext(), new XrmConnection());

            if (metaFilter != null)
            {
                if (metaFilter.IndexOf(",date") > 0)
                {
                    string   dateFilterString = metaFilter.Substring(metaFilter.IndexOf("date=") + 5);
                    string[] dateFilters      = dateFilterString.Split(new string[] { ",date=" }, StringSplitOptions.None);

                    /*int dateFromIndexStart = metaFilter.LastIndexOf("DateFrom=") + 9;
                     * int dateFromIndexEnd = metaFilter.LastIndexOf("&DateTo=") + 8;
                     * dateFilter = metaFilter.Substring(metaFilter.IndexOf("date=") + 5);
                     * int fieldNameIndex = metaFilter.LastIndexOf("&field=") + 7;
                     * string dateFromValue = metaFilter.Substring(dateFromIndexStart, 10);
                     * string dateToValue = metaFilter.Substring(dateFromIndexEnd, 10);
                     * string entityFieldName = metaFilter.Substring(fieldNameIndex, (metaFilter.Length - fieldNameIndex));*/

                    foreach (string dateFilter in dateFilters)
                    {
                        string[] dateFilterValues = dateFilter.Split('&');
                        DateTime?dateFromValue    = dateFilterValues[0].Split('=')[1] != "" ? (DateTime?)Convert.ToDateTime(dateFilterValues[0].Split('=')[1]) : null;
                        DateTime?dateToValue      = dateFilterValues[1].Split('=')[1] != "" ? (DateTime?)Convert.ToDateTime(dateFilterValues[1].Split('=')[1]) : null;
                        string   entityFieldName  = dateFilterValues[2].Split('=')[1];

                        viewConfiguration = converter.SetCustomFetchXml(viewConfiguration, dateFromValue, dateToValue, entityFieldName);
                        int start = metaFilter.LastIndexOf(",date");
                        metaFilter = metaFilter.Substring(0, start);
                    }
                }

                if (metaFilter.IndexOf(",prospect") > 0)
                {
                    int start = metaFilter.LastIndexOf(",prospect");

                    viewConfiguration = converter.FilterProspect(viewConfiguration);

                    metaFilter = metaFilter.Substring(0, start);
                }

                if (metaFilter.IndexOf(",statecode") > 0)
                {
                    int    start     = metaFilter.LastIndexOf(",statecode");
                    string statecode = metaFilter.Substring(metaFilter.IndexOf("statecode=") + 10);

                    viewConfiguration = converter.FilterRecordsbyStateCode(viewConfiguration, statecode);
                    metaFilter        = metaFilter.Substring(0, start);
                }

                if (metaFilter.IndexOf(",vehiclecolor") > 0)
                {
                    int    start        = metaFilter.LastIndexOf(",vehiclecolor");
                    string vehicleColor = metaFilter.Substring(metaFilter.IndexOf("vehiclecolor=") + 13);

                    viewConfiguration = converter.FilterRecordsbyVehicleColor(viewConfiguration, vehicleColor);
                    metaFilter        = metaFilter.Substring(0, start);
                }
            }


            viewConfiguration = converter.CustomFilterViews(viewConfiguration);
            //  viewConfiguration = converter.FilterRootBusinessUnitRecords(viewConfiguration);
            #endregion

            //disable related record filtering for Vehicle Lookup in PO
            var            serviceContext2 = dataAdapterDependencies.GetServiceContext();
            SavedQueryView queryView       = viewConfiguration.GetSavedQueryView(serviceContext2);
            if (queryView.Name == "Vehicle Lookup - PO Portal View")
            {
                applyRecordLevelFilters = false;
            }

            var viewDataAdapter = applyRelatedRecordFilter &&
                                  (!string.IsNullOrWhiteSpace(filterRelationshipName) &&
                                   !string.IsNullOrWhiteSpace(filterEntityName))
                 ? new CustomViewAdapter(viewConfiguration, dataAdapterDependencies, filterRelationshipName, filterEntityName,
                                         filterAttributeName, filterValue ?? Guid.Empty, page, search, sortExpression, filter, metaFilter, applyRecordLevelFilters)
                 : new CustomViewAdapter(viewConfiguration, dataAdapterDependencies, page, search, sortExpression, filter, metaFilter,
                                         applyRecordLevelFilters);

            var result        = viewDataAdapter.CustomFetchEntities(viewConfiguration);
            var resultRecords = result.Records;

            //   var filteredRecords = converter.FilterSharedEntityScope(viewConfiguration, result.Records);
            // var globalRecords = converter.FilterRootBusinessUnitRecords(viewConfiguration, filterEntityName, filterRelationshipName, filterValue, search);

            //var combinedResults = filteredRecords.Union(globalRecords);

            // combinedResults = combinedResults.GroupBy(x => x.Id).Select(y => y.First());

            //Custom Order By

            /*  string[] order = sortExpression.Split(' ');
             * var count = 0;
             *
             * foreach (var combinedResult in resultRecords)
             * {
             *    foreach (var attributes in combinedResult.Attributes)
             *    {
             *        var name = attributes.Key;
             *        if (name.Equals(order[0]))
             *        {
             *            count++;
             *
             *            var value = attributes.Value;
             *            var valueType = value.GetType().Name;
             *            if (valueType == "String")
             *            {
             *                if (order[1] == "DESC")
             *                    resultRecords = resultRecords.OrderByDescending(x => x.Contains(order[0]) ? x.Attributes[order[0]] : "");
             *                else
             *                    resultRecords = resultRecords.OrderBy(x => x.Contains(order[0]) ? x.Attributes[order[0]] : "");
             *            }
             *            else if (valueType == "Money")
             *            {
             *                if (order[1] == "DESC")
             *                    resultRecords = resultRecords.OrderByDescending(x => x.Contains(order[0]) ? x.GetAttributeValue<Money>(order[0]).ToString() : "");
             *                else
             *                    resultRecords = resultRecords.OrderBy(x => x.Contains(order[0]) ? x.GetAttributeValue<Money>(order[0]).ToString() : "");
             *            }
             *            else if (valueType == "OptionSetValue")
             *            {
             *                if (order[1] == "DESC")
             *                    resultRecords = resultRecords.OrderByDescending(x => x.Contains(order[0]) ? x.FormattedValues[order[0]] : "");
             *                else
             *                    resultRecords = resultRecords.OrderBy(x => x.Contains(order[0]) ? x.FormattedValues[order[0]] : "");
             *            }
             *            else if (valueType == "EntityReference")
             *            {
             *                if (order[1] == "DESC")
             *                    resultRecords = resultRecords.OrderByDescending(x => x.GetAttributeValue<EntityReference>(order[0]) != null ? x.GetAttributeValue<EntityReference>(order[0]).Name : "");
             *                else
             *                    resultRecords = resultRecords.OrderBy(x => x.GetAttributeValue<EntityReference>(order[0]) != null ? x.GetAttributeValue<EntityReference>(order[0]).Name : "");
             *            }
             *            break;
             *        }
             *    }
             *
             *    if (count > 0)
             *        break;
             * }
             * //Custom Order By Ends Here*/

            if (result.EntityPermissionDenied)
            {
                var permissionResult = new EntityPermissionResult(true);

                return(Json(permissionResult));
            }

            IEnumerable <EntityRecord> records;
            if (viewConfiguration.EnableEntityPermissions && AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled)
            {
                var serviceContext = dataAdapterDependencies.GetServiceContext();
                var crmEntityPermissionProvider = new CrmEntityPermissionProvider();

                records = resultRecords.Select(e => new EntityRecord(e, serviceContext, crmEntityPermissionProvider, viewDataAdapter.EntityMetadata, true));
            }
            else
            {
                records = resultRecords.Select(e => new EntityRecord(e, viewDataAdapter.EntityMetadata));
            }

            var totalRecordCount = result.TotalRecordCount;

            var data = new PaginatedGridData(records, totalRecordCount, page, pageSize);

            var json = Json(data);
            json.MaxJsonLength = int.MaxValue;

            //

            return(json);
        }
Beispiel #4
0
 internal static IEnumerable <FilterOptionGroup> ToFilterOptionGroups(OrganizationServiceContext context, IPortalContext portalContext, EntityMetadata entityMetadata,
                                                                      IEnumerable <Filter> filters, IEnumerable <Link> links, NameValueCollection query, SavedQueryView queryView, IViewConfiguration viewConfiguration, int languageCode)
 {
     return(filters.Select(f => ToFilterOptionGroup(entityMetadata, f, query, queryView, viewConfiguration, languageCode))
            .Union(links.Select(l => ToFilterOptionGroup(context, portalContext, l, query, languageCode)))
            .OrderBy(f => f.Order)
            .ToList());
 }
Beispiel #5
0
        private static FilterOptionGroup ToFilterOptionGroup(EntityMetadata entityMetadata, Filter filter,
                                                             NameValueCollection query, SavedQueryView currentView, IViewConfiguration viewConfiguration, int languageCode)
        {
            var id       = filter.Extensions.GetExtensionValue("id");
            var selected = query.GetValues(id) ?? new string[] { };

            return(new FilterOptionGroup
            {
                Id = id,
                Order = filter.Extensions.GetExtensionValue("uiorder"),
                SelectionMode = filter.Extensions.GetExtensionValue("uiselectionmode"),
                Label = ToFilterOptionGroupLabel(currentView.EntityMetadata, filter, viewConfiguration, languageCode),
                Options = GetFilterOptions(entityMetadata, filter, selected, languageCode),
            });
        }
        private void RenderDuplicatesList(OrganizationServiceContext context, Guid viewId, string latitudeFieldName, string longitudeFieldName, double latitude, double longitude, double distance)
        {
            var savedQueryView = new SavedQueryView(context, viewId, LanguageCode);

            var angularDistance        = distance / GeoHelpers.EarthRadiusInKilometers;
            var originLatitudeRadians  = GeoHelpers.DegreesToRadians(latitude);
            var originLongitudeRadians = GeoHelpers.DegreesToRadians(longitude);
            var minLatitudeRadians     = originLatitudeRadians - angularDistance;
            var maxLatitudeRadians     = originLatitudeRadians + angularDistance;
            var deltaLongitude         = Math.Asin(Math.Sin(angularDistance) / Math.Cos(originLatitudeRadians));
            var minLongitudeRadians    = originLongitudeRadians - deltaLongitude;
            var maxLongitudeRadians    = originLongitudeRadians + deltaLongitude;
            var minLatitude            = GeoHelpers.RadiansToDegrees(minLatitudeRadians);
            var maxLatitude            = GeoHelpers.RadiansToDegrees(maxLatitudeRadians);
            var minLongitude           = GeoHelpers.RadiansToDegrees(minLongitudeRadians);
            var maxLongitude           = GeoHelpers.RadiansToDegrees(maxLongitudeRadians);

            var minLatitudeCondition = new XElement("condition",
                                                    new XAttribute("attribute", latitudeFieldName),
                                                    new XAttribute("operator", "ge"),
                                                    new XAttribute("value", minLatitude));

            var maxLatitudeCondition = new XElement("condition",
                                                    new XAttribute("attribute", latitudeFieldName),
                                                    new XAttribute("operator", "le"),
                                                    new XAttribute("value", maxLatitude));

            var minLongitudeCondition = new XElement("condition",
                                                     new XAttribute("attribute", longitudeFieldName),
                                                     new XAttribute("operator", "ge"),
                                                     new XAttribute("value", minLongitude));

            var maxLongitudeCondition = new XElement("condition",
                                                     new XAttribute("attribute", longitudeFieldName),
                                                     new XAttribute("operator", "le"),
                                                     new XAttribute("value", maxLongitude));

            var notCurrentServiceRequest = new XElement("condition",
                                                        new XAttribute("attribute", PreviousStepEntityPrimaryKeyLogicalName),
                                                        new XAttribute("operator", "ne"),
                                                        new XAttribute("value", PreviousStepEntityID));

            savedQueryView.FetchXml.Element("entity").Add(new XElement("filter", new XAttribute("type", "and"), notCurrentServiceRequest,
                                                                       minLatitudeCondition, maxLatitudeCondition, minLongitudeCondition, maxLongitudeCondition));

            var viewConfiguration = new ViewConfiguration(savedQueryView)
            {
                DataPagerEnabled = false,
                FetchXml         = savedQueryView.FetchXml.ToString(),
                LanguageCode     = LanguageCode,
                PortalName       = PortalName
            };

            var response = context.Execute(new RetrieveMultipleRequest {
                Query = new FetchExpression(viewConfiguration.FetchXml.ToString())
            }) as RetrieveMultipleResponse;

            if (!response.EntityCollection.Entities.Any())
            {
                _isUnique = true;
                MoveToNextStep(PreviousStepEntityID);
                return;
            }

            var crmEntityListView = new CrmEntityListView
            {
                ID                 = "DuplicateList",
                LanguageCode       = LanguageCode,
                PortalName         = PortalName,
                ViewConfigurations = new List <ViewConfiguration> {
                    viewConfiguration
                },
                ListCssClass = "table table-striped",
                SelectMode   = EntityGridExtensions.GridSelectMode.Single
            };

            DuplicateListPlaceholder.Controls.Add(crmEntityListView);
        }
        protected virtual IEdmEntityObject BuildEdmEntityObject(Entity record, SavedQueryView view, IEnumerable <SavedQueryView.ViewColumn> viewColumns, EdmEntityTypeReference dataEntityTypeReference, EdmComplexTypeReference entityReferenceComplexTypeReference, EdmComplexTypeReference optionSetComplexTypeReference, string entityListIdString, string viewIdString)
        {
            if (record == null)
            {
                return(null);
            }

            var entityObject = new EdmEntityObject(dataEntityTypeReference);

            entityObject.TrySetPropertyValue(view.PrimaryKeyLogicalName, record.Id);

            foreach (var column in viewColumns)
            {
                var value = record.Attributes.Contains(column.LogicalName) ? record.Attributes[column.LogicalName] : null;

                if (value is AliasedValue)
                {
                    var aliasedValue = value as AliasedValue;
                    value = aliasedValue.Value;
                }

                if (column.Metadata == null)
                {
                    continue;
                }

                var propertyName = column.LogicalName;

                if (propertyName.Contains('.'))
                {
                    propertyName = string.Format("{0}-{1}", column.Metadata.EntityLogicalName, column.Metadata.LogicalName);
                }

                switch (column.Metadata.AttributeType)
                {
                case AttributeTypeCode.Money:
                    var     money      = value as Money;
                    decimal moneyValue = 0;
                    if (money != null)
                    {
                        moneyValue = money.Value;
                    }
                    entityObject.TrySetPropertyValue(propertyName, moneyValue);
                    break;

                case AttributeTypeCode.Customer:
                case AttributeTypeCode.Lookup:
                case AttributeTypeCode.Owner:
                    var entityReference = value as EntityReference;
                    if (entityReference == null)
                    {
                        continue;
                    }
                    var entityReferenceObject = new EdmComplexObject(entityReferenceComplexTypeReference);
                    entityReferenceObject.TrySetPropertyValue("Name", entityReference.Name);
                    entityReferenceObject.TrySetPropertyValue("Id", entityReference.Id);
                    entityObject.TrySetPropertyValue(propertyName, entityReferenceObject);
                    break;

                case AttributeTypeCode.State:
                    var stateOptionSet = value as OptionSetValue;
                    if (stateOptionSet == null)
                    {
                        continue;
                    }
                    var stateAttributeMetadata = column.Metadata as StateAttributeMetadata;
                    if (stateAttributeMetadata == null)
                    {
                        continue;
                    }
                    var stateOption = stateAttributeMetadata.OptionSet.Options.FirstOrDefault(o => o != null && o.Value != null && o.Value.Value == stateOptionSet.Value);
                    if (stateOption == null)
                    {
                        continue;
                    }
                    var stateLabel      = stateOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == LanguageCode) ?? stateOption.Label.GetLocalizedLabel();
                    var stateOptionName = stateLabel == null?stateOption.Label.GetLocalizedLabelString() : stateLabel.Label;

                    var stateOptionSetObject = new EdmComplexObject(optionSetComplexTypeReference);
                    stateOptionSetObject.TrySetPropertyValue("Name", stateOptionName);
                    stateOptionSetObject.TrySetPropertyValue("Value", stateOptionSet.Value);
                    entityObject.TrySetPropertyValue(propertyName, stateOptionSetObject);
                    break;

                case AttributeTypeCode.Picklist:
                    var optionSet = value as OptionSetValue;
                    if (optionSet == null)
                    {
                        continue;
                    }
                    var picklistAttributeMetadata = column.Metadata as PicklistAttributeMetadata;
                    if (picklistAttributeMetadata == null)
                    {
                        continue;
                    }
                    var option = picklistAttributeMetadata.OptionSet.Options.FirstOrDefault(o => o != null && o.Value != null && o.Value.Value == optionSet.Value);
                    if (option == null)
                    {
                        continue;
                    }
                    var label = option.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == LanguageCode) ?? option.Label.GetLocalizedLabel();
                    var name  = label == null?option.Label.GetLocalizedLabelString() : label.Label;

                    var optionSetObject = new EdmComplexObject(optionSetComplexTypeReference);
                    optionSetObject.TrySetPropertyValue("Name", name);
                    optionSetObject.TrySetPropertyValue("Value", optionSet.Value);
                    entityObject.TrySetPropertyValue(propertyName, optionSetObject);
                    break;

                case AttributeTypeCode.Status:
                    var statusOptionSet = value as OptionSetValue;
                    if (statusOptionSet == null)
                    {
                        continue;
                    }
                    var statusAttributeMetadata = column.Metadata as StatusAttributeMetadata;
                    if (statusAttributeMetadata == null)
                    {
                        continue;
                    }
                    var statusOption = statusAttributeMetadata.OptionSet.Options.FirstOrDefault(o => o != null && o.Value != null && o.Value.Value == statusOptionSet.Value);
                    if (statusOption == null)
                    {
                        continue;
                    }
                    var statusLabel      = statusOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == LanguageCode) ?? statusOption.Label.GetLocalizedLabel();
                    var statusOptionName = statusLabel == null?statusOption.Label.GetLocalizedLabelString() : statusLabel.Label;

                    var statusOptionSetObject = new EdmComplexObject(optionSetComplexTypeReference);
                    statusOptionSetObject.TrySetPropertyValue("Name", statusOptionName);
                    statusOptionSetObject.TrySetPropertyValue("Value", statusOptionSet.Value);
                    entityObject.TrySetPropertyValue(propertyName, statusOptionSetObject);
                    break;

                default:
                    entityObject.TrySetPropertyValue(propertyName, value);
                    break;
                }
                entityObject.TrySetPropertyValue("list-id", entityListIdString);
                entityObject.TrySetPropertyValue("view-id", viewIdString);
            }
            return(entityObject);
        }
        /// <summary>
        /// Get EdmModel
        /// </summary>
        /// <returns><see cref="IEdmModel"/></returns>
        public virtual IEdmModel GetEdmModel()
        {
            var serviceContext = Dependencies.GetServiceContext();
            var website        = Dependencies.GetWebsite();
            var model          = new EdmModel();
            var container      = new EdmEntityContainer(NamespaceName, ContainerName);

            model.AddElement(container);
            model.SetIsDefaultEntityContainer(container, true);

            var entitylists = GetEntityLists(website);

            if (!entitylists.Any())
            {
                return(model);
            }

            var entityReferenceType = new EdmComplexType(NamespaceName, "EntityReference");

            entityReferenceType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Guid);
            entityReferenceType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);

            var picklistType = new EdmComplexType(NamespaceName, "OptionSet");

            picklistType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            picklistType.AddStructuralProperty("Value", EdmPrimitiveTypeKind.Int32);

            model.AddElement(entityReferenceType);
            model.AddElement(picklistType);

            var entitySetNames = new List <string>();

            foreach (var entitylist in entitylists)
            {
                var entityListId             = entitylist.GetAttributeValue <Guid>("adx_entitylistid");
                var entityListEntityName     = entitylist.GetAttributeValue <string>("adx_entityname");
                var entityListEntityTypeName = entitylist.GetAttributeValue <string>("adx_odata_entitytypename");
                var entityListEntitySetName  = entitylist.GetAttributeValue <string>("adx_odata_entitysetname");
                var entityTypeName           = string.IsNullOrWhiteSpace(entityListEntityTypeName) ? entityListEntityName : entityListEntityTypeName;
                var entitySetName            = string.IsNullOrWhiteSpace(entityListEntitySetName) ? entityListEntityName : entityListEntitySetName;
                var entityPermissionsEnabled = entitylist.GetAttributeValue <bool>("adx_entitypermissionsenabled");
                if (entitySetNames.Contains(entitySetName))
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(string.Format("An Entity Set has already been defined with the name '{0}'. Entity Set could not added to the model. You must not have multiple Entity List records with OData enabled and the same Entity Name specified, otherwise specifiy a unique Entity Set Name and Entity Type Name in the Entity List's OData Settings in CRM.", entitySetName)));
                    continue;
                }
                entitySetNames.Add(entitySetName);
                var entityType   = new EdmEntityType(NamespaceName, entityTypeName);
                var viewIdString = entitylist.GetAttributeValue <string>("adx_odata_view");

                if (string.IsNullOrWhiteSpace(viewIdString))
                {
                    continue;
                }

                Guid viewId;

                Guid.TryParse(viewIdString, out viewId);

                var savedQuery = GetSavedQuery(viewId);

                var view = new SavedQueryView(serviceContext, savedQuery, LanguageCode);

                var columns = view.Columns;

                var key = entityType.AddStructuralProperty(view.PrimaryKeyLogicalName, EdmPrimitiveTypeKind.Guid);
                entityType.AddKeys(key);

                foreach (var column in columns)
                {
                    var attributeMetadata = column.Metadata;
                    var propertyName      = column.LogicalName;
                    if (propertyName.Contains('.'))
                    {
                        propertyName = string.Format("{0}-{1}", column.Metadata.EntityLogicalName, column.Metadata.LogicalName);
                    }
                    var edmPrimitiveTypeKind = MetadataHelpers.GetEdmPrimitiveTypeKindFromAttributeMetadata(attributeMetadata);
                    if (edmPrimitiveTypeKind != null)
                    {
                        entityType.AddStructuralProperty(propertyName, edmPrimitiveTypeKind.GetValueOrDefault(EdmPrimitiveTypeKind.None));
                    }
                    else
                    {
                        switch (attributeMetadata.AttributeType)
                        {
                        case AttributeTypeCode.Customer:
                        case AttributeTypeCode.Lookup:
                        case AttributeTypeCode.Owner:
                            entityType.AddStructuralProperty(propertyName, new EdmComplexTypeReference(entityReferenceType, true));
                            break;

                        case AttributeTypeCode.Picklist:
                        case AttributeTypeCode.State:
                        case AttributeTypeCode.Status:
                            entityType.AddStructuralProperty(propertyName, new EdmComplexTypeReference(picklistType, true));
                            break;
                        }
                    }
                }

                entityType.AddProperty(new EdmStructuralProperty(entityType, "list-id", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, true), entityListId.ToString(), EdmConcurrencyMode.None));
                entityType.AddProperty(new EdmStructuralProperty(entityType, "view-id", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, true), viewId.ToString(), EdmConcurrencyMode.None));
                entityType.AddProperty(new EdmStructuralProperty(entityType, "entity-permissions-enabled", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, true), entityPermissionsEnabled.ToString(), EdmConcurrencyMode.None));

                model.AddElement(entityType);
                container.AddEntitySet(entitySetName, entityType);
            }

            return(model);
        }
        /// <summary>
        /// Creates the HTML to render a subgrid listing of records defined by the associated view
        /// </summary>
        protected virtual IHtmlString BuildGrid(HtmlControl container, OrganizationServiceContext context, Guid[] viewGuids,
                                                Guid viewId, Guid entityId, Entity user)
        {
            var portalContext = PortalCrmConfigurationManager.CreatePortalContext(Metadata.FormView.ContextName);
            var html          = Mvc.Html.EntityExtensions.GetHtmlHelper(Metadata.FormView.ContextName, container.Page.Request.RequestContext, container.Page.Response);
            var source        = new EntityReference(Metadata.TargetEntityName, entityId);
            var relationship  = new Relationship(Metadata.ViewRelationshipName);

            var metadataManyToMany    = EntityMetadata.ManyToManyRelationships.FirstOrDefault(r => r.SchemaName == Metadata.ViewRelationshipName);
            var relationshipManyToOne = EntityMetadata.ManyToOneRelationships.FirstOrDefault(r => r.SchemaName == Metadata.ViewRelationshipName);
            var relationshipOneToMany = EntityMetadata.OneToManyRelationships.FirstOrDefault(r => r.SchemaName == Metadata.ViewRelationshipName);

            if (relationshipManyToOne != null && relationshipOneToMany != null)             // self referential
            {
                relationship.PrimaryEntityRole = EntityRole.Referenced;
            }
            else if (metadataManyToMany != null && metadataManyToMany.Entity1LogicalName == metadataManyToMany.Entity2LogicalName)
            {
                relationship.PrimaryEntityRole = EntityRole.Referencing;
            }

            var settings = Metadata.SubgridSettings;

            var viewConfigurations = new List <ViewConfiguration>();

            var cssClass             = (settings != null) ? settings.CssClass : null;
            var gridCssClass         = (settings != null) ? settings.GridCssClass : null;
            var gridColumnWidthStyle = (settings != null && settings.GridColumnWidthStyle != null) ? settings.GridColumnWidthStyle.GetValueOrDefault(EntityGridExtensions.GridColumnWidthStyle.Percent) : EntityGridExtensions.GridColumnWidthStyle.Percent;

            var accessDeniedMessage = (settings != null) ? Localization.GetLocalizedString(settings.AccessDeniedMessage, Metadata.LanguageCode) : null;
            var errorMessage        = (settings != null) ? Localization.GetLocalizedString(settings.ErrorMessage, Metadata.LanguageCode) : null;
            var loadingMessage      = (settings != null) ? Localization.GetLocalizedString(settings.LoadingMessage, Metadata.LanguageCode) : null;
            var emptyMessage        = (settings != null) ? Localization.GetLocalizedString(settings.EmptyMessage, Metadata.LanguageCode) : null;

            var modalLookup = (settings != null) ? settings.LookupDialog : null;

            var modalLookupSelectedRecordsTitle = modalLookup == null ? null : Localization.GetLocalizedString(modalLookup.SelectRecordsTitle, Metadata.LanguageCode);
            var modalLookupCssClass             = modalLookup == null ? null : modalLookup.CssClass;
            var modalLookupTitle                   = modalLookup == null ? null : Localization.GetLocalizedString(modalLookup.Title, Metadata.LanguageCode);
            var modalLookupTitleCssClass           = modalLookup == null ? null : modalLookup.TitleCssClass;
            var modalLookupPrimaryButtonText       = modalLookup == null ? null : Localization.GetLocalizedString(modalLookup.PrimaryButtonText, Metadata.LanguageCode);
            var modalLookupDismissButtonSrText     = modalLookup == null ? null : Localization.GetLocalizedString(modalLookup.DismissButtonSrText, Metadata.LanguageCode);
            var modalLookupCloseButtonText         = modalLookup == null ? null : Localization.GetLocalizedString(modalLookup.CloseButtonText, Metadata.LanguageCode);
            var modalLookupPrimaryButtonCssClass   = modalLookup == null ? null : modalLookup.PrimaryButtonCssClass;
            var modalLookupCloseButtonCssClass     = modalLookup == null ? null : modalLookup.CloseButtonCssClass;
            var modalLookupGridContainerCssClass   = modalLookup == null ? null : modalLookup.GridSettings == null ? null : modalLookup.GridSettings.CssClass;
            var modalLookupGridCssClass            = modalLookup == null ? null : modalLookup.GridSettings == null ? null : modalLookup.GridSettings.GridCssClass;
            var modalLookupGridLoadingMessage      = modalLookup == null ? null : modalLookup.GridSettings == null ? null : Localization.GetLocalizedString(modalLookup.GridSettings.LoadingMessage, Metadata.LanguageCode);
            var modalLookupGridErrorMessage        = modalLookup == null ? null : modalLookup.GridSettings == null ? null : Localization.GetLocalizedString(modalLookup.GridSettings.ErrorMessage, Metadata.LanguageCode);
            var modalLookupGridAccessDeniedMessage = modalLookup == null ? null : modalLookup.GridSettings == null ? null : Localization.GetLocalizedString(modalLookup.GridSettings.AccessDeniedMessage, Metadata.LanguageCode);
            var modalLookupGridEmptyMessage        = modalLookup == null ? null : modalLookup.GridSettings == null ? null : Localization.GetLocalizedString(modalLookup.GridSettings.EmptyMessage, Metadata.LanguageCode);
            var modalLookupDefaultErrorMessage     = modalLookup == null ? null : Localization.GetLocalizedString(modalLookup.DefaultErrorMessage, Metadata.LanguageCode);

            var modalDetailsForm                    = (settings != null) ? settings.DetailsFormDialog : null;
            var modalDetailsFormCssClass            = modalDetailsForm == null ? null : modalDetailsForm.CssClass;
            var modalDetailsFormTitle               = modalDetailsForm == null ? null : Localization.GetLocalizedString(modalDetailsForm.Title, Metadata.LanguageCode);
            var modalDetailsFormTitleCssClass       = modalDetailsForm == null ? null : modalDetailsForm.TitleCssClass;
            var modalDetailsFormLoadingMessage      = modalDetailsForm == null ? null : Localization.GetLocalizedString(modalDetailsForm.LoadingMessage, Metadata.LanguageCode);
            var modalDetailsFormDismissButtonSrText = modalDetailsForm == null ? null : Localization.GetLocalizedString(modalDetailsForm.DismissButtonSrText, Metadata.LanguageCode);
            var modalDetailsFormSize                = (modalDetailsForm != null && modalDetailsForm.Size != null) ? modalDetailsForm.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Large) : BootstrapExtensions.BootstrapModalSize.Large;

            var modalEditForm                    = (settings != null) ? settings.EditFormDialog : null;
            var modalEditFormCssClass            = modalEditForm == null ? null : modalEditForm.CssClass;
            var modalEditFormTitle               = modalEditForm == null ? null : Localization.GetLocalizedString(modalEditForm.Title, Metadata.LanguageCode);
            var modalEditFormTitleCssClass       = modalEditForm == null ? null : modalEditForm.TitleCssClass;
            var modalEditFormLoadingMessage      = modalEditForm == null ? null : Localization.GetLocalizedString(modalEditForm.LoadingMessage, Metadata.LanguageCode);
            var modalEditFormDismissButtonSrText = modalEditForm == null ? null : Localization.GetLocalizedString(modalEditForm.DismissButtonSrText, Metadata.LanguageCode);
            var modalEditFormSize                = (modalEditForm != null && modalEditForm.Size != null) ? modalEditForm.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Large) : BootstrapExtensions.BootstrapModalSize.Large;

            var modalCreateForm                    = (settings != null) ? settings.CreateFormDialog : null;
            var modalCreateFormCssClass            = modalCreateForm == null ? null : modalCreateForm.CssClass;
            var modalCreateFormTitle               = modalCreateForm == null ? null : Localization.GetLocalizedString(modalCreateForm.Title, Metadata.LanguageCode);
            var modalCreateFormTitleCssClass       = modalCreateForm == null ? null : modalCreateForm.TitleCssClass;
            var modalCreateFormLoadingMessage      = modalCreateForm == null ? null : Localization.GetLocalizedString(modalCreateForm.LoadingMessage, Metadata.LanguageCode);
            var modalCreateFormDismissButtonSrText = modalCreateForm == null ? null : Localization.GetLocalizedString(modalCreateForm.DismissButtonSrText, Metadata.LanguageCode);
            var modalCreateFormSize                = (modalCreateForm != null && modalCreateForm.Size != null) ? modalCreateForm.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Large) : BootstrapExtensions.BootstrapModalSize.Large;


            var modalDelete                    = (settings != null) ? settings.DeleteDialog : null;
            var modalDeleteCssClass            = modalDelete == null ? null : modalDelete.CssClass;
            var modalDeleteTitle               = modalDelete == null ? null : Localization.GetLocalizedString(modalDelete.Title, Metadata.LanguageCode);
            var modalDeleteTitleCssClass       = modalDelete == null ? null : modalDelete.TitleCssClass;
            var modalDeletePrimaryButtonText   = modalDelete == null ? null : Localization.GetLocalizedString(modalDelete.PrimaryButtonText, Metadata.LanguageCode);
            var modalDeleteCloseButtonText     = modalDelete == null ? null : Localization.GetLocalizedString(modalDelete.CloseButtonText, Metadata.LanguageCode);
            var modalDeleteDismissButtonSrText = modalDelete == null ? null : Localization.GetLocalizedString(modalDelete.DismissButtonSrText, Metadata.LanguageCode);
            var modalDeleteSize                = (modalDelete != null && modalDelete.Size != null) ? modalDelete.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Default) : BootstrapExtensions.BootstrapModalSize.Default;
            var modalDeleteBody                = modalDelete == null ? null : Localization.GetLocalizedString(modalDelete.Confirmation, Metadata.LanguageCode);

            var modalError                    = (settings != null) ? settings.ErrorDialog : null;
            var modalErrorSize                = (modalError != null && modalError.Size != null) ? modalError.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Default) : BootstrapExtensions.BootstrapModalSize.Default;
            var modalErrorCssClass            = modalError == null ? null : modalError.CssClass;
            var modalErrorTitle               = modalError == null ? null : Localization.GetLocalizedString(modalError.Title, Metadata.LanguageCode);
            var modalErrorTitleCssClass       = modalError == null ? null : modalError.TitleCssClass;
            var modalErrorDismissButtonSrText = modalError == null ? null : Localization.GetLocalizedString(modalError.DismissButtonSrText, Metadata.LanguageCode);
            var modalErrorCloseButtonText     = modalError == null ? null : Localization.GetLocalizedString(modalError.CloseButtonText, Metadata.LanguageCode);
            var modalErrorBody                = modalError == null ? null : Localization.GetLocalizedString(modalError.Body, Metadata.LanguageCode);

            var modalLookupGridPageSize = html.IntegerSetting("Portal/Lookup/Modal/Grid/PageSize") ?? 10;
            var modalLookupSizeSetting  = html.Setting("Portal/Lookup/Modal/Size");
            var modalLookupSize         = BootstrapExtensions.BootstrapModalSize.Large;

            if (modalLookupSizeSetting != null && modalLookupSizeSetting.ToLower() == "default")
            {
                modalLookupSize = BootstrapExtensions.BootstrapModalSize.Default;
            }
            if (modalLookupSizeSetting != null && modalLookupSizeSetting.ToLower() == "small")
            {
                modalLookupSize = BootstrapExtensions.BootstrapModalSize.Small;
            }

            var modalCreateRelatedRecord                    = (settings != null) ? settings.CreateRelatedRecordDialog : null;
            var modalCreateRelatedRecordCssClass            = modalCreateRelatedRecord == null ? null : modalCreateRelatedRecord.CssClass;
            var modalCreateRelatedRecordTitle               = modalCreateRelatedRecord == null ? null : Localization.GetLocalizedString(modalCreateRelatedRecord.Title, Metadata.LanguageCode);
            var modalCreateRelatedRecordTitleCssClass       = modalCreateRelatedRecord == null ? null : modalCreateRelatedRecord.TitleCssClass;
            var modalCreateRelatedRecordLoadingMessage      = modalCreateRelatedRecord == null ? null : Localization.GetLocalizedString(modalCreateRelatedRecord.LoadingMessage, Metadata.LanguageCode);
            var modalCreateRelatedRecordDismissButtonSrText = modalCreateRelatedRecord == null ? null : Localization.GetLocalizedString(modalCreateRelatedRecord.DismissButtonSrText, Metadata.LanguageCode);
            var modalCreateRelatedRecordSize                = (modalCreateRelatedRecord != null && modalCreateRelatedRecord.Size != null) ? modalCreateRelatedRecord.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Large) : BootstrapExtensions.BootstrapModalSize.Large;

            foreach (var viewGuid in viewGuids)
            {
                var savedQueryView = new SavedQueryView(context, viewGuid, Metadata.LanguageCode);

                if (savedQueryView.FetchXml == null)
                {
                    continue;
                }

                var fetch = Fetch.Parse(savedQueryView.FetchXml);

                AddFiltersToFetch(context, fetch, entityId.ToString());

                var viewConfiguration = new ViewConfiguration(portalContext, savedQueryView, Metadata.ViewRecordsPerPage ?? 0,
                                                              fetch.ToXml().ToString(), new ViewSearch(Metadata.ViewEnableQuickFind), Metadata.FormView.EnableEntityPermissions,
                                                              settings, Metadata.LanguageCode, ContextName, Metadata.ViewRelationshipName, Metadata.ViewTargetEntityType, viewGuid,
                                                              modalLookupGridPageSize)
                {
                    SubgridFormEntityId          = entityId,
                    SubgridFormEntityLogicalName = Metadata.TargetEntityName
                };

                viewConfigurations.Add(viewConfiguration);
            }

            return(!string.IsNullOrWhiteSpace(Metadata.ViewRelationshipName)
                                ? html.EntitySubGrid(source, relationship, viewConfigurations,
                                                     EntityListFunctions.BuildControllerActionUrl("GetSubgridData", "EntityGrid", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }), user,
                                                     string.Join(" ", new[] { CssClass, cssClass }).TrimEnd(' '),
                                                     string.Join(" ", new[] { "table-striped", gridCssClass }).TrimEnd(' '),
                                                     gridColumnWidthStyle, EntityGridExtensions.GridSelectMode.None, null, loadingMessage,
                                                     errorMessage, accessDeniedMessage, emptyMessage, Metadata.FormView.ContextName, Metadata.LanguageCode, false, true,
                                                     modalDetailsFormSize, modalDetailsFormCssClass, modalDetailsFormTitle, modalDetailsFormLoadingMessage, modalDetailsFormDismissButtonSrText,
                                                     modalDetailsFormTitleCssClass, modalCreateFormSize, modalCreateFormCssClass, modalCreateFormTitle,
                                                     modalCreateFormLoadingMessage, modalCreateFormDismissButtonSrText, modalCreateFormTitleCssClass, modalEditFormSize,
                                                     modalEditFormCssClass, modalEditFormTitle, modalEditFormLoadingMessage, modalEditFormDismissButtonSrText,
                                                     modalEditFormTitleCssClass, modalDeleteSize, modalDeleteCssClass, modalDeleteTitle, modalDeleteBody,
                                                     modalDeletePrimaryButtonText, modalDeleteCloseButtonText, modalDeleteDismissButtonSrText, modalDeleteTitleCssClass,
                                                     modalErrorSize, modalErrorCssClass, modalErrorTitle, modalErrorBody, modalErrorDismissButtonSrText,
                                                     modalErrorCloseButtonText, modalErrorTitleCssClass, modalLookupCssClass,
                                                     modalLookupTitle, modalLookupSelectedRecordsTitle, modalLookupPrimaryButtonText, modalLookupCloseButtonText,
                                                     modalLookupDismissButtonSrText, modalLookupTitleCssClass, modalLookupPrimaryButtonCssClass,
                                                     modalLookupCloseButtonCssClass, modalLookupGridContainerCssClass, modalLookupGridCssClass,
                                                     modalLookupGridLoadingMessage, modalLookupGridErrorMessage, modalLookupGridAccessDeniedMessage,
                                                     modalLookupGridEmptyMessage, modalLookupDefaultErrorMessage, modalLookupSize, modalCreateRelatedRecordSize, modalCreateRelatedRecordCssClass, modalCreateRelatedRecordTitle, modalCreateRelatedRecordLoadingMessage,
                                                     modalCreateRelatedRecordDismissButtonSrText, modalCreateRelatedRecordTitleCssClass)
                                : html.EntitySubGrid(viewConfigurations,
                                                     EntityListFunctions.BuildControllerActionUrl("GetSubgridData", "EntityGrid", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }), user,
                                                     string.Join(" ", new[] { CssClass, cssClass }).TrimEnd(' '),
                                                     string.Join(" ", new[] { "table-striped", gridCssClass }).TrimEnd(' '), gridColumnWidthStyle,
                                                     EntityGridExtensions.GridSelectMode.None, null, loadingMessage, errorMessage, accessDeniedMessage, emptyMessage,
                                                     Metadata.FormView.ContextName, Metadata.LanguageCode, false, true, modalDetailsFormSize, modalDetailsFormCssClass,
                                                     modalDetailsFormTitle, modalDetailsFormLoadingMessage, modalDetailsFormDismissButtonSrText,
                                                     modalDetailsFormTitleCssClass, modalCreateFormSize, modalCreateFormCssClass, modalCreateFormTitle,
                                                     modalCreateFormLoadingMessage, modalCreateFormDismissButtonSrText, modalCreateFormTitleCssClass, modalEditFormSize,
                                                     modalEditFormCssClass, modalEditFormTitle, modalEditFormLoadingMessage, modalEditFormDismissButtonSrText,
                                                     modalEditFormTitleCssClass, modalDeleteSize, modalDeleteCssClass, modalDeleteTitle, modalDeleteBody,
                                                     modalDeletePrimaryButtonText, modalDeleteCloseButtonText, modalDeleteDismissButtonSrText, modalDeleteTitleCssClass,
                                                     modalErrorSize, modalErrorCssClass, modalErrorTitle, modalErrorBody, modalErrorDismissButtonSrText,
                                                     modalErrorCloseButtonText, modalErrorTitleCssClass, modalCreateRelatedRecordSize, modalCreateRelatedRecordCssClass, modalCreateRelatedRecordTitle, modalCreateRelatedRecordLoadingMessage,
                                                     modalCreateRelatedRecordDismissButtonSrText, modalCreateRelatedRecordTitleCssClass));
        }
Beispiel #10
0
        private Fetch FilterGlobalRecords(ViewConfiguration viewConfiguration)
        {
            SavedQueryView queryView  = viewConfiguration.GetSavedQueryView(_serviceContext);
            var            objectName = queryView.Name;

            Fetch fetch;

            if (viewConfiguration.FetchXml != null)
            {
                fetch = Fetch.Parse(viewConfiguration.FetchXml);
            }
            else
            {
                fetch = Fetch.Parse(queryView.FetchXml);
            }

            String webRole           = String.Empty;
            String parentustomerId   = String.Empty;
            String parentustomerType = String.Empty;
            var    accountField      = String.Empty;
            var    context           = HttpContext.Current;
            var    request           = context.Request.RequestContext;
            var    cookies           = request.HttpContext.Request.Cookies;

            if (cookies != null)
            {
                if (cookies["Branch"] != null)
                {
                    webRole           = cookies["Branch"]["webRoleName"];
                    parentustomerId   = cookies["Branch"]["parentCustomerId"];
                    parentustomerType = cookies["Branch"]["parentCustomerType"];
                    if (parentustomerType == "100000000")
                    {
                        accountField = "gsc_dealerid";
                    }
                    else if (parentustomerType == "100000001")
                    {
                        accountField = "gsc_branchid";
                    }
                }
            }

            if (!webRole.Contains("MMPC") && webRole != "Administrators")
            {
                //Check if entity is a global entity
                if (!CheckIfGlobalEntity(queryView))
                {
                    return(fetch);
                }
                else
                {
                    Filter filter = new Filter {
                        Type = LogicalOperator.Or
                    };
                    filter.Conditions = new List <Condition>();

                    filter.Conditions.Add(new Condition
                    {
                        Attribute = accountField,
                        Operator  = ConditionOperator.Equal,
                        Value     = parentustomerId
                    });

                    filter.Conditions.Add(new Condition
                    {
                        Attribute = "gsc_isglobalrecord",
                        Operator  = ConditionOperator.Equal,
                        Value     = true
                    });

                    fetch.Entity.Filters.Add(filter);
                }
            }

            return(fetch);
        }
Beispiel #11
0
        private Fetch FilterSharedEntityScope(Fetch fetch, ViewConfiguration viewConfiguration)
        {
            SavedQueryView queryView  = viewConfiguration.GetSavedQueryView(_serviceContext);
            var            objectName = queryView.Name;

            EntityCollection entityPermission = GetSharedEntityScope(fetch);

            if (entityPermission == null)
            {
                return(fetch);
            }

            String scope = "";

            if (objectName.Equals("Individual") || objectName.Equals("Corporate"))
            {
                scope = GetReadAppendScope(entityPermission, "adx_append");
            }
            else
            {
                scope = GetReadAppendScope(entityPermission, "adx_read");
            }

            if (scope == "Global")
            {
                return(fetch);
            }

            else if (scope == "Account")
            {
                Guid   branchId = Guid.Empty;
                Guid   userId   = Guid.Empty;
                String webRole  = String.Empty;
                var    context  = HttpContext.Current;
                var    request  = context.Request.RequestContext;
                var    cookies  = request.HttpContext.Request.Cookies;
                if (cookies != null)
                {
                    if (cookies["Branch"] != null)
                    {
                        branchId = new Guid(cookies["Branch"]["branchId"]);
                        userId   = new Guid(cookies["Branch"]["userId"]);
                        webRole  = cookies["Branch"]["webRoleName"];
                    }
                }

                if (webRole.Contains("Sales Supervisor") && (objectName.Equals("Individual") || objectName.Equals("Corporate")))
                {
                    Link relatedEntity = new Link();
                    relatedEntity.Alias         = "Related";
                    relatedEntity.FromAttribute = "contactid";
                    relatedEntity.Name          = "contact";
                    relatedEntity.ToAttribute   = "gsc_salesexecutiveid";
                    fetch.Entity.Links.Add(relatedEntity);

                    Filter filter = new Filter {
                        Type = LogicalOperator.Or
                    };
                    filter.Conditions = new List <Condition>();

                    filter.Conditions.Add(new Condition
                    {
                        Attribute = "gsc_salesexecutiveid",
                        Operator  = ConditionOperator.Equal,
                        Value     = userId
                    });

                    filter.Conditions.Add(new Condition
                    {
                        EntityName = "Related",
                        Attribute  = "gsc_reportsto",
                        Operator   = ConditionOperator.Equal,
                        Value      = userId
                    });

                    fetch.Entity.Filters.Add(filter);
                }
                else
                {
                    Filter filter = new Filter {
                        Type = LogicalOperator.And
                    };
                    filter.Conditions = new List <Condition>();
                    filter.Conditions.Add(new Condition
                    {
                        Attribute = "gsc_branchid",
                        Operator  = ConditionOperator.Equal,
                        Value     = branchId
                    });

                    fetch.Entity.Filters.Add(filter);
                }
            }
            else if (scope == "Contact")
            {
                Guid userId  = Guid.Empty;
                var  context = HttpContext.Current;
                var  request = context.Request.RequestContext;
                var  cookies = request.HttpContext.Request.Cookies;
                if (cookies != null)
                {
                    if (cookies["Branch"] != null)
                    {
                        userId = new Guid(cookies["Branch"]["userId"]);
                    }
                }

                Filter filter = new Filter {
                    Type = LogicalOperator.And
                };

                filter.Conditions = new List <Condition>();

                if (objectName.Equals("Individual") || objectName.Equals("Corporate"))
                {
                    filter.Conditions.Add(new Condition
                    {
                        Attribute = "gsc_salesexecutiveid",
                        Operator  = ConditionOperator.Equal,
                        Value     = userId
                    });
                }
                else
                {
                    filter.Conditions.Add(new Condition
                    {
                        Attribute = "gsc_recordownerid",
                        Operator  = ConditionOperator.Equal,
                        Value     = userId
                    });
                }

                fetch.Entity.Filters.Add(filter);
            }
            return(fetch);
        }