public override void Initialize(string name, NameValueCollection config) { OutputObjectCacheName = config["outputObjectCacheName"] ?? AdxstudioCrmConfigurationManager.GetCrmSection().OutputObjectCacheName; base.Initialize(name, config); }
private static void LoadOutputCache(object sender, EventArgs e) { var name = AdxstudioCrmConfigurationManager.GetCrmSection().OutputObjectCacheName; var keys = HttpSingleton <OutputCacheKeyCollection> .GetInstance(name, () => new OutputCacheKeyCollection()); HttpContext.Current.Response.AddCacheItemDependencies(keys.ToArray()); }
/// <summary> /// Constructor /// </summary> public SubgridViewLayout(ViewConfiguration configuration, EntityReference source, Relationship relationship, string viewEntityLogicalName, EntityView view = null, string portalName = null, int languageCode = 0, bool addSelectColumn = false, bool addActionsColumn = false, string selectColumnHeaderText = "") : base(configuration, view, portalName, languageCode, addSelectColumn, addActionsColumn, selectColumnHeaderText) { if (source == null) { throw new ArgumentNullException("source"); } if (relationship == null) { throw new ArgumentNullException("relationship"); } if (string.IsNullOrWhiteSpace(viewEntityLogicalName)) { throw new ArgumentNullException("viewEntityLogicalName"); } Source = source; Relationship = relationship; if ((configuration.EnableEntityPermissions && AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) && configuration.AssociateActionLink.Enabled) { var serviceContext = PortalCrmConfigurationManager.CreateServiceContext(configuration.PortalName); var crmEntityPermissionProvider = new CrmEntityPermissionProvider(configuration.PortalName); configuration.AssociateActionLink.Enabled = crmEntityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.AppendTo, Retrieve(serviceContext, source)) && crmEntityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Append, viewEntityLogicalName); } }
private static void Initialize() { if (_initialized) { return; } lock (_initializeLock) { if (_initialized) { return; } OnInitializing(); var searchElement = AdxstudioCrmConfigurationManager.GetCrmSection().Search; _enabled = searchElement.Enabled; if (_enabled.GetValueOrDefault(false)) { _providers = new ProviderCollection <SearchProvider>(); foreach (ProviderSettings providerSettings in searchElement.Providers) { _providers.Add(InstantiateProvider <SearchProvider>(providerSettings)); } _providers.SetReadOnly(); if (searchElement.DefaultProvider == null) { throw new ProviderException("Specify a default search provider."); } try { _provider = _providers[searchElement.DefaultProvider]; } catch {} if (_provider == null) { var defaultProviderPropertyInformation = searchElement.ElementInformation.Properties["defaultProvider"]; const string message = "Default Search Provider could not be found."; throw defaultProviderPropertyInformation == null ? (Exception) new ProviderException(message) : new ConfigurationErrorsException(message, defaultProviderPropertyInformation.Source, defaultProviderPropertyInformation.LineNumber); } } _initialized = true; } }
protected virtual bool TryAssertByCrmEntityPermissionProvider(OrganizationServiceContext context, Entity entity) { if (!AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) { return(false); } var crmEntityPermissionProvider = new CrmEntityPermissionProvider(PortalName); return(crmEntityPermissionProvider.TryAssert(context, CrmEntityPermissionRight.Read, entity)); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!AdxstudioCrmConfigurationManager.GetCrmSection().MembershipProviderEnabled) { filterContext.Result = new HttpNotFoundResult(); return; } base.OnActionExecuting(filterContext); }
private bool ValidateEntityPermission(OrganizationServiceContext serviceContext, CrmEntitySearchResult result) { if (!AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) { return(false); } var permissionResult = new CrmEntityPermissionProvider(PortalName).TryAssert(serviceContext, result.Entity); return(permissionResult.RulesExist && permissionResult.CanRead); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!OpenAuthConfigurationManager.GetSection().Enabled&& !AdxstudioCrmConfigurationManager.GetCrmSection().IdentityModelEnabled) { filterContext.Result = new HttpNotFoundResult(); return; } base.OnActionExecuting(filterContext); }
public static string FederatedSignInUrl(this UrlHelper url, string returnUrl = null) { if (!AdxstudioCrmConfigurationManager.GetCrmSection().IdentityModelEnabled) { return(LocalSignInUrl(url, returnUrl)); } var fam = new AdxstudioFederationAuthenticationModule(url.RequestContext.HttpContext); var signInUrl = fam.GetSignInRequestUrl(GetReturnUrl(url, returnUrl)); return(signInUrl); }
public static void ConfigureSearchProvider(this IAppBuilder app, CrmWebsite website) { var searchElement = AdxstudioCrmConfigurationManager.GetCrmSection().Search; searchElement.Enabled = website.Settings.Get <bool>("Search/Enabled"); if (searchElement.Enabled) { if (searchElement.Providers.Count == 0) { ConfigureProviderSettings(searchElement, website); } } }
private CacheItemPolicy GetPolicy(ObjectCache cache, DateTime utcExpiry, string regionName) { // Add an output cache specific dependency item and key cache.AddOrGetExisting(_outputCacheDependency, _outputCacheDependency, ObjectCache.InfiniteAbsoluteExpiration, CacheRegionName); // Get the keys from HttpContext var name = AdxstudioCrmConfigurationManager.GetCrmSection().OutputObjectCacheName; var keys = HttpSingleton <OutputCacheKeyCollection> .GetInstance(name, () => new OutputCacheKeyCollection()); // Create Monitor and Policy objects var monitorKeys = keys.Select(d => d.ToLower()).ToArray(); var monitor = GetChangeMonitor(cache, monitorKeys, regionName); var policy = monitor.GetCacheItemPolicy(cache.Name); policy.AbsoluteExpiration = ToDateTimeOffset(utcExpiry); policy.RemovedCallback += CacheEventSource.Log.OnRemovedCallback; return(policy); }
protected virtual bool TryAssertByCrmEntityPermissionProvider(OrganizationServiceContext context, Entity entity, EntityReference regarding) { if (!AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) { return(false); } var crmEntityPermissionProvider = new CrmEntityPermissionProvider(PortalName); if (string.Equals(entity.LogicalName, "annotation", StringComparison.InvariantCulture) && regarding != null && string.Equals(regarding.LogicalName, "adx_portalcomment", StringComparison.InvariantCulture)) { // If can read portal comment, bypass assertion check on notes and assume read permission. return(TryAssertPortalCommentPermission(context, crmEntityPermissionProvider, CrmEntityPermissionRight.Read, regarding)); } return(crmEntityPermissionProvider.TryAssert(context, CrmEntityPermissionRight.Read, entity, regarding: regarding)); }
private Func <OrganizationServiceContext, Entity, bool> GetSecurityAssertion(string portalName) { var cmsSecurityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(portalName); if (!AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) { return((serviceContext, entity) => cmsSecurityProvider.TryAssert(serviceContext, entity, CrmEntityRight.Read)); } var entityPermissionProvider = new CrmEntityPermissionProvider(portalName); return((serviceContext, entity) => { if (cmsSecurityProvider.TryAssert(serviceContext, entity, CrmEntityRight.Read)) { return true; } var permissionResult = entityPermissionProvider.TryAssert(serviceContext, entity); return permissionResult.RulesExist && permissionResult.CanRead; }); }
private static string SignInUrlMembership(this UrlHelper url, string returnUrl = null) { if (!AdxstudioCrmConfigurationManager.GetCrmSection().MembershipProviderEnabled && !AdxstudioCrmConfigurationManager.GetCrmSection().IdentityModelEnabled && !OpenAuthConfigurationManager.GetSection().Enabled) { return(null); } var authenticationType = AdxstudioCrmConfigurationManager.GetCrmSection().LoginButtonAuthenticationType; if (_identityModelAuthenticationTypes.Contains(authenticationType, StringComparer.OrdinalIgnoreCase)) { return(FederatedSignInUrl(url, returnUrl)); } if (!string.IsNullOrWhiteSpace(authenticationType)) { return(OpenAuthSignInUrl(url, authenticationType, returnUrl)); } return(LocalSignInUrl(url, returnUrl)); }
private EntityPermissionsDrop GetPermissions() { if (!AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) { return(null); } if (FullEntity == null) { return(null); } using (var serviceContext = PortalViewContext.CreateServiceContext()) { var clone = serviceContext.MergeClone(FullEntity); var permissionResult = new CrmEntityPermissionProvider(PortalViewContext.PortalName) .TryAssert(serviceContext, clone); return(permissionResult == null ? null : new EntityPermissionsDrop(permissionResult)); } }
/// <summary> /// Constructor /// </summary> public ViewLayout(ViewConfiguration configuration, EntityView view = null, string portalName = null, int languageCode = 0, bool addSelectColumn = false, bool addActionsColumn = false, string selectColumnHeaderText = "") { Configuration = configuration; var serviceContext = PortalCrmConfigurationManager.CreateServiceContext(portalName); if (view == null) { view = Configuration.GetEntityView(serviceContext, languageCode); } View = view; ViewName = view.Name; Id = view.Id; SortExpression = view.SortExpression; var overrideColumns = new List <ViewColumn>(); if (addSelectColumn) { overrideColumns.Add(new ViewColumn("col-select", selectColumnHeaderText ?? string.Empty, null, 20, 0, true, ViewColumnType.Select)); } if (Configuration.ColumnOverrides.Any()) { foreach (var columnA in View.Columns) { var match = false; foreach (var columnB in Configuration.ColumnOverrides) { if (columnA.LogicalName == columnB.AttributeLogicalName) { match = true; overrideColumns.Add(new ViewColumn(columnB.AttributeLogicalName, string.IsNullOrWhiteSpace(columnB.DisplayName) ? columnA.Name : columnB.DisplayName, null, columnB.Width == 0 ? columnA.Width : columnB.Width, 0, columnA.SortDisabled)); } } if (!match) { overrideColumns.Add(new ViewColumn(columnA.LogicalName, columnA.Name, columnA.Metadata, columnA.Width, 0, columnA.SortDisabled)); } } } else { overrideColumns.AddRange(View.Columns.Select(c => new ViewColumn(c.LogicalName, c.Name, c.Metadata, c.Width, 0, c.SortDisabled))); } if (addActionsColumn) { overrideColumns.Add(new ViewColumn("col-action", configuration.ActionColumnHeaderText ?? "<span class='sr-only'>Actions</span>", null, configuration.ActionLinksColumnWidth, 0, true, ViewColumnType.Actions)); } ColumnsTotalWidth = overrideColumns.Sum(c => c.Width); // Adjust the widths to be percentage based foreach (var column in overrideColumns) { var columnWidth = overrideColumns.FirstOrDefault(o => o.LogicalName == column.LogicalName); if (columnWidth == null) { continue; } var width = Convert.ToDouble(columnWidth.Width) / ColumnsTotalWidth * 100; column.WidthAsPercent = width; } Columns = overrideColumns; if (configuration.EnableEntityPermissions && AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) { var insertActionEnabled = configuration.InsertActionLink.Enabled; var createViewActionLinks = configuration.ViewActionLinks.Where(viewAction => viewAction.Enabled && viewAction.Type == LinkActionType.Insert); if (insertActionEnabled || createViewActionLinks.Any()) { var crmEntityPermissionProvider = new CrmEntityPermissionProvider(configuration.PortalName); var canCreate = crmEntityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Create, configuration.EntityName); if (insertActionEnabled) { configuration.InsertActionLink.Enabled = canCreate; } foreach (var action in createViewActionLinks) { action.Enabled = canCreate; } } } // Produce a secure configuration converted to a Base64 string var configurationJson = JsonConvert.SerializeObject(configuration, new JsonSerializerSettings { Converters = new List <JsonConverter> { new UrlBuilderConverter() } }); var configurationByteArray = Encoding.UTF8.GetBytes(configurationJson); var protectedByteArray = MachineKey.Protect(configurationByteArray, "Secure View Configuration"); Base64SecureConfiguration = Convert.ToBase64String(protectedByteArray); }
public override T GetDependency <T>(string name) { if (AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) { var dependency = GetContentMapDependency <T>(); if (dependency != null) { return(dependency); } } if (typeof(T) == typeof(IEntityWebsiteProvider)) { return(new AdxEntityWebsiteProvider() as T); } if (typeof(T) == typeof(IEntityUrlProvider)) { return(new AdxEntityUrlProvider(new AdxEntityWebsiteProvider(), PortalName) as T); } if (typeof(T) == typeof(ICmsDataServiceQueryInterceptorProvider)) { return(new AdxCmsDataServiceQueryInterceptorProvider(PortalName) as T); } if (typeof(T) == typeof(IRegisterClientSideDependenciesProvider)) { return(new AdxRegisterClientSideDependenciesProvider() as T); } if (typeof(T) == typeof(ICmsEntityEditingMetadataProvider)) { return(new CmsEntityEditingMetadataProvider(PortalName) as T); } if (typeof(T) == typeof(ICrmEntityEditingMetadataProvider)) { return(new CrmEntityEditingMetadataProviderAdapter(new CmsEntityEditingMetadataProvider(PortalName), PortalName) as T); } if (typeof(T) == typeof(ICmsDataServiceProvider)) { return(new AdxCmsDataServiceProvider(PortalName) as T); } if (typeof(T) == typeof(ICmsEntityServiceProvider)) { return(new CmsEntityServiceProvider(PortalName) as T); } if (typeof(T) == typeof(IRedirectProvider)) { return(new CompositeRedirectProvider(new RedirectProvider(PortalName), new CanonicalUrlRedirectProvider(), new UrlHistoryRedirectProvider(PortalName)) as T); } if (typeof(T) == typeof(IPublishingStateTransitionSecurityProvider)) { return(new PublishingStateTransitionSecurityProvider() as T); } if (typeof(T) == typeof(ICrmEntityFileAttachmentProvider)) { return(new NotesFileAttachmentProvider(PortalName) as T); } if (typeof(T) == typeof(IPortalRouteHandlerProvider)) { return(new PortalRouteHandlerProvider(PortalName) as T); } return(base.GetDependency <T>(name)); }
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, IDictionary <string, string> customParameters = null) { PaginatedGridData data; //Search criteria with length 4000+ causes Generic SQL error Bug#371907 const int maxSearchLength = 3999; var searchCriteria = search?.Length > maxSearchLength?search.Substring(0, maxSearchLength) : search; using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.EntityGridController, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.GetData)) { if (viewConfiguration == null) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Invalid_Request"))); } if (pageSize < 0) { pageSize = DefaultPageSize; } if (pageSize > DefaultMaxPageSize && !overrideMaxPageSize) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format( "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); var website = HttpContext.GetWebsite(); var viewDataAdapter = SetViewDataAdapter(viewConfiguration, sortExpression, searchCriteria, filter, metaFilter, page, applyRecordLevelFilters, applyRelatedRecordFilter, filterRelationshipName, filterEntityName, filterAttributeName, filterValue, customParameters, dataAdapterDependencies, website); var result = viewDataAdapter.FetchEntities(); //If current page doesn't contain any records, but records exist in general, get those records from previous page for further rendering them. if (!result.Records.Any() && result.TotalRecordCount > 0) { viewDataAdapter = SetViewDataAdapter(viewConfiguration, sortExpression, searchCriteria, filter, metaFilter, page - 1, applyRecordLevelFilters, applyRelatedRecordFilter, filterRelationshipName, filterEntityName, filterAttributeName, filterValue, customParameters, dataAdapterDependencies, website); result = viewDataAdapter.FetchEntities(); } if (result.EntityPermissionDenied) { var permissionResult = new EntityPermissionResult(true); return(Json(permissionResult)); } var serviceContext = dataAdapterDependencies.GetServiceContext(); var organizationMoneyFormatInfo = new OrganizationMoneyFormatInfo(dataAdapterDependencies); var crmLcid = HttpContext.GetCrmLcid(); EntityRecord[] records; if (viewConfiguration.EnableEntityPermissions && AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled&& viewConfiguration.EntityName != "entitlement") { var crmEntityPermissionProvider = new CrmEntityPermissionProvider(); records = result.Records.Select(e => new EntityRecord(e, serviceContext, crmEntityPermissionProvider, viewDataAdapter.EntityMetadata, true, organizationMoneyFormatInfo: organizationMoneyFormatInfo, crmLcid: crmLcid)).ToArray(); } else { records = result.Records.Select(e => new EntityRecord(e, viewDataAdapter.EntityMetadata, serviceContext, organizationMoneyFormatInfo, crmLcid)).ToArray(); } records = FilterWebsiteRelatedRecords(records, dataAdapterDependencies.GetWebsite()); var totalRecordCount = result.TotalRecordCount; var disabledActionLinks = new List <DisabledItemActionLink>(); // Disable Create Related Record Action Links based on Filter Criteria. disabledActionLinks.AddRange(DisableActionLinksBasedOnFilterCriteria(serviceContext, viewDataAdapter.EntityMetadata, viewConfiguration.CreateRelatedRecordActionLinks, records)); // Disable Item Action Links based on Filter Criteria. disabledActionLinks.AddRange(DisableActionLinksBasedOnFilterCriteria(serviceContext, viewDataAdapter.EntityMetadata, viewConfiguration.ItemActionLinks, records)); data = new PaginatedGridData(records, totalRecordCount, page, pageSize, disabledActionLinks) { CreateActionMetadata = GetCreationActionMetadata(viewConfiguration, dataAdapterDependencies), MoreRecords = result.MoreRecords.GetValueOrDefault() || (totalRecordCount > (page * pageSize)) }; } var json = Json(data); json.MaxJsonLength = int.MaxValue; return(json); }
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); }
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) { if (viewConfiguration == null) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Invalid Request.")); } if (pageSize < 0) { pageSize = DefaultPageSize; } 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); var viewDataAdapter = applyRelatedRecordFilter && (!string.IsNullOrWhiteSpace(filterRelationshipName) && !string.IsNullOrWhiteSpace(filterEntityName)) ? new ViewDataAdapter(viewConfiguration, dataAdapterDependencies, filterRelationshipName, filterEntityName, filterAttributeName, filterValue ?? Guid.Empty, page, search, sortExpression, filter, metaFilter, applyRecordLevelFilters) : new ViewDataAdapter(viewConfiguration, dataAdapterDependencies, page, search, sortExpression, filter, metaFilter, applyRecordLevelFilters); var result = viewDataAdapter.FetchEntities(); 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 = result.Records.Select(e => new EntityRecord(e, serviceContext, crmEntityPermissionProvider, viewDataAdapter.EntityMetadata, true)); } else { records = result.Records.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); }
public void ProcessRequest(HttpContext context) { var section = AdxstudioCrmConfigurationManager.GetCrmSection(); var config = section.CacheFeed; if (!config.Enabled) { throw new HttpException("Feed isn't enabled."); } if (config.LocalOnly && !IsLocal(context.Request)) { throw new HttpException("Feed is local only."); } // Get the output content type, let the querystring override web.config value. Default value is JSON. ContentType outputType = ContentType.Json; bool queryStringOverrideContentType = false; if (!string.IsNullOrEmpty(context.Request[QueryKeys.ContentType])) { if (context.Request[QueryKeys.ContentType].ToLower().Contains("xml")) { queryStringOverrideContentType = true; outputType = ContentType.Xml; } else if (context.Request[QueryKeys.ContentType].ToLower().Contains("json")) { // Keep output type as JSON queryStringOverrideContentType = true; } } if (!queryStringOverrideContentType && !string.IsNullOrEmpty(config.ContentType) && config.ContentType.ToLower().Contains("xml")) { // web.config override to XML outputType = ContentType.Xml; } switch (outputType) { case ContentType.Xml: context.Response.ContentType = "text/xml"; break; case ContentType.Json: default: context.Response.ContentType = "text/json"; break; } context.Trace.IsEnabled = config.Traced; var showValues = config.ShowValues; bool showAll; bool.TryParse(context.Request["showAll"], out showAll); bool expanded; bool.TryParse(context.Request[QueryKeys.Expanded], out expanded); var regionName = context.Request["regionName"]; bool cacheFootprint; bool.TryParse(context.Request[QueryKeys.CacheFootprint], out cacheFootprint); var url = context.Request.Url; var alternateLink = new Uri(url.GetLeftPart(UriPartial.Path)); bool clear; var key = context.Request["key"]; var remove = context.Request["remove"]; var objectCacheName = context.Request["objectCacheName"] ?? config.ObjectCacheName; if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(objectCacheName)) { var cache = GetCache(objectCacheName); if (cache != null) { switch (outputType) { case ContentType.Xml: var feed = cache.GetFeed(key, null, null, alternateLink, alternateLink, showAll, regionName, showValues); Render(feed, context.Response.OutputStream, config.Stylesheet); break; case ContentType.Json: default: var json = cache.GetJson(key, null, null, alternateLink, alternateLink, showAll, regionName, showValues); Render(json, context.Response.OutputStream); break; } } } else if (!string.IsNullOrWhiteSpace(remove) && !string.IsNullOrWhiteSpace(objectCacheName)) { var cache = GetCache(objectCacheName); if (cache != null) { Remove(cache, remove, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet); } } else if (bool.TryParse(context.Request["clear"], out clear)) { if (string.IsNullOrWhiteSpace(objectCacheName)) { var caches = GetCaches(objectCacheName); foreach (var cache in caches) { Clear(cache, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet); } } else { var cache = GetCache(objectCacheName); if (cache != null) { Clear(cache, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet); } } } else if (cacheFootprint) { var caches = GetCaches(objectCacheName); RenderCacheFootprint(caches, context, outputType, expanded); } else { var caches = GetCaches(objectCacheName); RenderList(caches, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet); } }