private void FormViewInserted(object sender, CrmEntityFormViewInsertedEventArgs args)
        {
            if (FileUpload == null || !FileUpload.HasFiles || !args.EntityId.HasValue)
            {
                return;
            }

            var regarding = new EntityReference(Metadata.TargetEntityName, args.EntityId.Value);

            var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies();
            var dataAdapter             = new SharePointDataAdapter(dataAdapterDependencies);

            dataAdapter.AddFiles(regarding, FileUpload.PostedFiles.Select(file => new HttpPostedFileWrapper(file) as HttpPostedFileBase).ToList());
        }
        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 GetAttachments(EntityReference regarding)
        {
            var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext);
            var dataAdapter             = new ActivityDataAdapter(dataAdapterDependencies);
            var attachments             = dataAdapter.GetAttachments(regarding).ToArray();

            if (attachments.Any())
            {
                return(new JsonResult {
                    Data = attachments, MaxJsonLength = int.MaxValue
                });
            }
            return(new EmptyResult());
        }
コード例 #4
0
        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));
        }
コード例 #5
0
        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));
        }
コード例 #6
0
        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");
        }
コード例 #8
0
        public ActionResult GetActivities(EntityReference regarding, List <Order> orders, int page, int pageSize = DefaultPageSize)
        {
            var portalContext = PortalCrmConfigurationManager.CreatePortalContext();

            var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext);
            var dataAdapter             = new ActivityDataAdapter(dataAdapterDependencies);
            var entityMetadata          = portalContext.ServiceContext.GetEntityMetadata(regarding.LogicalName, EntityFilters.All);
            var result = dataAdapter.GetActivities(regarding, orders, page, pageSize, entityMetadata);
            var entityPermissionProvider = new CrmEntityPermissionProvider();
            var crmLcid = HttpContext.GetCrmLcid();
            var records = result.Select(r => new ActivityRecord(r, dataAdapterDependencies, entityPermissionProvider, entityMetadata, true, crmLcid)).ToArray();
            var data    = new PaginatedGridData(records, result.TotalCount, page, pageSize);

            return(new JsonResult {
                Data = data, MaxJsonLength = int.MaxValue
            });
        }
コード例 #9
0
        public ActionResult AddSharePointFiles(string regardingEntityLogicalName, string regardingEntityId, IList <HttpPostedFileBase> files, bool overwrite, string folderPath = 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 dataAdapter             = new SharePointDataAdapter(dataAdapterDependencies);
            var result = dataAdapter.AddFiles(regarding, files, overwrite, folderPath);

            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 SharePoint files."));
            }

            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 SharePoint files."));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.NoContent));
        }
コード例 #10
0
        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));
        }
コード例 #11
0
        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));
        }
コード例 #12
0
        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;
        }
コード例 #13
0
        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);
        }
コード例 #14
0
        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));
        }
コード例 #15
0
        public ActionResult AddSharePointFolder(EntityReference regarding, string name, string folderPath = null)
        {
            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 SharePointDataAdapter(dataAdapterDependencies);
            var result = dataAdapter.AddFolder(regarding, name, folderPath);

            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 SharePoint files")));
            }

            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 SharePoint files")));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.NoContent));
        }
コード例 #16
0
        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));
        }
コード例 #17
0
ファイル: Event.aspx.cs プロジェクト: weedkiller/dms
        protected void Speakers_OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var dataItem = e.Item as ListViewDataItem;

            if (dataItem == null || dataItem.DataItem == null)
            {
                return;
            }

            var speaker = dataItem.DataItem as Entity;

            if (speaker == null)
            {
                return;
            }

            var repeaterControl = (Repeater)e.Item.FindControl("SpeakerAnnotations");

            if (repeaterControl == null)
            {
                return;
            }

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

            var annotations = XrmContext.CreateQuery("annotation")
                              .Where(a => a.GetAttributeValue <EntityReference>("objectid") == speaker.ToEntityReference() &&
                                     a.GetAttributeValue <bool?>("isdocument").GetValueOrDefault(false))
                              .OrderBy(a => a.GetAttributeValue <DateTime>("createdon"))
                              .Select(entity => dataAdapter.GetAnnotation(entity));

            repeaterControl.DataSource = annotations;
            repeaterControl.DataBind();
        }
コード例 #18
0
        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));
        }
コード例 #19
0
        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));
        }
コード例 #20
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);
        }
コード例 #21
0
        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));
            }
        }
コード例 #22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var reference = Entity.GetAttributeValue <EntityReference>("adx_entityform");

            var entityFormRecord = XrmContext.CreateQuery("adx_entityform").FirstOrDefault(ef => ef.GetAttributeValue <Guid>("adx_entityformid") == reference.Id);

            if (entityFormRecord != null)
            {
                var recordEntityLogicalName = entityFormRecord.GetAttributeValue <string>("adx_entityname");

                Guid recordId;

                if (Guid.TryParse(Request["id"], out recordId))
                {
                    var metadataRequest = new RetrieveEntityRequest
                    {
                        LogicalName   = recordEntityLogicalName,
                        EntityFilters = EntityFilters.Attributes
                    };

                    var metadataResponse = (RetrieveEntityResponse)XrmContext.Execute(metadataRequest);

                    var primaryFieldLogicalName = metadataResponse.EntityMetadata.PrimaryIdAttribute;

                    var permitRecord = XrmContext.CreateQuery(recordEntityLogicalName).FirstOrDefault(r => r.GetAttributeValue <Guid>(primaryFieldLogicalName) == recordId);

                    var permitTypeReference = permitRecord.GetAttributeValue <EntityReference>("adx_permittype");

                    var permitType =
                        XrmContext.CreateQuery("adx_permittype").FirstOrDefault(
                            srt => srt.GetAttributeValue <Guid>("adx_permittypeid") == permitTypeReference.Id);

                    var entityName = permitType.GetAttributeValue <string>("adx_entityname");

                    RegardingContactFieldName = permitType.GetAttributeValue <string>("adx_regardingcontactfieldname");

                    var trueMetadataRequest = new RetrieveEntityRequest
                    {
                        LogicalName   = entityName,
                        EntityFilters = EntityFilters.Attributes
                    };

                    var trueMetadataResponse = (RetrieveEntityResponse)XrmContext.Execute(trueMetadataRequest);

                    var primaryFieldName = trueMetadataResponse.EntityMetadata.PrimaryIdAttribute;

                    var entityId = permitRecord.GetAttributeValue <string>("adx_entityid");

                    var trueRecordId = Guid.Parse(entityId);

                    var trueRecord = XrmContext.CreateQuery(entityName).FirstOrDefault(r => r.GetAttributeValue <Guid>(primaryFieldName) == trueRecordId);

                    Permit = trueRecord;

                    var permitDataSource = CreateDataSource("PermitDataSource", entityName, primaryFieldName, trueRecordId);

                    var permitFormView = new CrmEntityFormView()
                    {
                        FormName = "Details Form", Mode = FormViewMode.Edit, EntityName = entityName, CssClass = "crmEntityFormView", AutoGenerateSteps = false
                    };

                    var languageCodeSetting = OrganizationServiceContextExtensions.GetSiteSettingValueByName(ServiceContext, Portal.Website, "Language Code");
                    if (!string.IsNullOrWhiteSpace(languageCodeSetting))
                    {
                        int languageCode;
                        if (int.TryParse(languageCodeSetting, out languageCode))
                        {
                            permitFormView.LanguageCode         = languageCode;
                            permitFormView.ContextName          = languageCode.ToString(CultureInfo.InvariantCulture);
                            permitDataSource.CrmDataContextName = languageCode.ToString(CultureInfo.InvariantCulture);
                        }
                    }

                    CrmEntityFormViewPanel.Controls.Add(permitFormView);

                    permitFormView.DataSourceID = permitDataSource.ID;

                    var regardingContact = Permit.GetAttributeValue <EntityReference>(RegardingContactFieldName);

                    if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id)
                    {
                        PermitControls.Enabled = false;
                        PermitControls.Visible = false;
                        AddNoteInline.Visible  = false;
                        AddNoteInline.Enabled  = false;
                    }
                    else
                    {
                        var dataAdapterDependencies =
                            new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
                        var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
                        var annotations = dataAdapter.GetAnnotations(Permit.ToEntityReference(),
                                                                     new List <Order> {
                            new Order("createdon")
                        }, respectPermissions: false);

                        NotesList.DataSource = annotations;
                        NotesList.DataBind();
                    }
                }
            }
        }
コード例 #23
0
        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));
        }
コード例 #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();

            if (OrderToEdit == null || (OrderToEdit.GetAttributeValue <EntityReference>("customerid") != null && !OrderToEdit.GetAttributeValue <EntityReference>("customerid").Equals(Contact.ToEntityReference())))
            {
                PageBreadcrumbs.Visible  = true;
                GenericError.Visible     = true;
                OrderHeader.Visible      = false;
                OrderDetails.Visible     = false;
                OrderInfo.Visible        = false;
                OrderBreadcrumbs.Visible = false;
                OrderHeader.Visible      = false;

                return;
            }

            var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
            var dataAdapter             = new AnnotationDataAdapter(dataAdapterDependencies);
            var annotations             = dataAdapter.GetAnnotations(OrderToEdit.ToEntityReference(),
                                                                     new List <Order> {
                new Order("createdon")
            });

            NotesList.DataSource = annotations;
            NotesList.DataBind();

            var formViewDataSource = new CrmDataSource {
                ID = "WebFormDataSource", CrmDataContextName = FormView.ContextName
            };

            var fetchXml = string.Format("<fetch mapping='logical'><entity name='{0}'><all-attributes /><filter type='and'><condition attribute = '{1}' operator='eq' value='{{{2}}}'/></filter></entity></fetch>", "salesorder", "salesorderid", OrderToEdit.GetAttributeValue <Guid>("salesorderid"));

            formViewDataSource.FetchXml = fetchXml;

            OrderForm.Controls.Add(formViewDataSource);

            FormView.DataSourceID = "WebFormDataSource";

            var baseCartReference = OrderToEdit.GetAttributeValue <EntityReference>("adx_shoppingcartid");

            if (baseCartReference == null)
            {
                ShoppingCartSummary.Visible = false;

                Entity invoice;

                if (TryGetInvoice(XrmContext, OrderToEdit, out invoice))
                {
                    ShowInvoice(XrmContext, invoice);

                    return;
                }

                ShowOrder(XrmContext, OrderToEdit);

                Order.Visible   = true;
                Invoice.Visible = false;

                return;
            }

            // legacy code for displaying summary of ordered items.

            var baseCart = XrmContext.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue <Guid>("adx_shoppingcartid") == baseCartReference.Id);

            var cartRecord = baseCart == null ? null : new ShoppingCart(baseCart, XrmContext);

            if (cartRecord == null)
            {
                ShoppingCartSummary.Visible = false;

                return;
            }

            var cartItems = cartRecord.GetCartItems().Select(sci => sci.Entity);

            if (!cartItems.Any())
            {
                ShoppingCartSummary.Visible = false;

                return;
            }

            CartRepeater.DataSource = cartItems;
            CartRepeater.DataBind();

            Total.Text = cartRecord.GetCartTotal().ToString("C2");
        }
コード例 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ServiceRequestRollupRecord != null)
            {
                var serviceRequestTypeReference =
                    ServiceRequestRollupRecord.GetAttributeValue <EntityReference>("adx_servicerequesttype");

                var serviceRequestType =
                    XrmContext.CreateQuery("adx_servicerequesttype").FirstOrDefault(
                        srt => srt.GetAttributeValue <Guid>("adx_servicerequesttypeid") == serviceRequestTypeReference.Id);

                var entityName = serviceRequestType.GetAttributeValue <string>("adx_entityname");

                RegardingContactFieldName = serviceRequestType.GetAttributeValue <string>("adx_regardingcontactfieldname");

                var trueMetadataRequest = new RetrieveEntityRequest
                {
                    LogicalName   = entityName,
                    EntityFilters = EntityFilters.Attributes
                };

                var trueMetadataResponse = (RetrieveEntityResponse)XrmContext.Execute(trueMetadataRequest);

                var primaryFieldName = trueMetadataResponse.EntityMetadata.PrimaryIdAttribute;

                var entityId = ServiceRequestRollupRecord.GetAttributeValue <string>("adx_entityid");

                var trueRecordId = Guid.Parse(entityId);

                var trueRecord =
                    XrmContext.CreateQuery(entityName).FirstOrDefault(r => r.GetAttributeValue <Guid>(primaryFieldName) == trueRecordId);

                ServiceRequest = trueRecord;



                var regardingContact = ServiceRequest.GetAttributeValue <EntityReference>(RegardingContactFieldName);

                if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id)
                {
                    AddANote.Enabled      = false;
                    AddANote.Visible      = false;
                    AddNoteInline.Visible = false;
                    AddNoteInline.Enabled = false;

                    RenderCrmEntityFormView(entityName, primaryFieldName, trueRecordId, FormViewMode.ReadOnly);

                    var dataAdapterDependencies =
                        new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
                    var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
                    var annotations = dataAdapter.GetAnnotations(ServiceRequest.ToEntityReference(),
                                                                 new List <Order> {
                        new Order("createdon")
                    });

                    if (!annotations.Any())
                    {
                        NotesLabel.Visible = false;
                        NotesList.Visible  = false;
                    }

                    NotesList.DataSource = annotations;
                    NotesList.DataBind();
                }
                else
                {
                    RenderCrmEntityFormView(entityName, primaryFieldName, trueRecordId, FormViewMode.Edit);

                    var dataAdapterDependencies =
                        new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
                    var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
                    var annotations = dataAdapter.GetAnnotations(ServiceRequest.ToEntityReference(),
                                                                 new List <Order> {
                        new Order("createdon")
                    },
                                                                 privacy: AnnotationPrivacy.Web | AnnotationPrivacy.Private | AnnotationPrivacy.Public);

                    NotesList.DataSource = annotations;
                    NotesList.DataBind();
                }

                if (Request.IsAuthenticated && Contact != null)
                {
                    var dataAdapter = CreateAlertDataAdapter();

                    var hasAlert = dataAdapter.HasAlert(Contact.ToEntityReference());

                    AddAlert.Visible    = !hasAlert;
                    RemoveAlert.Visible = hasAlert;
                }
                else
                {
                    AddAlertLoginLink.Visible = true;
                }

                DisplaySlaDetails(serviceRequestType);
            }
        }
コード例 #26
0
        private static ViewDataAdapter SetViewDataAdapter(ViewConfiguration viewConfiguration, string sortExpression, string search,
                                                          string filter, string metaFilter, int page, bool applyRecordLevelFilters, bool applyRelatedRecordFilter,
                                                          string filterRelationshipName, string filterEntityName, string filterAttributeName, Guid?filterValue,
                                                          IDictionary <string, string> customParameters, PortalConfigurationDataAdapterDependencies dataAdapterDependencies, CrmWebsite website)
        {
            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, customParameters: customParameters)
                                : new ViewDataAdapter(viewConfiguration, dataAdapterDependencies, page, search, sortExpression, filter,
                                                      metaFilter,
                                                      applyRecordLevelFilters, customParameters: customParameters);

            var siteSettings       = new SettingDataAdapter(dataAdapterDependencies, website);
            var multiQueryEntities = (siteSettings.GetValue("Grid/DoQueryPerRecordLevelFilter/Entities") ?? string.Empty)
                                     .Split(',')
                                     .ToLookup(e => e, StringComparer.OrdinalIgnoreCase);

            viewDataAdapter.DoQueryPerRecordLevelFilter = multiQueryEntities.Contains(viewConfiguration.EntityName);

            return(viewDataAdapter);
        }
コード例 #27
0
        public ActionResult DownloadAsExcel(string viewName, IEnumerable <LayoutColumn> columns, string base64SecureConfiguration, string sortExpression, string search, string filter,
                                            string metaFilter, int page = 1, int pageSize = DefaultPageSize, int timezoneOffset = 0)
        {
            var viewConfiguration = ConvertSecureStringToViewConfiguration(base64SecureConfiguration);

            if (viewConfiguration == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Invalid_Request")));
            }

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

            // override the page parameters
            page     = 1;
            pageSize = new SettingDataAdapter(dataAdapterDependencies, HttpContext.GetWebsite())
                       .GetIntegerValue("Grid/Download/MaximumResults")
                       .GetValueOrDefault(Fetch.MaximumPageSize);
            viewConfiguration.PageSize = pageSize;

            var json = GetData(viewConfiguration, sortExpression, search, filter, metaFilter, page, pageSize, true, false, null, null, null, null, true) as JsonResult;

            if (json == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NoContent));
            }

            if (json.Data is EntityPermissionResult)
            {
                return(json);
            }

            var data = json.Data as PaginatedGridData;

            if (data == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NoContent));
            }

            var stream = new MemoryStream();

            var spreadsheet = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);

            var workbookPart = spreadsheet.AddWorkbookPart();

            workbookPart.Workbook = new Workbook();

            var worksheetPart = workbookPart.AddNewPart <WorksheetPart>();
            var sheet         = new Sheet {
                Id = spreadsheet.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = viewName.Truncate(30)
            };

            var sheets = new Sheets();

            sheets.Append(sheet);

            var sheetData = new SheetData();

            var rowIndex    = 1;
            var columnIndex = 1;

            var firstRow = new Row {
                RowIndex = (uint)rowIndex
            };

            var dataColumns = columns.Where(col => col.LogicalName != "col-action").ToArray();

            foreach (var column in dataColumns)
            {
                var cell = new Cell {
                    CellReference = CreateCellReference(columnIndex) + rowIndex, DataType = CellValues.InlineString
                };

                var inlineString = new InlineString {
                    Text = new Text {
                        Text = column.Name
                    }
                };

                cell.AppendChild(inlineString);

                firstRow.AppendChild(cell);

                columnIndex++;
            }

            sheetData.Append(firstRow);

            foreach (var record in data.Records)
            {
                var row = new Row {
                    RowIndex = (uint)++rowIndex
                };

                columnIndex = 0;

                foreach (var column in dataColumns)
                {
                    columnIndex++;

                    var attribute = record.Attributes.FirstOrDefault(a => a.Name == column.LogicalName);

                    if (attribute == null)
                    {
                        continue;
                    }

                    var isDateTime = attribute.AttributeMetadata.AttributeType == AttributeTypeCode.DateTime;

                    var cell = new Cell {
                        CellReference = CreateCellReference(columnIndex) + rowIndex, DataType = CellValues.InlineString
                    };

                    var inlineString = new InlineString {
                        Text = new Text {
                            Text = isDateTime ? this.GetFormattedDateTime(attribute, timezoneOffset) : attribute.DisplayValue as string
                        }
                    };

                    cell.AppendChild(inlineString);

                    row.AppendChild(cell);
                }

                sheetData.Append(row);
            }

            worksheetPart.Worksheet = new Worksheet(sheetData);

            spreadsheet.WorkbookPart.Workbook.AppendChild(sheets);

            workbookPart.Workbook.Save();

            spreadsheet.Close();

            var filename = new string(viewName.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray());

            var sessionKey = "{0:s}|{1}.xlsx".FormatWith(DateTime.UtcNow, filename);

            stream.Position = 0;             // Reset the stream to the beginning and save to session.

            Session[sessionKey] = stream;

            return(Json(new { success = true, sessionKey }, JsonRequestBehavior.AllowGet));
        }
コード例 #28
0
        public ActionResult DownloadAsCsv(string viewName, IEnumerable <LayoutColumn> columns, string base64SecureConfiguration, string sortExpression, string search, string filter,
                                          string metaFilter, int page = 1, int pageSize = DefaultPageSize)
        {
            var viewConfiguration = ConvertSecureStringToViewConfiguration(base64SecureConfiguration);

            using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.EntityGridController, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.DownloadAsCsv))
            {
                if (viewConfiguration == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Invalid_Request")));
                }

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

                // override the page parameters
                page     = 1;
                pageSize = new SettingDataAdapter(dataAdapterDependencies, HttpContext.GetWebsite())
                           .GetIntegerValue("Grid/Download/MaximumResults")
                           .GetValueOrDefault(Fetch.MaximumPageSize);
                viewConfiguration.PageSize = pageSize;

                var json = GetData(viewConfiguration, sortExpression, search, filter, metaFilter, page, pageSize, true, false, null, null, null, null, true) as JsonResult;

                if (json == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.NoContent));
                }

                if (json.Data is EntityPermissionResult)
                {
                    return(json);
                }

                var data = json.Data as PaginatedGridData;

                if (data == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.NoContent));
                }

                var csv = new StringBuilder();

                var dataColumns = columns.Where(col => col.LogicalName != "col-action").ToArray();

                foreach (var column in dataColumns)
                {
                    csv.Append(EncodeCommaSeperatedValue(column.Name));
                }

                csv.AppendLine();

                foreach (var record in data.Records)
                {
                    foreach (var column in dataColumns)
                    {
                        var attribute = record.Attributes.FirstOrDefault(a => a.Name == column.LogicalName);

                        if (attribute == null)
                        {
                            continue;
                        }

                        csv.Append(EncodeCommaSeperatedValue(attribute.DisplayValue as string));
                    }

                    csv.AppendLine();
                }

                var filename = new string(viewName.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray());

                var sessionKey = "{0:s}|{1}.csv".FormatWith(DateTime.UtcNow, filename);

                Session[sessionKey] = csv.ToString();

                return(Json(new { success = true, sessionKey }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #29
0
        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));
        }
コード例 #30
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, 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);
        }