public ActionResult ExecuteWorkflow(EntityReference workflow, EntityReference entity) { string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var request = new ExecuteWorkflowRequest { WorkflowId = workflow.Id, EntityId = entity.Id }; serviceContext.Execute(request); serviceContext.TryRemoveFromCache(entity); return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
public ActionResult GetRepositories() { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext); var serviceContext = dataAdapterDependencies.GetServiceContext(); var website = dataAdapterDependencies.GetWebsite(); var repositories = serviceContext.CreateQuery("adx_packagerepository") .Where(e => e.GetAttributeValue <string>("adx_name") != null) .Where(e => e.GetAttributeValue <string>("adx_partialurl") != null) .Where(e => e.GetAttributeValue <int?>("statecode") == 0) .Where(e => e.GetAttributeValue <bool?>("adx_hidden").GetValueOrDefault(false) != true) .OrderBy(e => e.GetAttributeValue <int?>("adx_order")) .ThenBy(e => e.GetAttributeValue <string>("adx_name")) .ToArray(); AddCrossOriginAccessHeaders(Response); return(new JObjectResult(new JObject { { "Repositories", new JArray(repositories.Select(e => new JObject { { "Name", e.GetAttributeValue <string>("adx_name") }, { "URL", GetPackageRepositoryUrl(website.Id, e.GetAttributeValue <string>("adx_partialurl")) }, } )) }, })); }
protected void Page_PreRender(object sender, EventArgs args) { if (WebForm.CurrentSessionHistory == null) { return; } var currentStepId = WebForm.CurrentSessionHistory.CurrentStepId; if (currentStepId == Guid.Empty) { return; } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(PortalName, Request.RequestContext); var serviceContext = dataAdapterDependencies.GetServiceContext(); var step = serviceContext.CreateQuery("adx_webformstep") .FirstOrDefault(e => e.GetAttributeValue <Guid>("adx_webformstepid") == currentStepId); if (step == null) { return; } if (step.GetAttributeValue <EntityReference>("adx_nextstep") == null) { WebForm.ShowHideNextButton(false); } }
public ActionResult Status() { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext); // Check for existence of shopping cart schema, and return empty cart if not found. try { using (var serviceContext = dataAdapterDependencies.GetServiceContext()) { serviceContext.Execute(new RetrieveEntityRequest { LogicalName = "adx_shoppingcart", EntityFilters = EntityFilters.Entity }); } } catch (FaultException <OrganizationServiceFault> ) { return(ShoppingCart(0)); } var dataAdapter = new ShoppingCartDataAdapter(dataAdapterDependencies, HttpContext.Profile.UserName); var cart = dataAdapter.SelectCart(); if (cart == null) { return(ShoppingCart(0)); } var cartItems = cart.GetCartItems().ToArray(); return(ShoppingCart(cartItems.Sum(item => item.Quantity))); }
private static void CreateFiles(ICommandContext commandContext, DirectoryUploadInfo uploadInfo, IEnumerable <HttpPostedFile> files, EntityReference publishingState, out List <string> @select, out List <Tuple <string, string> > errors) { @select = new List <string>(); errors = new List <Tuple <string, string> >(); var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(); var annotationDataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var website = HttpContext.Current.GetWebsite(); var location = website.Settings.Get <string>("WebFiles/StorageLocation"); StorageLocation storageLocation; if (!Enum.TryParse(location, true, out storageLocation)) { storageLocation = StorageLocation.CrmDocument; } var maxFileSizeErrorMessage = website.Settings.Get <string>("WebFiles/MaxFileSizeErrorMessage"); var annotationSettings = new AnnotationSettings(dataAdapterDependencies.GetServiceContext(), storageLocation: storageLocation, maxFileSizeErrorMessage: maxFileSizeErrorMessage); foreach (var file in files) { var serviceContext = commandContext.CreateServiceContext(); try { var webFile = new Entity("adx_webfile"); var fileName = Path.GetFileName(file.FileName); webFile.Attributes["adx_name"] = fileName; webFile.Attributes["adx_partialurl"] = GetPartialUrlFromFileName(fileName); webFile.Attributes["adx_websiteid"] = website.Entity.ToEntityReference(); webFile.Attributes["adx_publishingstateid"] = publishingState; webFile.Attributes["adx_hiddenfromsitemap"] = true; webFile.Attributes[uploadInfo.WebFileForeignKeyAttribute] = uploadInfo.EntityReference; serviceContext.AddObject(webFile); serviceContext.SaveChanges(); annotationDataAdapter.CreateAnnotation(new Annotation { Regarding = webFile.ToEntityReference(), FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(file), annotationSettings.StorageLocation) }, annotationSettings); @select.Add(new DirectoryContentHash(webFile.ToEntityReference()).ToString()); } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Exception uploading file: {0}", e.ToString())); errors.Add(new Tuple <string, string>(file.FileName, e.Message)); } } }
/// <summary> /// Indicates whether entity permissions permit the user to add notes to the target entity. /// </summary> protected virtual bool TryAssertAddNote(Guid regardingId) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start Assert Add Note Privilege on: {0} {1}", Metadata.TargetEntityName, regardingId)); if (!Metadata.FormView.EnableEntityPermissions) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. Entity Permissions have not been enabled."); return(false); } var regarding = new EntityReference(Metadata.TargetEntityName, regardingId); var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(); var serviceContext = dataAdapterDependencies.GetServiceContext(); var entityPermissionProvider = new CrmEntityPermissionProvider(); if (!entityPermissionProvider.PermissionsExist) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. Entity Permissions have not been defined. Your request could not be completed."); return(false); } var entityType = IsTimeline ? "adx_portalcomment" : "annotation"; var entityMetadata = serviceContext.GetEntityMetadata(regarding.LogicalName, EntityFilters.All); var primaryKeyName = entityMetadata.PrimaryIdAttribute; var entity = serviceContext.CreateQuery(regarding.LogicalName) .First(e => e.GetAttributeValue <Guid>(primaryKeyName) == regarding.Id); var canAppendTo = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.AppendTo, entity, entityMetadata); var canCreate = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Create, entityType, regarding); var canAppend = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Append, entityType, regarding); if (canCreate & canAppend & canAppendTo) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Add Note Permission Granted: {0} {1}", EntityNamePrivacy.GetEntityName(Metadata.TargetEntityName), regardingId)); return(true); } if (!canCreate) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Create notes."); } else if (!canAppendTo) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Permission Denied. You do not have the appropriate Entity Permissions to Append To {0}.", EntityNamePrivacy.GetEntityName(entity.LogicalName))); } else { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Append notes."); } return(false); }
protected void AddNote_Click(object sender, EventArgs e) { var regardingContact = ServiceRequest.GetAttributeValue <EntityReference>(RegardingContactFieldName); if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id) { throw new InvalidOperationException("Unable to retrieve order."); } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies( requestContext: Request.RequestContext, portalName: PortalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); if (NewNotePublic.Checked) { if (!string.IsNullOrEmpty(NewNoteText.Text) || (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)) { var annotation = new Annotation { NoteText = string.Format("{0}{1}", AnnotationHelper.PublicAnnotationPrefix, NewNoteText.Text), Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies), Regarding = ServiceRequest.ToEntityReference() }; if (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(NewNoteAttachment.PostedFile)); } dataAdapter.CreateAnnotation(annotation); } } else { if (!string.IsNullOrEmpty(NewNoteText.Text) || (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)) { var annotation = new Annotation { NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, NewNoteText.Text), Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies), Regarding = ServiceRequest.ToEntityReference() }; if (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(NewNoteAttachment.PostedFile)); } dataAdapter.CreateAnnotation(annotation); } } Response.Redirect(Request.Url.PathAndQuery); }
private string GetPackageRepositoryUrl(Guid websiteId, Guid repositoryId) { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext); var serviceContext = dataAdapterDependencies.GetServiceContext(); var repository = serviceContext.CreateQuery("adx_packagerepository") .FirstOrDefault(e => e.GetAttributeValue <Guid>("adx_packagerepositoryid") == repositoryId && e.GetAttributeValue <string>("adx_partialurl") != null && e.GetAttributeValue <int?>("statecode") == 0); return(repository == null ? null : GetPackageRepositoryUrl(websiteId, repository.GetAttributeValue <string>("adx_partialurl"))); }
public ActionResult Index(Guid entityListId, Guid viewId, string category, string filter, string search) { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext); var serviceContext = dataAdapterDependencies.GetServiceContext(); var repository = serviceContext.CreateQuery("adx_packagerepository") .FirstOrDefault(e => e.GetAttributeValue <EntityReference>("adx_entitylistid") == new EntityReference("adx_entitylist", entityListId) && e.GetAttributeValue <int?>("statecode") == 0); if (repository == null) { return(HttpNotFound()); } return(Index(repository.ToEntityReference(), entityListId, viewId, category, filter, search)); }
public ActionResult Delete(EntityReference entityReference) { string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var entityPermissionProvider = new CrmEntityPermissionProvider(); if (!entityPermissionProvider.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Entity_Permissions_Have_Not_Been_Defined_Message"))); } var entityMetadata = serviceContext.GetEntityMetadata(entityReference.LogicalName, EntityFilters.All); var primaryKeyName = entityMetadata.PrimaryIdAttribute; var entity = serviceContext.CreateQuery(entityReference.LogicalName) .First(e => e.GetAttributeValue <Guid>(primaryKeyName) == entityReference.Id); var test = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Delete, entity); if (test) { using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.EntityGridController, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.Delete)) { serviceContext.DeleteObject(entity); serviceContext.SaveChanges(); } } else { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("No_Permissions_To_Delete_This_Record"))); } return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
public ActionResult Associate(AssociateRequest request) { string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var entityPermissionProvider = new CrmEntityPermissionProvider(); if (!entityPermissionProvider.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Entity_Permissions_Have_Not_Been_Defined_Message"))); } var relatedEntities = request.RelatedEntities .Where(e => entityPermissionProvider.TryAssertAssociation(serviceContext, request.Target, request.Relationship, e)) .ToArray(); if (!relatedEntities.Any()) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Missing_Permissions_For_Operation_Exception"))); } relatedEntities = FilterAlreadyAssociated(serviceContext, request.Relationship, request.Target, relatedEntities); var filtered = new AssociateRequest { Target = request.Target, Relationship = request.Relationship, RelatedEntities = new EntityReferenceCollection(relatedEntities) }; serviceContext.Execute(filtered); return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
protected override void ProcessRequest(HttpContext context, ICmsEntityServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, Entity entity, CmsEntityMetadata entityMetadata, ICrmEntitySecurityProvider security) { if (!IsRequestMethod(context.Request, "POST")) { throw new CmsEntityServiceException(HttpStatusCode.MethodNotAllowed, "Request method {0} not allowed for this resource.".FormatWith(context.Request.HttpMethod)); } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: context.Request.RequestContext, portalName: PortalName); var annotationDataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var website = context.GetWebsite(); var location = website.Settings.Get <string>("WebFiles/StorageLocation"); StorageLocation storageLocation; if (!Enum.TryParse(location, true, out storageLocation)) { storageLocation = StorageLocation.CrmDocument; } var maxFileSizeErrorMessage = website.Settings.Get <string>("WebFiles/MaxFileSizeErrorMessage"); var annotationSettings = new AnnotationSettings(dataAdapterDependencies.GetServiceContext(), storageLocation: storageLocation, maxFileSizeErrorMessage: maxFileSizeErrorMessage); var files = context.Request.Files; var postedFiles = new List <HttpPostedFile>(); for (var i = 0; i < files.Count; i++) { postedFiles.Add(files[i]); } foreach (var file in postedFiles) { annotationDataAdapter.CreateAnnotation(new Annotation { Regarding = entity.ToEntityReference(), FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(file), annotationSettings.StorageLocation) }, annotationSettings); } context.Response.ContentType = "text/plain"; context.Response.Write("OK"); }
public ActionResult Delete(EntityReference entityReference) { string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var entityPermissionProvider = new CrmEntityPermissionProvider(); if (!entityPermissionProvider.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Entity Permissions have not been defined. Your request could not be completed.")); } var entityMetadata = serviceContext.GetEntityMetadata(entityReference.LogicalName, EntityFilters.All); var primaryKeyName = entityMetadata.PrimaryIdAttribute; var entity = serviceContext.CreateQuery(entityReference.LogicalName) .First(e => e.GetAttributeValue <Guid>(primaryKeyName) == entityReference.Id); var test = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Delete, entity); if (test) { serviceContext.DeleteObject(entity); serviceContext.SaveChanges(); } else { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to delete this record.")); } return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
public ActionResult Disassociate(DisassociateRequest request) { string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var entityPermissionProvider = new CrmEntityPermissionProvider(); if (!entityPermissionProvider.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Entity Permissions have not been defined. Your request could not be completed.")); } var relatedEntities = request.RelatedEntities.Where( related => entityPermissionProvider.TryAssertAssociation(serviceContext, request.Target, request.Relationship, related)).ToList(); if (relatedEntities.Any()) { var filtered = new DisassociateRequest { Target = request.Target, Relationship = request.Relationship, RelatedEntities = new EntityReferenceCollection(relatedEntities) }; serviceContext.Execute(filtered); } else { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to disassociate the records.")); } return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
protected void Page_Load(object sender, EventArgs args) { var quoteId = WebForm.CurrentSessionHistory.QuoteId; if (quoteId == Guid.Empty) { GeneralErrorMessage.Visible = true; Order.Visible = false; Invoice.Visible = false; return; } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(PortalName, Request.RequestContext); var serviceContext = dataAdapterDependencies.GetServiceContext(); Entity order; if (!TryGetOrder(serviceContext, quoteId, out order)) { GeneralErrorMessage.Visible = true; Order.Visible = false; Invoice.Visible = false; return; } Entity invoice; if (TryGetInvoice(serviceContext, order, out invoice)) { ShowInvoice(serviceContext, invoice); return; } ShowOrder(serviceContext, order); GeneralErrorMessage.Visible = false; Order.Visible = true; Invoice.Visible = false; }
public ActionResult PackageVersion(Guid packageVersionId) { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var serviceContext = dataAdapterDependencies.GetServiceContext(); var query = from a in serviceContext.CreateQuery("annotation") join v in serviceContext.CreateQuery("adx_packageversion") on a["objectid"] equals v["adx_packageversionid"] where a.GetAttributeValue <string>("objecttypecode") == "adx_packageversion" where a.GetAttributeValue <bool?>("isdocument") == true where v.GetAttributeValue <Guid>("adx_packageversionid") == packageVersionId where v.GetAttributeValue <OptionSetValue>("statecode") != null && v.GetAttributeValue <OptionSetValue>("statecode").Value == 0 orderby a["createdon"] descending select a; var note = query.FirstOrDefault(); return(note == null?HttpNotFound() : dataAdapter.DownloadAction(Response, note)); }
private string GetDependentFilterAttributeValue(Guid entityId, string entityName, string filterAttributeName) { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext); var serviceContext = dataAdapterDependencies.GetServiceContext(); var entityRetrieveResponse = (RetrieveResponse)serviceContext.Execute(new RetrieveRequest() { ColumnSet = new ColumnSet(new string[] { filterAttributeName }), Target = new EntityReference(entityName, entityId) }); if (null != entityRetrieveResponse && null != entityRetrieveResponse.Entity) { var filterEntityReference = entityRetrieveResponse.Entity.GetAttributeValue <EntityReference>(filterAttributeName); if (null != filterEntityReference) { return(filterEntityReference.Id.ToString()); } } return(null); }
public ActionResult IndexByPartialUrl(string repositoryPartialUrl, string category, string filter, string search) { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext); var serviceContext = dataAdapterDependencies.GetServiceContext(); var repository = serviceContext.CreateQuery("adx_packagerepository") .FirstOrDefault(e => e.GetAttributeValue <string>("adx_partialurl") == repositoryPartialUrl && e.GetAttributeValue <EntityReference>("adx_entitylistid") != null && e.GetAttributeValue <int?>("statecode") == 0); if (repository == null) { return(HttpNotFound()); } var entityList = serviceContext.CreateQuery("adx_entitylist") .FirstOrDefault(e => e.GetAttributeValue <Guid>("adx_entitylistid") == repository.GetAttributeValue <EntityReference>("adx_entitylistid").Id && e.GetAttributeValue <int?>("statecode") == 0); if (entityList == null) { return(HttpNotFound()); } var viewId = (entityList.GetAttributeValue <string>("adx_view") ?? string.Empty) .Split(',') .Select(e => { Guid parsed; return(Guid.TryParse(e.Trim(), out parsed) ? new Guid?(parsed) : null); }) .FirstOrDefault(e => e.HasValue); if (viewId == null) { return(HttpNotFound()); } return(Index(repository.ToEntityReference(), entityList.Id, viewId.Value, category, filter, search)); }
public ActionResult AddNote(string regardingEntityLogicalName, string regardingEntityId, string text, bool isPrivate = false, HttpPostedFileBase file = null, string attachmentSettings = null) { Guid regardingId; Guid.TryParse(regardingEntityId, out regardingId); var regarding = new EntityReference(regardingEntityLogicalName, regardingId); string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var settings = JsonConvert.DeserializeObject <AnnotationSettings>(attachmentSettings) ?? new AnnotationSettings(serviceContext, true); var annotation = new Annotation { NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, text), Subject = AnnotationHelper.BuildNoteSubject(serviceContext, dataAdapterDependencies.GetPortalUser(), isPrivate), Regarding = regarding }; if (file != null && file.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(file, settings.StorageLocation); } var result = dataAdapter.CreateAnnotation(annotation, settings); if (!result.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Entity Permissions have not been defined. Your request could not be completed.")); } if (!result.CanCreate) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to create notes.")); } if (!result.CanAppendTo) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to append to record.")); } if (!result.CanAppend) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to append notes.")); } return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
public ActionResult Delete(EntityReference entityReference) { string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var entityPermissionProvider = new CrmEntityPermissionProvider(); if (!entityPermissionProvider.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Entity Permissions have not been defined. Your request could not be completed.")); } var entityMetadata = serviceContext.GetEntityMetadata(entityReference.LogicalName, EntityFilters.All); var primaryKeyName = entityMetadata.PrimaryIdAttribute; var entity = serviceContext.CreateQuery(entityReference.LogicalName) .First(e => e.GetAttributeValue <Guid>(primaryKeyName) == entityReference.Id); var test = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Delete, entity); if (test) { try { serviceContext.DeleteObject(entity); serviceContext.SaveChanges(); SalesHub hub = new SalesHub(); string url = Request.Url.OriginalString; } catch (Exception ex) { if (ex.InnerException.Message.Contains("The object you tried to delete is associated with another object and cannot be deleted.")) { throw new InvalidOperationException("Record cannot be deleted. It is already used in transactions."); } else { throw new InvalidOperationException(ex.InnerException.Message.ToString()); } } //string userId = Portal.User.Id.ToString(); //string fullName = Portal.User.Attributes["fullname"].ToString(); //hub.UserHasSaved(url, userId, fullName); } else { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to delete this record.")); } return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
public ActionResult DeleteNote(string id) { Guid annotationId; Guid.TryParse(id, out annotationId); string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var annotation = dataAdapter.GetAnnotation(annotationId); var result = dataAdapter.DeleteAnnotation(annotation, new AnnotationSettings(dataAdapterDependencies.GetServiceContext(), true)); if (!result.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Entity Permissions have not been defined. Your request could not be completed.")); } if (!result.CanDelete) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to delete this record.")); } return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
public ActionResult UpdateNote(string id, string text, string subject, bool isPrivate = false, HttpPostedFileBase file = null, string attachmentSettings = null) { Guid annotationId; Guid.TryParse(id, out annotationId); string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var settings = JsonConvert.DeserializeObject <AnnotationSettings>(attachmentSettings) ?? new AnnotationSettings(dataAdapterDependencies.GetServiceContext(), true); var annotation = dataAdapter.GetAnnotation(annotationId); annotation.AnnotationId = annotationId; annotation.NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, text); if (!isPrivate && !string.IsNullOrWhiteSpace(subject) && subject.Contains(AnnotationHelper.PrivateAnnotationPrefix)) { annotation.Subject = subject.Replace(AnnotationHelper.PrivateAnnotationPrefix, string.Empty); } if (isPrivate && !string.IsNullOrWhiteSpace(subject) && !subject.Contains(AnnotationHelper.PrivateAnnotationPrefix)) { annotation.Subject = subject + AnnotationHelper.PrivateAnnotationPrefix; } if (file != null && file.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(file, settings.StorageLocation); } try { var result = dataAdapter.UpdateAnnotation(annotation, settings); if (!result.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Entity Permissions have not been defined. Your request could not be completed.")); } if (!result.CanWrite) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to update notes.")); } return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); } catch (AnnotationException ex) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ex.Message)); } }
public ActionResult UpdateNote(string id, string text, string subject, bool isPrivate = false, HttpPostedFileBase file = null, string attachmentSettings = null) { if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(StringHelper.StripHtml(text))) { return(new HttpStatusCodeResult(HttpStatusCode.ExpectationFailed, ResourceManager.GetString("Required_Field_Error").FormatWith(ResourceManager.GetString("Note_DefaultText")))); } Guid annotationId; Guid.TryParse(id, out annotationId); string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var settings = GetAnnotationSettings(dataAdapterDependencies.GetServiceContext(), attachmentSettings); var annotation = dataAdapter.GetAnnotation(annotationId); annotation.AnnotationId = annotationId; annotation.NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, text); if (!isPrivate && !string.IsNullOrWhiteSpace(subject) && subject.Contains(AnnotationHelper.PrivateAnnotationPrefix)) { annotation.Subject = subject.Replace(AnnotationHelper.PrivateAnnotationPrefix, string.Empty); } if (isPrivate && !string.IsNullOrWhiteSpace(subject) && !subject.Contains(AnnotationHelper.PrivateAnnotationPrefix)) { annotation.Subject = subject + AnnotationHelper.PrivateAnnotationPrefix; } if (file != null && file.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(file, settings.StorageLocation); } try { var result = dataAdapter.UpdateAnnotation(annotation, settings); if (!result.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Entity_Permissions_Have_Not_Been_Defined_Message"))); } if (!result.PermissionGranted) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, string.Format(ResourceManager.GetString("No_Entity_Permissions"), "update notes"))); } return(new HttpStatusCodeResult(HttpStatusCode.OK)); } catch (AnnotationException ex) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ex.Message)); } }
public ActionResult AddNote(string regardingEntityLogicalName, string regardingEntityId, string text, bool isPrivate = false, HttpPostedFileBase file = null, string attachmentSettings = null) { if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(StringHelper.StripHtml(text))) { return(new HttpStatusCodeResult(HttpStatusCode.ExpectationFailed, ResourceManager.GetString("Required_Field_Error").FormatWith(ResourceManager.GetString("Note_DefaultText")))); } Guid regardingId; Guid.TryParse(regardingEntityId, out regardingId); var regarding = new EntityReference(regardingEntityLogicalName, regardingId); string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var user = Request.GetOwinContext().GetUser(); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var settings = GetAnnotationSettings(serviceContext, attachmentSettings); var annotation = new Annotation { NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, text), Subject = AnnotationHelper.BuildNoteSubject(serviceContext, user.ContactId, isPrivate), Regarding = regarding }; if (file != null && file.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(file, settings.StorageLocation); } var result = (AnnotationCreateResult)dataAdapter.CreateAnnotation(annotation, settings); if (!result.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Entity_Permissions_Have_Not_Been_Defined_Message"))); } if (!result.CanCreate) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, string.Format(ResourceManager.GetString("No_Entity_Permissions"), "create notes"))); } if (!result.CanAppendTo) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, string.Format(ResourceManager.GetString("No_Entity_Permissions"), "append to record"))); } if (!result.CanAppend) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, string.Format(ResourceManager.GetString("No_Entity_Permissions"), "append notes"))); } return(new HttpStatusCodeResult(HttpStatusCode.Created)); }
public ActionResult AddPortalComment(string regardingEntityLogicalName, string regardingEntityId, string text, HttpPostedFileBase file = null, string attachmentSettings = null) { if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(StringHelper.StripHtml(text))) { return(new HttpStatusCodeResult(HttpStatusCode.ExpectationFailed, ResourceManager.GetString("Required_Field_Error").FormatWith(ResourceManager.GetString("Comment_DefaultText")))); } Guid regardingId; Guid.TryParse(regardingEntityId, out regardingId); var regarding = new EntityReference(regardingEntityLogicalName, regardingId); var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext); var serviceContext = dataAdapterDependencies.GetServiceContext(); var dataAdapter = new ActivityDataAdapter(dataAdapterDependencies); var settings = EntityNotesController.GetAnnotationSettings(serviceContext, attachmentSettings); var crmUser = dataAdapter.GetCRMUserActivityParty(regarding, "ownerid"); var portalUser = new Entity("activityparty"); portalUser["partyid"] = dataAdapterDependencies.GetPortalUser(); var portalComment = new PortalComment { Description = text, From = portalUser, To = crmUser, Regarding = regarding, AttachmentSettings = settings, StateCode = StateCode.Completed, StatusCode = StatusCode.Received, DirectionCode = PortalCommentDirectionCode.Incoming }; if (file != null && file.ContentLength > 0) { // Soon we will change the UI/controller to accept multiple attachments during the create dialog, so the data adapter takes in a list of attachments portalComment.FileAttachments = new IAnnotationFile[] { AnnotationDataAdapter.CreateFileAttachment(file, settings.StorageLocation) }; } var result = dataAdapter.CreatePortalComment(portalComment); if (!result.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Entity_Permissions_Have_Not_Been_Defined_Message"))); } if (!result.CanCreate) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("No_Permissions_To_Create_Notes"))); } if (!result.CanAppendTo) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("No_Permissions_To_Append_Record"))); } if (!result.CanAppend) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("No_Permissions_To_Append_Notes"))); } if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)) { PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Comments, this.HttpContext, "create_comment_" + regardingEntityLogicalName, 1, regarding, "create"); } return(new HttpStatusCodeResult(HttpStatusCode.Created)); }
public ActionResult DeleteNote(string id) { Guid annotationId; Guid.TryParse(id, out annotationId); string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var annotation = dataAdapter.GetAnnotation(annotationId); var result = dataAdapter.DeleteAnnotation(annotation, new AnnotationSettings(dataAdapterDependencies.GetServiceContext(), true)); if (!result.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Entity_Permissions_Have_Not_Been_Defined_Message"))); } if (!result.PermissionGranted) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, string.Format(ResourceManager.GetString("No_Entity_Permissions"), "delete this record"))); } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
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); }
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, 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); }