protected void AddNote_Click(object sender, EventArgs e) { var regardingContact = ServiceRequest.GetAttributeValue <EntityReference>(RegardingContactFieldName); if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id) { throw new InvalidOperationException("Unable to retrieve order."); } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies( requestContext: Request.RequestContext, portalName: PortalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); if (NewNotePublic.Checked) { if (!string.IsNullOrEmpty(NewNoteText.Text) || (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)) { var annotation = new Annotation { NoteText = string.Format("{0}{1}", AnnotationHelper.PublicAnnotationPrefix, NewNoteText.Text), Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies), Regarding = ServiceRequest.ToEntityReference() }; if (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(NewNoteAttachment.PostedFile)); } dataAdapter.CreateAnnotation(annotation); } } else { if (!string.IsNullOrEmpty(NewNoteText.Text) || (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)) { var annotation = new Annotation { NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, NewNoteText.Text), Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies), Regarding = ServiceRequest.ToEntityReference() }; if (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(NewNoteAttachment.PostedFile)); } dataAdapter.CreateAnnotation(annotation); } } Response.Redirect(Request.Url.PathAndQuery); }
protected void AddNote_Click(object sender, EventArgs e) { if (OrderToEdit == null || (OrderToEdit.GetAttributeValue <EntityReference>("customerid") != null && !OrderToEdit.GetAttributeValue <EntityReference>("customerid").Equals(Contact.ToEntityReference()))) { throw new InvalidOperationException("Unable to retrieve 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 = OrderToEdit.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); }
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)); } }
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 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 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 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); }
/// <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); }
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 AddNote(string regardingEntityLogicalName, string regardingEntityId, string text, bool isPrivate = false, HttpPostedFileBase file = null, string attachmentSettings = null) { Guid regardingId; Guid.TryParse(regardingEntityId, out regardingId); var regarding = new EntityReference(regardingEntityLogicalName, regardingId); string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var settings = JsonConvert.DeserializeObject <AnnotationSettings>(attachmentSettings) ?? new AnnotationSettings(serviceContext, true); var annotation = new Annotation { NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, text), Subject = AnnotationHelper.BuildNoteSubject(serviceContext, dataAdapterDependencies.GetPortalUser(), isPrivate), Regarding = regarding }; if (file != null && file.ContentLength > 0) { annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(file, settings.StorageLocation); } var result = dataAdapter.CreateAnnotation(annotation, settings); if (!result.PermissionsExist) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Entity Permissions have not been defined. Your request could not be completed.")); } if (!result.CanCreate) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to create notes.")); } if (!result.CanAppendTo) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to append to record.")); } if (!result.CanAppend) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Permission Denied. You do not have the appropriate Entity Permissions to append notes.")); } return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }