public void ProcessRequest(HttpContext context) { if (_annotation == null) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } 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: context.Request.RequestContext, portalName: portalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); dataAdapter.Download(new HttpContextWrapper(context), _annotation, _webfile); }
public ActionResult GetNotes(EntityReference regarding, List <Order> orders, int page, int pageSize = DefaultPageSize) { 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 entityMetadata = portalContext.ServiceContext.GetEntityMetadata(regarding.LogicalName, EntityFilters.All); var result = dataAdapter.GetAnnotations(regarding, orders, page, pageSize, entityMetadata: entityMetadata); var totalRecordCount = result.TotalCount; var entityPermissionProvider = new CrmEntityPermissionProvider(); var crmLcid = HttpContext.GetCrmLcid(); var records = result.Select(r => new NoteRecord(r, dataAdapterDependencies, entityPermissionProvider, entityMetadata, true, crmLcid)); var data = new PaginatedGridData(records, totalRecordCount, page, pageSize); return(new JsonResult { Data = data, MaxJsonLength = int.MaxValue }); }
public virtual void AttachFile(OrganizationServiceContext context, Entity entity, HttpPostedFile postedFile) { if (context == null) { throw new ArgumentNullException("context"); } if (entity == null) { throw new ArgumentNullException("entity"); } if (postedFile == null) { throw new ArgumentNullException("postedFile"); } var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName); securityProvider.Assert(context, entity, CrmEntityRight.Change); var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: HttpContext.Current.Request.RequestContext, portalName: PortalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var result = dataAdapter.CreateAnnotation(entity.ToEntityReference(), string.Empty, string.Empty, new HttpPostedFileWrapper(postedFile)); if (result.Annotation.Entity.Id != null) { throw new InvalidOperationException("The file couldn't be attached to entity {0}.".FormatWith(entity)); } }
protected void AddNote_Click(object sender, EventArgs e) { var regardingContact = Permit.GetAttributeValue <EntityReference>(RegardingContactFieldName); if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id) { throw new InvalidOperationException("Unable to retrieve the order."); } if (!string.IsNullOrEmpty(NewNoteText.Text) || (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)) { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies( requestContext: Request.RequestContext, portalName: PortalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var annotation = new Annotation { NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, NewNoteText.Text), Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies), Regarding = Permit.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 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> /// Report a review as abusive. /// </summary> /// <param name="remarks"></param> public virtual void ReportAbuse(string remarks) { var httpContext = Dependencies.GetRequestContext().HttpContext; var user = Dependencies.GetPortalUser(); var username = httpContext.Request.IsAuthenticated && user != null ? user.Name : httpContext.Request.AnonymousID; var title = string.Format("Abuse Reported on {0} by {1}", DateTime.UtcNow.ToString(CultureInfo.InvariantCulture), username); IAnnotationDataAdapter da = new AnnotationDataAdapter(Dependencies); da.CreateAnnotation(Review, title, remarks); }
protected virtual void LogPaymentRequest(HttpContext context, PortalConfigurationDataAdapterDependencies dataAdapterDependencies, Tuple <Guid, string> quoteAndReturnUrl, string subject, string log) { var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var note = new Annotation { Subject = subject, Regarding = new EntityReference("quote", quoteAndReturnUrl.Item1), FileAttachment = AnnotationDataAdapter.CreateFileAttachment("log.txt", "text/plain", Encoding.UTF8.GetBytes(log)) }; dataAdapter.CreateAnnotation(note); }
public IForumPost SelectPost(Guid forumPostId) { var serviceContext = Dependencies.GetServiceContext(); var postFetch = new Fetch { Entity = new FetchEntity("adx_communityforumpost") { Filters = new[] { new Filter { Conditions = new[] { new Condition("adx_communityforumpostid", ConditionOperator.Equal, forumPostId), new Condition("adx_forumthreadid", ConditionOperator.Equal, this.ForumThread.Id) } } } } }; var entity = serviceContext.RetrieveSingle(postFetch); if (entity == null) { return(null); } var website = Dependencies.GetWebsite(); var securityProvider = Dependencies.GetSecurityProvider(); var urlProvider = Dependencies.GetUrlProvider(); var viewEntity = new PortalViewEntity(serviceContext, entity, securityProvider, urlProvider); var cloudStorageAccount = AnnotationDataAdapter.GetStorageAccount(serviceContext); var cloudStorageContainerName = AnnotationDataAdapter.GetStorageContainerName(serviceContext); CloudBlobContainer cloudStorageContainer = null; if (cloudStorageAccount != null) { cloudStorageContainer = AnnotationDataAdapter.GetBlobContainer(cloudStorageAccount, cloudStorageContainerName); } var postInfo = serviceContext.FetchForumPostInfo(entity.Id, website.Id, cloudStorageContainer); var user = Dependencies.GetPortalUser(); return(new ForumPost(entity, viewEntity, postInfo, new Lazy <ApplicationPath>(() => Dependencies.GetEditPath(entity.ToEntityReference()), LazyThreadSafetyMode.None), new Lazy <ApplicationPath>(() => Dependencies.GetDeletePath(entity.ToEntityReference()), LazyThreadSafetyMode.None), canEdit: new Lazy <bool>(() => user != null && user.Equals(postInfo.Author.EntityReference), LazyThreadSafetyMode.None))); }
public virtual IEnumerable <IRelatedNote> SelectRelatedNotes(IKnowledgeArticle article) { if (!IsAnnotationSearchEnabled) { return(null); } var annotationDataAdapter = new AnnotationDataAdapter(this.Dependencies); var webPrefix = GetNotesFilterPrefix; var relatedNotes = annotationDataAdapter.GetDocuments(article.EntityReference, webPrefix: webPrefix); return(relatedNotes.Select(a => new RelatedNote(a.NoteText == null ? string.Empty : a.NoteText.ToString().Substring(webPrefix.Length), a.FileAttachment.FileName, a.FileAttachment.Url))); }
public virtual IEnumerable <IAnnotation> SelectNotes() { var serviceContext = Dependencies.GetServiceContext(); IAnnotationDataAdapter annotationDataAdapter = new AnnotationDataAdapter(Dependencies); return(serviceContext.CreateQuery("annotation") .Where(e => e.GetAttributeValue <EntityReference>("objectid") == Incident && e.GetAttributeValue <string>("objecttypecode") == Incident.LogicalName && e.GetAttributeValue <string>("notetext").Contains(AnnotationHelper.WebAnnotationPrefix)) .ToArray() .Select(entity => annotationDataAdapter.GetAnnotation(entity)) .OrderBy(e => e.CreatedOn) .ToArray()); }
public void UpdatePost(IForumPostSubmission forumPost) { if (forumPost == null) { throw new ArgumentNullException("forumPost"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start"); var entityReference = ((IForumPostInfo)forumPost).EntityReference; var serviceContext = Dependencies.GetServiceContextForWrite(); var update = new Entity("adx_communityforumpost") { Id = entityReference.Id }; if (forumPost.Name != null) { update["adx_name"] = Truncate(forumPost.Name, 100); } if (forumPost.Content != null) { update["adx_content"] = forumPost.Content; } if (update.Attributes.Any()) { serviceContext.Attach(update); serviceContext.UpdateObject(update); serviceContext.SaveChanges(); } foreach (var attachment in forumPost.Attachments) { IAnnotationDataAdapter da = new AnnotationDataAdapter(Dependencies); da.CreateAnnotation(entityReference, string.Empty, string.Empty, attachment.Name, attachment.ContentType, attachment.Content); } if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)) { PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Forum, HttpContext.Current, "edit_forum_post", 1, entityReference, "edit"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End"); }
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 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 IEnumerable <IAttachment> GetAnnotationsAsAttachmentCollection(EntityReference regarding, bool respectPermissions = true) { // Retrieve attachments var annotationDataAdapter = new AnnotationDataAdapter(_dependencies); var annotationCollection = annotationDataAdapter.GetAnnotations(regarding, respectPermissions: respectPermissions, privacy: AnnotationPrivacy.Any); // Filter and project into Attachment object return(annotationCollection.Where(annotation => EntityContainsRequiredAnnotationFields(annotation.Entity.Attributes)).Select(annotation => { var entity = annotation.Entity; var fileName = GetFieldValue(entity, "filename"); var fileType = GetFieldValue(entity, "mimetype"); ulong fileSize; if (!ulong.TryParse(GetFieldValue(entity, "filesize"), out fileSize)) { fileSize = 0; } FileSize attachmentSize = new FileSize(fileSize); // Create CrmAnnotationFile for URL generation var crmAnnotationFile = new CrmAnnotationFile(fileName, fileType, new byte[0]); crmAnnotationFile.Annotation = new Entity("annotation") { Id = Guid.Parse(GetFieldValue(entity, "annotationid")) }; var activityAttachment = new Attachment { AttachmentContentType = fileType, AttachmentFileName = fileName, AttachmentIsImage = (new List <string> { "image/jpeg", "image/gif", "image/png" }).Contains(fileType), AttachmentSize = attachmentSize, AttachmentSizeDisplay = attachmentSize.ToString(), AttachmentUrl = crmAnnotationFile.Annotation.GetFileAttachmentUrl(_dependencies.GetWebsite()) }; return activityAttachment; })); }
private void ValidateFileAccept(FileUpload fileUpload, ServerValidateEventArgs args) { args.IsValid = true; if (!fileUpload.HasFiles) { return; } var regex = AnnotationDataAdapter.GetAcceptRegex(_attachFileAccept); foreach (var uploadedFile in fileUpload.PostedFiles) { var path = System.IO.Path.GetExtension(uploadedFile.FileName); args.IsValid = regex.IsMatch(uploadedFile.ContentType) || regex.IsMatch(path); if (!args.IsValid) { break; } } }
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(); }
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 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)); }
public virtual void AddNote(string text, string fileName = null, string contentType = null, byte[] fileContent = null, EntityReference ownerId = null) { try { var da = new AnnotationDataAdapter(Dependencies); var annotation = new Annotation { Subject = AnnotationHelper.BuildNoteSubject(Dependencies), NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, text), Regarding = Incident, Owner = ownerId }; if (fileContent != null && fileContent.Length > 0 && !string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(contentType)) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(EnsureValidFileName(fileName), contentType, fileContent); } da.CreateAnnotation(annotation); } catch (Exception e) { WebEventSource.Log.GenericErrorException(new Exception("Create annotation error", e)); throw; } }
public IEnumerable <IForumPost> SelectPosts(bool descending, int startRowIndex, int maximumRows = -1) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("startRowIndex={0}, maximumRows={1}: Start", startRowIndex, maximumRows)); if (startRowIndex < 0) { throw new ArgumentException("Value must be a positive integer.", "startRowIndex"); } if (maximumRows == 0) { return(new IForumPost[] { }); } var serviceContext = Dependencies.GetServiceContext(); var securityProvider = Dependencies.GetSecurityProvider(); var query = serviceContext.CreateQuery("adx_communityforumpost") .Where(e => e.GetAttributeValue <EntityReference>("adx_forumthreadid") == ForumThread); query = descending ? query.OrderByDescending(e => e.GetAttributeValue <DateTime?>("adx_date")) : query.OrderBy(e => e.GetAttributeValue <DateTime?>("adx_date")); if (startRowIndex > 0) { query = query.Skip(startRowIndex); } if (maximumRows > 0) { query = query.Take(maximumRows); } var website = Dependencies.GetWebsite(); var entities = query.ToArray(); var firstPostEntity = entities.FirstOrDefault(); var cloudStorageAccount = AnnotationDataAdapter.GetStorageAccount(serviceContext); var cloudStorageContainerName = AnnotationDataAdapter.GetStorageContainerName(serviceContext); CloudBlobContainer cloudStorageContainer = null; if (cloudStorageAccount != null) { cloudStorageContainer = AnnotationDataAdapter.GetBlobContainer(cloudStorageAccount, cloudStorageContainerName); } var postInfos = serviceContext.FetchForumPostInfos(entities.Select(e => e.Id), website.Id, cloudStorageContainer: cloudStorageContainer); var urlProvider = Dependencies.GetUrlProvider(); var thread = Select(); var user = Dependencies.GetPortalUser(); var posts = entities.Select(entity => { IForumPostInfo postInfo; postInfo = postInfos.TryGetValue(entity.Id, out postInfo) ? postInfo : new UnknownForumPostInfo(); var viewEntity = new PortalViewEntity(serviceContext, entity, securityProvider, urlProvider); return(new ForumPost(entity, viewEntity, postInfo, new Lazy <ApplicationPath>(() => Dependencies.GetEditPath(entity.ToEntityReference()), LazyThreadSafetyMode.None), new Lazy <ApplicationPath>(() => Dependencies.GetDeletePath(entity.ToEntityReference()), LazyThreadSafetyMode.None), new Lazy <bool>(() => thread.Editable, LazyThreadSafetyMode.None), new Lazy <bool>(() => thread.ThreadType != null && thread.ThreadType.RequiresAnswer && (firstPostEntity == null || !firstPostEntity.ToEntityReference().Equals(entity.ToEntityReference())) && ((user != null && user.Equals(thread.Author.EntityReference)) || thread.Editable) && !thread.Locked, LazyThreadSafetyMode.None), canEdit: new Lazy <bool>(() => user != null && user.Equals(postInfo.Author.EntityReference) && !thread.Locked, LazyThreadSafetyMode.None))); }).ToArray(); ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End"); return(posts); }
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(); } } } }
protected void Page_Load(object sender, EventArgs e) { RedirectToLoginIfAnonymous(); var quoteToEditEntity = QuoteToEdit != null ? QuoteToEdit.Entity : null; if (quoteToEditEntity == null || (quoteToEditEntity.GetAttributeValue <EntityReference>("customerid") != null && !quoteToEditEntity.GetAttributeValue <EntityReference>("customerid").Equals(Contact.ToEntityReference()))) { PageBreadcrumbs.Visible = true; GenericError.Visible = true; QuoteHeader.Visible = false; QuoteDetails.Visible = false; QuoteInfo.Visible = false; QuoteBreadcrumbs.Visible = false; QuoteHeader.Visible = false; return; } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var annotations = dataAdapter.GetAnnotations(QuoteToEdit.Entity.ToEntityReference(), new List <Order> { new Order("createdon") }); NotesList.DataSource = annotations; NotesList.DataBind(); var quoteState = quoteToEditEntity.GetAttributeValue <OptionSetValue>("statecode"); ConvertToOrder.Visible = quoteState != null && (quoteState.Value == (int)Enums.QuoteState.Active || quoteState.Value == (int)Enums.QuoteState.Won); 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>", "quote", "quoteid", QuoteToEdit.Id); formViewDataSource.FetchXml = fetchXml; QuoteForm.Controls.Add(formViewDataSource); FormView.DataSourceID = "WebFormDataSource"; var baseCartReference = quoteToEditEntity.GetAttributeValue <EntityReference>("adx_shoppingcartid"); var baseCart = (baseCartReference != null) ? ServiceContext.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue <Guid>("adx_shoppingcartid") == baseCartReference.Id) : null; 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"); }
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 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 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)); } }
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); } }
public IForumPost CreatePost(IForumPostSubmission forumPost, bool incrementForumThreadCount = false) { if (forumPost == null) { throw new ArgumentNullException("forumPost"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start"); var serviceContext = Dependencies.GetServiceContextForWrite(); var thread = Select(); var locked = thread.Locked; if (locked) { throw new InvalidOperationException("You can't create a new post because the forum is locked."); } var entity = new Entity("adx_communityforumpost"); entity["adx_forumthreadid"] = ForumThread; entity["adx_name"] = Truncate(forumPost.Name, 100); entity["adx_isanswer"] = forumPost.IsAnswer; entity["adx_authorid"] = forumPost.Author.EntityReference; entity["adx_date"] = forumPost.PostedOn; entity["adx_content"] = forumPost.Content; entity["adx_helpfulvotecount"] = forumPost.HelpfulVoteCount; serviceContext.AddObject(entity); serviceContext.SaveChanges(); var threadEntity = SelectEntity(serviceContext); var threadUpdate = new Entity(threadEntity.LogicalName) { Id = threadEntity.Id }; threadUpdate["adx_lastpostdate"] = forumPost.PostedOn; threadUpdate["adx_lastpostid"] = entity.ToEntityReference(); threadUpdate["adx_postcount"] = threadEntity.GetAttributeValue <int?>("adx_postcount").GetValueOrDefault() + 1; if (threadEntity.GetAttributeValue <EntityReference>("adx_firstpostid") == null) { threadUpdate["adx_firstpostid"] = entity.ToEntityReference(); } serviceContext.Detach(threadEntity); serviceContext.Attach(threadUpdate); serviceContext.UpdateObject(threadUpdate); serviceContext.SaveChanges(); var entityReference = entity.ToEntityReference(); var forumDataAdapter = new ForumDataAdapter(threadEntity.GetAttributeValue <EntityReference>("adx_forumid"), Dependencies); forumDataAdapter.UpdateLatestPost(entityReference, incrementForumThreadCount); foreach (var attachment in forumPost.Attachments) { IAnnotationDataAdapter da = new AnnotationDataAdapter(Dependencies); da.CreateAnnotation(entityReference, string.Empty, string.Empty, attachment.Name, attachment.ContentType, attachment.Content); } var post = SelectPost(entityReference.Id); ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End"); if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)) { PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Forum, HttpContext.Current, "create_forum_post", 1, post.Entity.ToEntityReference(), "create"); } return(post); }
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"); }
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)); } }
/// <summary> /// Creates a Portal Comment entity, as well Annotation entities for any attachments /// </summary> /// <param name="portalComment"></param> /// <returns></returns> public PortalCommentCreateResult CreatePortalComment(PortalComment portalComment) { var serviceContext = _dependencies.GetServiceContext(); var serviceContextForWrite = _dependencies.GetServiceContextForWrite(); PortalCommentCreateResult result = null; var entityPermissionProvider = new CrmEntityPermissionProvider(); result = new PortalCommentCreateResult(entityPermissionProvider, serviceContext, portalComment.Regarding); if (result.PermissionsExist && result.PermissionGranted) { var acceptMimeTypes = AnnotationDataAdapter.GetAcceptRegex(portalComment.AttachmentSettings.AcceptMimeTypes); var acceptExtensionTypes = AnnotationDataAdapter.GetAcceptRegex(portalComment.AttachmentSettings.AcceptExtensionTypes); if (portalComment.FileAttachments != null) { portalComment.FileAttachments.ForEach(attachment => { if (!(acceptExtensionTypes.IsMatch(Path.GetExtension(attachment.FileName).ToLower()) || acceptMimeTypes.IsMatch(attachment.MimeType))) { throw new AnnotationException(portalComment.AttachmentSettings.RestrictMimeTypesErrorMessage); } }); } var owner = portalComment.To?.GetAttributeValue <EntityReference>("partyid"); var entity = new Entity("adx_portalcomment"); entity.SetAttributeValue("description", portalComment.Description); entity.SetAttributeValue("regardingobjectid", portalComment.Regarding); entity.SetAttributeValue("regardingobjecttypecode", portalComment.Regarding.LogicalName); entity.SetAttributeValue("from", new Entity[] { portalComment.From }); entity.SetAttributeValue("adx_portalcommentdirectioncode", new OptionSetValue((int)portalComment.DirectionCode)); if (owner != null) { entity.SetAttributeValue("ownerid", owner); if (!string.Equals(owner.LogicalName, "team", StringComparison.OrdinalIgnoreCase)) { entity.SetAttributeValue("to", new Entity[] { portalComment.To }); } } // Create adx_portalcomment but skip cache invalidation. var id = (serviceContext as IOrganizationService).ExecuteCreate(entity, RequestFlag.ByPassCacheInvalidation); portalComment.ActivityId = entity.Id = id; portalComment.Entity = entity; // Can only change state code value after entity creation entity.SetAttributeValue("statecode", new OptionSetValue((int)portalComment.StateCode)); entity.SetAttributeValue("statuscode", new OptionSetValue((int)portalComment.StatusCode)); // Explicitly include the activityid, this way the Cache will know to add dependency on "activitypointer" for this "adx_portalcomment" entity. entity.SetAttributeValue("activityid", id); (serviceContext as IOrganizationService).ExecuteUpdate(entity); if (portalComment.FileAttachments != null) { // permission for Portal Comment implies permission for attachment to Portal Comment portalComment.AttachmentSettings.RespectPermissions = false; foreach (IAnnotationFile attachment in portalComment.FileAttachments) { IAnnotation annotation = new Annotation { Subject = String.Empty, NoteText = String.Empty, Regarding = portalComment.Entity.ToEntityReference(), FileAttachment = attachment }; IAnnotationDataAdapter da = new AnnotationDataAdapter(_dependencies); da.CreateAnnotation(annotation, portalComment.AttachmentSettings); } } } return(result); }