public override void ProcessRequest(HttpContext context) { long attachmentId = context.Request.QueryString.Get<long>("attachmentId", 0); if (attachmentId <= 0) { WebUtility.Return404(context); return; } string tenantTypeId = context.Request.QueryString.Get<string>("tenantTypeId", null); if (string.IsNullOrEmpty(tenantTypeId)) { WebUtility.Return404(context); return; } AttachmentService<Attachment> attachmentService = new AttachmentService<Attachment>(tenantTypeId); Attachment attachment = attachmentService.Get(attachmentId); if (attachment == null) { WebUtility.Return404(context); return; } IUser currentUser = UserContext.CurrentUser; //判断是否有附件的购买权限或下载权限,有下载权限肯定有购买权限,目前只有未登录或积分不够时才判定为没有权限 if (!DIContainer.Resolve<Authorizer>().Attachment_Buy(attachment)) { WebUtility.Return403(context); return; } //如果还没有下载权限,则说明积分可以支付附件售价,但是还未购买,则先进行积分交易 if (!DIContainer.Resolve<Authorizer>().Attachment_Download(attachment)) { //积分交易 PointService pointService = new PointService(); pointService.Trade(currentUser.UserId, attachment.UserId, attachment.Price, string.Format("购买附件{0}", attachment.FriendlyFileName), true); } //创建下载记录 AttachmentDownloadService attachmentDownloadService = new AttachmentDownloadService(); attachmentDownloadService.Create(currentUser == null ? 0 : currentUser.UserId, attachment.AttachmentId); //下载计数 CountService countService = new CountService(TenantTypeIds.Instance().Attachment()); countService.ChangeCount(CountTypes.Instance().DownloadCount(), attachment.AttachmentId, attachment.UserId, 1, false); bool enableCaching = context.Request.QueryString.GetBool("enableCaching", true); context.Response.Status = "302 Object Moved"; context.Response.StatusCode = 302; LinktimelinessSettings linktimelinessSettings = DIContainer.Resolve<ISettingsManager<LinktimelinessSettings>>().Get(); string token = Utility.EncryptTokenForAttachmentDownload(linktimelinessSettings.Highlinktimeliness, attachmentId); context.Response.Redirect(SiteUrls.Instance().AttachmentTempUrl(attachment.AttachmentId, tenantTypeId, token, enableCaching), true); context.Response.Flush(); context.Response.End(); }
/// <summary> /// 手机端日志正文解析 /// </summary> /// <param name="body"></param> /// <param name="tenantTypeId"></param> /// <param name="associateId"></param> /// <param name="userId"></param> /// <returns></returns> public string ProcessForMobile(string body, string tenantTypeId, long associateId, long userId) { //解析at用户 AtUserService atUserService = new AtUserService(TenantTypeIds.Instance().BlogThread()); body = atUserService.ResolveBodyForDetail(body, associateId, userId, AtUserTagGenerate); AttachmentService attachmentService = new AttachmentService(tenantTypeId); IEnumerable<Attachment> attachments = attachmentService.GetsByAssociateId(associateId); if (attachments != null && attachments.Count() > 0) { IList<BBTag> bbTags = new List<BBTag>(); string htmlTemplate = "<a href=\"{1}\" target=\"_blank\" menu=\"#attachement-artdialog-{2}\">{0}</a>"; //解析文本中附件 IEnumerable<Attachment> attachmentsFiles = attachments.Where(n => n.MediaType != MediaType.Image); foreach (var attachment in attachmentsFiles) { bbTags.Add(AddBBTagForMobile(htmlTemplate, attachment)); } body = HtmlUtility.BBCodeToHtml(body, bbTags); } body = new EmotionService().EmoticonTransforms(body); body = DIContainer.Resolve<ParsedMediaService>().ResolveBodyForHtmlDetail(body, ParsedMediaTagGenerateForMobile); return body; }
/// <summary> /// 任务执行的内容 /// </summary> /// <param name="taskDetail">任务配置状态信息</param> public void Execute(TaskDetail taskDetail) { IEnumerable<TenantAttachmentSettings> allTenantAttachmentSettings = TenantAttachmentSettings.GetAll(); foreach (var tenantAttachmentSettings in allTenantAttachmentSettings) { AttachmentService service = new AttachmentService(tenantAttachmentSettings.TenantTypeId); service.DeleteTrashTemporaryAttachments(); } }
/// <summary> /// 动态处理程序 /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void BarPostActivityModule_After(BarPost sender, AuditEventArgs eventArgs) { ActivityService activityService = new ActivityService(); AuditService auditService = new AuditService(); bool? auditDirection = auditService.ResolveAuditDirection(eventArgs.OldAuditStatus, eventArgs.NewAuditStatus); if (auditDirection == true) //生成动态 { BarThreadService barThreadService = new BarThreadService(); BarThread barThread = barThreadService.Get(sender.ThreadId); if (barThread == null) return; if (sender.UserId == barThread.UserId) return; var barUrlGetter = BarUrlGetterFactory.Get(barThread.TenantTypeId); if (barUrlGetter == null) return; if (sender.ParentId > 0) { BarPost parentPost = new BarPostService().Get(sender.ParentId); if (parentPost == null) return; if (parentPost.UserId == sender.UserId) return; } Activity actvity = Activity.New(); actvity.ActivityItemKey = ActivityItemKeys.Instance().CreateBarPost(); actvity.ApplicationId = BarConfig.Instance().ApplicationId; //仅一级回复可以上传附件 if (sender.ParentId == 0) { AttachmentService attachmentService = new AttachmentService(TenantTypeIds.Instance().BarPost()); IEnumerable<Attachment> attachments = attachmentService.GetsByAssociateId(sender.PostId); if (attachments != null && attachments.Any(n => n.MediaType == MediaType.Image)) actvity.HasImage = true; //actvity.HasMusic = barThread.HasMusic; //actvity.HasVideo = barThread.HasVideo; } actvity.IsOriginalThread = true; actvity.IsPrivate = barUrlGetter.IsPrivate(barThread.SectionId); actvity.OwnerId = barThread.SectionId; actvity.OwnerName = barThread.BarSection.Name; actvity.OwnerType = barUrlGetter.ActivityOwnerType; actvity.ReferenceId = barThread.ThreadId; actvity.ReferenceTenantTypeId = TenantTypeIds.Instance().BarThread(); actvity.SourceId = sender.PostId; actvity.TenantTypeId = TenantTypeIds.Instance().BarPost(); actvity.UserId = sender.UserId; //创建从属内容,不向自己的动态收件箱推送动态 activityService.Generate(actvity, false); } else if (auditDirection == false) //删除动态 { activityService.DeleteSource(TenantTypeIds.Instance().BarPost(), sender.PostId); } }
public static void CleanUnUsedLocalPhoto() { try { var dir = new DirectoryInfo(PathUtil.GetLocalPhotoPath()); List <string> attachments = new AttachmentService(true).GetAll().Select(at => at.AttachmentUrl).ToList(); DeleteData(dir, attachments); } catch (Exception ex) { LogUtil.LogError(ErrorSeverity.Critical, "CleanData.CleanUnUsedLocalPhoto", ex.Message + Environment.NewLine + ex.InnerException, "defaultUser1", "Agency1"); } }
public void ApplicationFormViewTest() { var service = new AttachmentService(_fileRepositoryMock, _attachmentRepositoryMock); string testFilePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\TestFiles")); if (!Directory.Exists(testFilePath)) { testFilePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\TestFiles")); } var applicationViewTemplatePath = Path.Combine(testFilePath, "Section14cApplicationPdfView.html"); string template = File.ReadAllText(applicationViewTemplatePath); string applicationFormHtmlContent = service.GetApplicationFormViewContent(application, template); Assert.IsNotNull(applicationFormHtmlContent); }
public async Task <IAppAttachment> Create() { try { var crmService = StartupHelper.CreateCrmService(); IAttachmentService AttachmentService = new AttachmentService(crmService); IAppAttachment app = new AppAttachment(AttachmentService); return(app); } catch (Exception ex) { throw ex; } }
public TList <Attachment> GetAttachmentByFormID(string FormID, Pkurg.PWorld.Entities.Employee currentEmployee) { AttachmentService rs = new AttachmentService(); AttachmentQuery query = new AttachmentQuery(); query.Clear(); query.AppendEquals(string.Empty, AttachmentColumn.FormId, FormID); query.AppendEquals("and", AttachmentColumn.CreateByUserCode, currentEmployee.EmployeeCode); SqlSortBuilder <AttachmentColumn> sort = new SqlSortBuilder <AttachmentColumn>(); sort.AppendASC(AttachmentColumn.CreateAtTime); return(rs.Find(query.GetParameters(), sort.GetSortColumns())); }
public void DeleteNotFound() { // Arrange var einToTest = "30-9876543"; var testFileContents = "test"; var data = Encoding.ASCII.GetBytes(testFileContents); var memoryStream = new MemoryStream(data); var fileName = "test.txt"; var service = new AttachmentService(_fileRepositoryMock, _attachmentRepositoryMock); service.UploadAttachment(einToTest, memoryStream, fileName, "text/plain"); service.DeleteAttachement(einToTest, Guid.Empty); }
/// <summary> /// 资讯详情页 /// </summary> public ActionResult ContentItemDetail(long contentItemId) { ContentItem contentItem = contentItemService.Get(contentItemId); if (contentItem == null || contentItem.User == null) { return(HttpNotFound()); } //验证是否通过审核 long currentSpaceUserId = UserIdToUserNameDictionary.GetUserId(contentItem.User.UserName); if (!authorizer.IsAdministrator(CmsConfig.Instance().ApplicationId) && contentItem.UserId != currentSpaceUserId && (int)contentItem.AuditStatus < (int)(new AuditService().GetPubliclyAuditStatus(CmsConfig.Instance().ApplicationId))) { return(Redirect(SiteUrls.Instance().SystemMessage(TempData, new SystemMessageViewModel { Title = "尚未通过审核", Body = "由于当前资讯尚未通过审核,您无法浏览当前内容。", StatusMessageType = StatusMessageType.Hint }))); } AttachmentService <Attachment> attachmentService = new AttachmentService <Attachment>(TenantTypeIds.Instance().ContentItem()); //更新浏览计数 CountService countService = new CountService(TenantTypeIds.Instance().ContentItem()); countService.ChangeCount(CountTypes.Instance().HitTimes(), contentItem.ContentItemId, contentItem.UserId, 1, true); if (UserContext.CurrentUser != null) { //创建访客记录 VisitService visitService = new VisitService(TenantTypeIds.Instance().ContentItem()); visitService.CreateVisit(UserContext.CurrentUser.UserId, UserContext.CurrentUser.DisplayName, contentItem.ContentItemId, contentItem.Title); } //设置SEO信息 pageResourceManager.InsertTitlePart(contentItem.Title); List <string> keywords = new List <string>(); keywords.AddRange(contentItem.TagNames); string keyword = string.Join(" ", keywords.Distinct()); keyword += " " + string.Join(" ", ClauseScrubber.TitleToKeywords(contentItem.Title)); pageResourceManager.SetMetaOfKeywords(keyword); pageResourceManager.SetMetaOfDescription(contentItem.Summary); return(View(contentItem)); }
/// <summary> /// 转换成WikiPage /// </summary> public WikiPage AsWikiPage() { WikiPage page = WikiPage.New(); WikiService service = new WikiService(); if (this.PageId < 1)//创建 { if (this.OwnerId.HasValue) { page.OwnerId = this.OwnerId.Value; } else { page.OwnerId = UserContext.CurrentUser.UserId; } page.UserId = UserContext.CurrentUser.UserId; page.Author = UserContext.CurrentUser.DisplayName; page.Title = this.Title; } else//编辑词条 { page = service.Get(this.PageId); } page.IsLocked = this.IsLocked; page.FeaturedImageAttachmentId = this.FeaturedImageAttachmentId; if (page.FeaturedImageAttachmentId > 0) { Attachment attachment = new AttachmentService(TenantTypeIds.Instance().WikiPage()).Get(this.FeaturedImageAttachmentId); if (attachment != null) { page.FeaturedImage = attachment.GetRelativePath() + "\\" + attachment.FileName; } else { page.FeaturedImageAttachmentId = 0; } } else { page.FeaturedImage = string.Empty; } return(page); }
/// <summary> /// 动态处理程序 /// </summary> /// <param name="blogThread"></param> /// <param name="eventArgs"></param> private void BlogThreadActivityModule_After(BlogThread blogThread, AuditEventArgs eventArgs) { //生成动态 ActivityService activityService = new ActivityService(); AuditService auditService = new AuditService(); bool?auditDirection = auditService.ResolveAuditDirection(eventArgs.OldAuditStatus, eventArgs.NewAuditStatus); if (auditDirection == true) { //初始化Owner为用户的动态 Activity activityOfUser = Activity.New(); activityOfUser.ActivityItemKey = ActivityItemKeys.Instance().CreateBlogThread(); activityOfUser.ApplicationId = BlogConfig.Instance().ApplicationId; //判断是否有图片、音频、视频 AttachmentService attachmentService = new AttachmentService(TenantTypeIds.Instance().BlogThread()); IEnumerable <Attachment> attachments = attachmentService.GetsByAssociateId(blogThread.ThreadId); if (attachments != null && attachments.Any(n => n.MediaType == MediaType.Image)) { activityOfUser.HasImage = true; } activityOfUser.HasMusic = false; activityOfUser.HasVideo = false; activityOfUser.IsOriginalThread = !blogThread.IsReproduced; activityOfUser.IsPrivate = blogThread.PrivacyStatus == PrivacyStatus.Private ? true : false; activityOfUser.UserId = blogThread.UserId; activityOfUser.ReferenceId = 0; activityOfUser.ReferenceTenantTypeId = string.Empty; activityOfUser.SourceId = blogThread.ThreadId; activityOfUser.TenantTypeId = TenantTypeIds.Instance().BlogThread(); activityOfUser.OwnerId = blogThread.UserId; activityOfUser.OwnerName = blogThread.Author; activityOfUser.OwnerType = ActivityOwnerTypes.Instance().User(); //是否是公开的(用于是否推送站点动态) bool isPublic = blogThread.PrivacyStatus == PrivacyStatus.Public ? true : false; //生成动态 activityService.Generate(activityOfUser, true, isPublic); } //删除动态 else if (auditDirection == false) { activityService.DeleteSource(TenantTypeIds.Instance().BlogThread(), blogThread.ThreadId); } }
public void Attachment_Add() { var task = BusinessHelper.CreateTask(); var attachment = AttachmentService.AttachmentNew(SourceType.Task, task.TaskId); attachment.Name = DataHelper.RandomString(100); attachment.FileType = DataHelper.RandomString(30); Assert.IsTrue(attachment.IsValid, string.Format("IsValid should be true, but has following errors: {0}", attachment.BrokenRulesCollection)); attachment = AttachmentService.AttachmentSave(attachment); attachment = AttachmentService.AttachmentFetch(attachment.AttachmentId); Assert.IsTrue(attachment != null, "Object should not be null"); }
public void Create(TaskViewModel viewModel, string serverPath) { _unitOfWork.TaskRepository.Add(new Models.Entities.Task() { Attachment = AttachmentService.CheckFileAbleToSave(viewModel.AttachmentFile) ? AttachmentService.SaveImg(viewModel.AttachmentFile, serverPath, "Task") : null, AssignedDate = viewModel.AssignedDate, Description = viewModel.Description, AssignedToUser = viewModel.AssignedToUser, Status = viewModel.Status, Title = viewModel.Title, Id = viewModel.Id }); _unitOfWork.CommitChanges(); }
/// <summary> /// 得到附件信息列表 /// </summary> /// <returns></returns> public TList <Attachment> GetAttachmentList() { AttachmentService service = new AttachmentService(); AttachmentQuery query = new AttachmentQuery(); query.Clear(); SqlSortBuilder <AttachmentColumn> sort = new SqlSortBuilder <AttachmentColumn>(); sort.AppendASC(AttachmentColumn.CreateAtTime); return(service.Find(query.GetParameters(), sort.GetSortColumns())); }
public AttachmentController() { attachmentService = new AttachmentService(); UploadConfig = new UploadConfig() { AllowExtensions = Config.GetStringList("imageAllowFiles"), PathFormat = Config.GetString("imagePathFormat"), SizeLimit = Config.GetInt("imageMaxSize"), UploadFieldName = Config.GetString("imageFieldName") }; Result = new UploadResult() { State = UploadState.Unknown }; }
public ActionResult Add(AttachmentInfo model) { bool errors = false; if (string.IsNullOrEmpty(model.Title)) { errors = true; ModelState.AddModelError("Title", "请输入标题"); } if (!errors && ModelState.IsValid) { var newModel = AttachmentService.Create(model); ViewBag.Msg = "保存成功!<a href=\"list\">返回</a>"; } return(View()); }
public void DeleteAttachement() { // Arrange var einToTest = "30-9876543"; var testFileContents = "test"; var data = Encoding.ASCII.GetBytes(testFileContents); var memoryStream = new MemoryStream(data); var fileName = "test.txt"; var service = new AttachmentService(_fileRepositoryMock, _attachmentRepositoryMock); var upload = service.UploadAttachment(einToTest, data, fileName, "text/plain"); service.DeleteAttachement(einToTest, new Guid(upload.Id)); Assert.IsTrue(upload.Deleted); }
/// <summary> /// 注册组件 /// </summary> /// <param name="services">服务</param> /// <returns>服务提供者</returns> public static IServiceProvider RegisterComponents(IServiceCollection services) { AssemblyConfigLocalMember assemblyConfigLocalMember = new AssemblyConfigLocalMember(); assemblyConfigLocalMember.ProtoAssemblyConfigReader = new AssemblyConfigJson(); AssemblyConfigInfo assemblyConfig = assemblyConfigLocalMember.Reader(); //实例化一个autofac的创建容器 var builder = new ContainerBuilder(); IServiceProvider serviceProvider; builder.UnifiedRegisterAssemblys(services, new BuilderParam() { AssemblyServices = assemblyConfig.Services, RegisteringServiceAction = () => { builder.RegisterType <HttpContextAccessor>().As <IHttpContextAccessor>().AsSelf().PropertiesAutowired(); builder.RegisterType <IdentityCookieAuth>().As <IIdentityAuthVali>().AsSelf().PropertiesAutowired(); builder.RegisterType <IdentityCookieAuth>().As <IIdentityExit>().AsSelf().PropertiesAutowired(); builder.RegisterType <WorkflowConfigCache>().As <IWorkflowConfigReader>().AsSelf().PropertiesAutowired(); builder.RegisterType <WorkflowInitSequenceService>().As <IWorkflowFormService>().AsSelf().PropertiesAutowired(); //builder.RegisterInstance() builder.RegisterType <LanguageLibraryCache>().As <ILanguageLibrary>().AsSelf().PropertiesAutowired(); builder.RegisterType <LanguageLibraryConfigJson>().As <IReaderAll <LanguageInfo> >().AsSelf().PropertiesAutowired(); } }, out serviceProvider); AttachmentService attachmentService = AutofacTool.Resolve <AttachmentService>(); AttachmentOwnerLocalMember attachmentOwnerLocalMember = AutofacTool.Resolve <AttachmentOwnerLocalMember>(); attachmentOwnerLocalMember.ProtoAttachmentOwnerReader = AutofacTool.Resolve <AttachmentOwnerJson>(); attachmentService.AttachmentOwnerReader = attachmentOwnerLocalMember; var languageCache = AutofacTool.Resolve <LanguageLibraryCache>(); // var languageJson = AutofacTool.Resolve<LanguageLibraryJson>(); //languageJson.JsonFile = @"F:\MyWorks\net\Hzdtf.FoundationFramework\WebDemoCore\Hzdtf.WebDemo.Core\Config\LanguageLibrary\test.min.json"; /// languageCache.ProtoLanguageLibraryReader = languageJson; LanguageUtil.LanguageLibrary = languageCache; return(serviceProvider); }
public ActionResult Upload() { if (Request.Files != null) { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { string fileName = Path.GetFileName(file.FileName); Attachment attachment = AttachmentService.SaveAttachment(file.ContentLength, file.ContentType, fileName); file.SaveAs(attachment.FilePath); } } } return(RedirectToAction("Index")); }
public JsonResult GetAttachments(string gid) { AttachmentService service = new AttachmentService(); Response <IEnumerable <Attachment> > resp = service.GetAttachmentsByGroupID(new GetAttachmentsByGroupIDRequest() { GroupID = gid }); if (resp.IsSuccess) { return(Json(resp.Result)); } else { return(Json(new { msg = "没有对应附件" })); } }
public ActionResult AddAttachmentLine(string fileName, int fileSize, string documentTypeValueType, string validationType, string sheet = "") { string message = ""; AttachmentViewModel attachment = new AttachmentViewModel(); ValidationResult validateResult = new ValidationResult(); try { attachment.FileName = fileName; attachment.FileSize = fileSize; attachment.FileSizeMB = (attachment.FileSize / 1024f) / 1024f; attachment.FileExtension = Path.GetExtension(fileName).Substring(1); attachment.FileUniqueKey = AttachmentService.GetFileUniqueKey(); attachment.SavedFileName = attachment.FileUniqueKey + "_" + fileName; attachment.DocumentTypeValueType = documentTypeValueType; //case excel file attachment.SheetNameExcel = sheet; validateResult = AttachmentService.ValidateFileAttachment(attachment, validationType); } catch (Exception ex) { message = ex.ToString(); } if (validateResult.ErrorFlag) { return(Json(new { success = false, message = validateResult.Message, }, "text/html", JsonRequestBehavior.AllowGet)); } else { return(Json(new { success = true, message = message, savedFilename = attachment.SavedFileName, fileUniqueKey = attachment.FileUniqueKey, Url = Url.Action("DisplayAttachmentRow", attachment) }, "text/html", JsonRequestBehavior.AllowGet)); } }
public async Task <IActionResult> UploadFTP() { var formdata = await Request.ReadFormAsync(); var form = new Dictionary <string, object>(); foreach (var key in formdata.Keys) { var value = Request.Form[key][0]; form.Add(key, value); } IFormFile file = formdata.Files[0]; using var fileStream = file.OpenReadStream(); byte[] bytes = new byte[file.Length]; fileStream.Read(bytes, 0, (int)file.Length); Stream stream = file.OpenReadStream(); string traceIdentifier = HttpContext.TraceIdentifier; Startup.Progress.Add(traceIdentifier, 0); var watch = System.Diagnostics.Stopwatch.StartNew(); string methodName = "UploadFTP"; ResponseDTO response = new ResponseDTO(); try { Task[] tasks = new[] { Task.Run(() => AttachmentService.UploadFtp(appSettings, watch, traceIdentifier, form, file, bytes)) }; return(Ok($"Request submitted successfully: {traceIdentifier}")); } catch (Exception e) { response.Success = false; response.Msg = e.Message; watch.Stop(); Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(form)}"); Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}"); return(BadRequest(response)); } }
public async Task CreateAsync_ShouldThrow_ArgumentNullEx() { var options = TestUtilities.GetOptions(nameof(CreateAsync_ShouldThrow_ArgumentNullEx)); var mockAttachment = new Mock <Attachment>().Object; var mockAttachmentDTO = new Mock <AttachmentDTO>().Object; var mockAttachmentDTOMapper = new Mock <IAttachmentDTOMapper>(); mockAttachmentDTOMapper.Setup(a => a.MapFrom(mockAttachmentDTO)).Returns(mockAttachment); mockAttachmentDTOMapper.Setup(a => a.MapFrom(mockAttachment)).Returns(mockAttachmentDTO); using (var assertContext = new TBIAppDbContext(options)) { var attachmentService = new AttachmentService(assertContext, mockAttachmentDTOMapper.Object); await attachmentService.CreateAsync(null); } }
public ActionResult RealDelete(int[] ModelID) { foreach (int mid in ModelID) { var _commonModel = commonModelService.Find(mid); if (_commonModel == null) { return(Fail("查无此文章")); } if (_commonModel.State == CommonModelState.UnDelete) { return(Fail("《" + _commonModel.Title + "》是固定文章,不能删除!")); } commonModelService.Delete(_commonModel, false); } //附件处理 AttachmentService _attachmentService = new AttachmentService(); //查询相关附件 var _attachments = _attachmentService.FindAll().ToList();//_attachmentService.FindList(null, user, string.Empty).ToList(); if (_attachments == null) { return(View()); } //遍历附件 foreach (var _att in _attachments) { var _filePath = Server.MapPath(_att.FileParth); //未使用改附件则删除附件和数据库中的记录 if (_att.CommonModels.Count == 0) { System.IO.File.Delete(_filePath); _attachmentService.Delete(_att, false); } } if (commonModelService.Save() > 0) { return(Success()); } else { return(Fail()); } }
public JsonResult AddAttachment() { var form = HttpContext.Request.Form; var file = HttpContext.Request.Files[0]; string customerId = form["CustomerId"]; String attachmentData = "{" + "CustomerId: \"" + form["CustomerId"] + "\", " + "Description: \"" + form["Description"] + "\", " + "Type: \"" + form["Type"] + "\", " + "Category: \"" + form["Category"] + "\", " + "FileName: \"" + form["FileName"] + "\", " + "Location: \"" + ConfigurationManager.AppSettings["AttachmentsFolder"].Replace("\\", "\\\\") + "\\\\" + customerId + "\", " + "AttachedBy: \"" + form["AttachedBy"] + "\"}"; IAttachmentService dataService = new AttachmentService(); var addResult = dataService.AddAttachment(attachmentContext, attachmentData, file); return(Json(addResult, JsonRequestBehavior.AllowGet)); }
public IEnumerable <string> GetAllImageUrls(Guid contentId) { List <string> images = new List <string>(); IContent content = ContentService.Get(contentId); if (content != null) { LegacyContentIdentifier lContentId = LegacyContentService.GetLegacyIdentification(content); IViewableContent vContent = LegacyContentService.GetViewableContent(contentId); if (vContent != null && lContentId != null) { int applicationId; string[] ids = vContent.Container.UniqueID.Split(new[] { ':' }); if (ids.Length == 2) { if (int.TryParse(ids[1], out applicationId)) { IAttachment attachment = AttachmentService.Get(applicationId, (int)vContent.Container.ApplicationType, 0, lContentId.LegacyId); if (attachment != null) { if (FileViewerService.GetMediaType(attachment.File, FileViewerViewType.Preview, false) == FileViewerMediaType.Image) { images.Add(Globals.FullPath(attachment.Url)); } } } } } //Now does the content contain any images images.AddRange(ParseImagesFromContent(content.HtmlDescription(""))); //Container Image images.Add(Globals.FullPath(content.Application.Container.AvatarUrl)); } return(images.Distinct(StringComparer.OrdinalIgnoreCase)); }
// // GET: /Front/Download/ public ActionResult List() { //在线互动 ViewBag.RootCategoryInfo = CategoryService.Get(87); //相关下载 ViewBag.CurrentCategoryInfo = CategoryService.Get(91); int pageIndex = CECRequest.GetQueryInt("page", 1); ViewBag.List = AttachmentService.List(new SearchSetting() { PageIndex = pageIndex, PageSize = 20, ShowDeleted = false }); return(View()); }
public void Attachment_New() { var attachment = AttachmentService.AttachmentNew(SourceType.None, 0); Assert.IsTrue(attachment.IsNew, "IsNew should be true"); Assert.IsTrue(attachment.IsDirty, "IsDirty should be true"); Assert.IsFalse(attachment.IsValid, "IsValid should be false"); Assert.IsTrue(attachment.IsSelfDirty, "IsSelfDirty should be true"); Assert.IsFalse(attachment.IsSelfValid, "IsSelfValid should be false"); Assert.IsTrue(ValidationHelper.ContainsRule(attachment, DbType.String, "Name"), "Name should be required"); Assert.IsTrue(ValidationHelper.ContainsRule(attachment, DbType.String, "FileType"), "FileType should be required"); Assert.IsTrue(ValidationHelper.ContainsRule(attachment, DbType.Int32, "SourceId"), "SourceId should be required"); Assert.IsTrue(ValidationHelper.ContainsRule(attachment, "rule://epiworx.business.attachmentsourcetyperequired/SourceType"), "SourceType should be required"); }
// // GET: /Download/ public ActionResult Index() { int catId = CECRequest.GetQueryInt("catId", 0); if (catId > 0) { ViewBag.CurrentCategoryInfo = CategoryService.Get(catId); } var list = AttachmentService.List(new AttachmentSearchSetting() { PageIndex = CECRequest.GetQueryInt("page", 1), CategoryId = catId }); ViewBag.List = list; return(View()); }
/// <summary> /// 撰写词条 /// </summary> /// <param name="wikiPage">词条实体</param> public bool Create(WikiPage wikiPage, string body) { EventBus <WikiPage> .Instance().OnBefore(wikiPage, new CommonEventArgs(EventOperationType.Instance().Create())); //设置审核状态,草稿的审核状态为待审核 AuditService auditService = new AuditService(); auditService.ChangeAuditStatusForCreate(wikiPage.UserId, wikiPage); long pageId = 0; long.TryParse(wikiPageRepository.Insert(wikiPage).ToString(), out pageId); if (pageId > 0) { WikiPageVersion wikiPageVersion = WikiPageVersion.New(); wikiPageVersion.PageId = pageId; wikiPageVersion.TenantTypeId = wikiPage.TenantTypeId; wikiPageVersion.OwnerId = wikiPage.OwnerId; wikiPageVersion.VersionNum = 1; wikiPageVersion.Title = wikiPage.Title; wikiPageVersion.UserId = wikiPage.UserId; wikiPageVersion.Author = wikiPage.Author; wikiPageVersion.Summary = StringUtility.Trim(Tunynet.Utilities.HtmlUtility.StripHtml(body, true, false).Replace("\r", "").Replace("\n", ""), 200); wikiPageVersion.Body = body; wikiPageVersion.AuditStatus = AuditStatus.Success; wikiPageVersionRepository.Insert(wikiPageVersion); //转换临时附件 AttachmentService attachmentService = new AttachmentService(TenantTypeIds.Instance().WikiPage()); attachmentService.ToggleTemporaryAttachments(wikiPage.OwnerId, TenantTypeIds.Instance().WikiPage(), wikiPageVersion.PageId); OwnerDataService ownerDataService = new OwnerDataService(TenantTypeIds.Instance().User()); ownerDataService.Change(wikiPage.UserId, OwnerDataKeys.Instance().PageCount(), 1); EventBus <WikiPage> .Instance().OnAfter(wikiPage, new CommonEventArgs(EventOperationType.Instance().Create())); EventBus <WikiPage, AuditEventArgs> .Instance().OnAfter(wikiPage, new AuditEventArgs(null, wikiPage.AuditStatus)); return(true); } return(false); }
public ActionResult ValidatePhotoFile(string fileName, int fileSize) { string message = ""; AttachmentViewModel attachment = new AttachmentViewModel(); ValidationResult validateResult = new ValidationResult(); try { attachment.FileName = fileName; attachment.FileSize = fileSize; attachment.FileSizeMB = (attachment.FileSize / 1024f) / 1024f; attachment.FileExtension = Path.GetExtension(fileName).Substring(1); attachment.FileUniqueKey = AttachmentService.GetFileUniqueKey(); attachment.SavedFileName = attachment.FileUniqueKey + "_" + fileName; validateResult = AttachmentService.ValidateFileAttachment(attachment, "PHOTO"); } catch (Exception ex) { message = ex.ToString(); } if (validateResult.ErrorFlag) { return(Json(new { success = false, message = validateResult.Message, }, "text/html", JsonRequestBehavior.AllowGet)); } else { return(Json(new { success = true, message = message, savedFilename = attachment.SavedFileName, fileUniqueKey = attachment.FileUniqueKey, //Url = Url.Action("DisplayAttachmentRow", attachment) }, "text/html", JsonRequestBehavior.AllowGet)); } }
public void ManagePhotoFile(AssignUserRoleViewModel formData) { try { //Save employee photo if (formData.Photo.DeletedPhotoFlag) { //Delete uploaded photo AttachmentService.DeleteFile(formData.Photo.PhotoSavedFilename, ConfigurationManager.AppSettings["TempFilePath"]); AttachmentService.DeleteFile(formData.Photo.FilenameToDelete, ConfigurationManager.AppSettings["TempFilePath"]); //Delete old photo from agent document AttachmentService.DeleteFile(formData.AssignUserRoleItem.PhotoFileName, AttachmentService.GetDocumentFilePath(AssignUserRoleViewModel.ProcessCode)); } else { if (!string.IsNullOrEmpty(formData.Photo.PhotoSavedFilename)) { //Move file from temp to agent document storage List <AttachmentViewModel> attachmentList = new List <AttachmentViewModel>(); AttachmentViewModel attachment = new AttachmentViewModel(); attachment.SavedFileName = formData.Photo.PhotoSavedFilename; //Target path attachment.DocumentFilePath = AttachmentService.GetDocumentFilePath(AssignUserRoleViewModel.ProcessCode); attachmentList.Add(attachment); AttachmentService.ManageFile(attachmentList); //Delete old photo from agent document AttachmentService.DeleteFile(formData.AssignUserRoleItem.PhotoFileName, AttachmentService.GetDocumentFilePath(AssignUserRoleViewModel.ProcessCode)); } } } catch (Exception ex) { } }
public void AttachmentsSave() { // Arrange var einToTest = "30-9876543"; var testFileContents = "test"; var data = Encoding.ASCII.GetBytes(testFileContents); var memoryStream = new MemoryStream(data); var fileName = "test.txt"; var service = new AttachmentService(_fileRepositoryMock, _attachmentRepositoryMock); var upload = service.UploadAttachment(einToTest, memoryStream, fileName, "text/plain"); using (var outMemoryStream = new MemoryStream()) { service.DownloadAttachment(outMemoryStream, einToTest, upload.Id); string outText = Encoding.ASCII.GetString(outMemoryStream.ToArray()); Assert.AreEqual(outText, testFileContents); } }
public ActionResult Add(Article article) { if (ModelState.IsValid) { //设置固定值 article.CommonModel.Hits = 0; article.CommonModel.Inputer = User.Identity.Name; article.CommonModel.Model = "Article"; article.CommonModel.ReleaseDate = DateTime.Now; article.CommonModel.Status = 99; article = articleService.Add(article); if (article.ArticleID > 0) { //附件处理 InterfaceAttachmentService _attachmentService = new AttachmentService(); //查询相关附件 var _attachments = _attachmentService.FindList(null, User.Identity.Name, string.Empty).ToList(); //遍历附件 foreach (var _att in _attachments) { var _filePath = Url.Content(_att.FileParth); //文章首页图片或内容中使用了该附件则更改ModelID为文章保存后的ModelID if ((article.CommonModel.DefaultPicUrl != null && article.CommonModel.DefaultPicUrl.IndexOf(_filePath) >= 0) || article.Content.IndexOf(_filePath) > 0) { _att.ModelID = article.ModelID; _attachmentService.Update(_att); } //未使用改附件则删除附件和数据库中的记录 else { System.IO.File.Delete(Server.MapPath(_att.FileParth)); _attachmentService.Delete(_att); } } return View("AddSuccess", article); } } return View(article); }
/// <summary> /// 动态处理程序 /// </summary> /// <param name="blogThread"></param> /// <param name="eventArgs"></param> private void BlogThreadActivityModule_After(BlogThread blogThread, AuditEventArgs eventArgs) { //生成动态 ActivityService activityService = new ActivityService(); AuditService auditService = new AuditService(); bool? auditDirection = auditService.ResolveAuditDirection(eventArgs.OldAuditStatus, eventArgs.NewAuditStatus); if (auditDirection == true) { //初始化Owner为用户的动态 Activity activityOfUser = Activity.New(); activityOfUser.ActivityItemKey = ActivityItemKeys.Instance().CreateBlogThread(); activityOfUser.ApplicationId = BlogConfig.Instance().ApplicationId; //判断是否有图片、音频、视频 AttachmentService attachmentService = new AttachmentService(TenantTypeIds.Instance().BlogThread()); IEnumerable<Attachment> attachments = attachmentService.GetsByAssociateId(blogThread.ThreadId); if (attachments != null && attachments.Any(n => n.MediaType == MediaType.Image)) { activityOfUser.HasImage = true; } activityOfUser.HasMusic = false; activityOfUser.HasVideo = false; activityOfUser.IsOriginalThread = !blogThread.IsReproduced; activityOfUser.IsPrivate = blogThread.PrivacyStatus == PrivacyStatus.Private ? true : false; activityOfUser.UserId = blogThread.UserId; activityOfUser.ReferenceId = 0; activityOfUser.ReferenceTenantTypeId = string.Empty; activityOfUser.SourceId = blogThread.ThreadId; activityOfUser.TenantTypeId = TenantTypeIds.Instance().BlogThread(); activityOfUser.OwnerId = blogThread.UserId; activityOfUser.OwnerName = blogThread.Author; activityOfUser.OwnerType = ActivityOwnerTypes.Instance().User(); //是否是公开的(用于是否推送站点动态) bool isPublic = blogThread.PrivacyStatus == PrivacyStatus.Public ? true : false; //生成动态 activityService.Generate(activityOfUser, true, isPublic); } //删除动态 else if (auditDirection == false) { activityService.DeleteSource(TenantTypeIds.Instance().BlogThread(), blogThread.ThreadId); } }
/// <summary> /// 将EditModel转换成数据库实体 /// </summary> public ContentItem AsContentItem(System.Web.HttpRequestBase Request) { ContentItem contentItem = null; if (this.ContentItemId > 0) { contentItem = new ContentItemService().Get(this.ContentItemId); } else { contentItem = new ContentItem(); contentItem.Author = UserContext.CurrentUser == null ? "" : UserContext.CurrentUser.DisplayName; contentItem.IP = WebUtility.GetIP(); contentItem.UserId = UserContext.CurrentUser == null ? 0 : UserContext.CurrentUser.UserId; contentItem.ContentTypeId = this.ContentTypeId; } if (this.ContentFolderId > 0) { ContentFolder folder = new ContentFolderService().Get(this.ContentFolderId); if (folder != null) { contentItem.ContentFolderId = this.ContentFolderId; if (this.AdditionalProperties == null) this.AdditionalProperties = new Dictionary<string, object>(); IEnumerable<ContentTypeColumnDefinition> contentTypeColumnDefinitions = new MetadataService().GetColumnsByContentTypeId(this.ContentTypeId); foreach (var item in contentTypeColumnDefinitions) { object value = null; switch (item.DataType) { case "int": case "long": value = Request.Form.Get<long>(item.ColumnName, 0); break; case "datetime": value = Request.Form.Get<DateTime>(item.ColumnName, DateTime.MinValue); break; case "bool": value = Request.Form.Get<bool>(item.ColumnName, false); break; default: value = Request.Form.Get<string>(item.ColumnName, string.Empty); break; } if (this.AdditionalProperties.ContainsKey(item.ColumnName)) this.AdditionalProperties[item.ColumnName] = value; else this.AdditionalProperties.Add(item.ColumnName, value); } } } contentItem.AdditionalProperties = this.AdditionalProperties; contentItem.IsEssential = false; contentItem.IsLocked = false; contentItem.IsGlobalSticky = this.IsGlobalSticky; if (this.GlobalStickyDate.CompareTo(DateTime.MinValue) > 0) contentItem.GlobalStickyDate = this.GlobalStickyDate; contentItem.IsFolderSticky = this.IsFolderSticky; if (this.FolderStickyDate.CompareTo(DateTime.MinValue) > 0) contentItem.FolderStickyDate = this.FolderStickyDate; contentItem.DisplayOrder = this.DisplayOrder; contentItem.FeaturedImageAttachmentId = this.FeaturedImageAttachmentId; contentItem.LastModified = DateTime.UtcNow; contentItem.Title = this.Title; if (this.ReleaseDate.CompareTo(DateTime.MinValue) > 0) contentItem.ReleaseDate = this.ReleaseDate.ToUniversalTime(); //摘要 contentItem.Summary = this.Summary ?? string.Empty; if (this.TrimBodyAsSummary) { string summary = HtmlUtility.TrimHtml(Request.Form.Get<string>("Body", string.Empty), TextLengthSettings.TEXT_DESCRIPTION_MAXLENGTH); contentItem.Summary = summary; } if (contentItem.AdditionalProperties.ContainsKey("AutoPage")) { bool autoPage = Request.Form.Get<bool>("AutoPage", false); int pageLength = Request.Form.Get<int>("PageLength", 1000); string body = contentItem.AdditionalProperties.Get<string>("Body", string.Empty); if (autoPage) { pageLength = pageLength > 0 ? pageLength : 1000; if (!string.IsNullOrEmpty(body)) { body = body.Replace(ContentPages.PageSeparator, ""); contentItem.AdditionalProperties["Body"] = string.Join(ContentPages.PageSeparator, ContentPages.GetPageContentForStorage(body, pageLength, true).ToArray()); } } else { pageLength = 0; body = body.Replace(ContentPages.PageSeparator, ""); contentItem.AdditionalProperties["Body"] = body; contentItem.AdditionalProperties["pageLength"] = pageLength; } } if (contentItem.AdditionalProperties.ContainsKey("Editor")) { string editor = contentItem.AdditionalProperties.Get<string>("Editor", string.Empty); if (string.IsNullOrEmpty(editor)) contentItem.AdditionalProperties["Editor"] = contentItem.ContentFolder.Editor; } if (contentItem.FeaturedImageAttachmentId > 0) { AttachmentService<Attachment> attachmentService = new AttachmentService<Attachment>(TenantTypeIds.Instance().ContentItem()); Attachment attachment = attachmentService.Get(contentItem.FeaturedImageAttachmentId); if (attachment != null) { contentItem.FeaturedImage = attachment.GetRelativePath() + "\\" + attachment.FileName; } else { contentItem.FeaturedImageAttachmentId = 0; } } else { contentItem.FeaturedImage = string.Empty; } return contentItem; }
/// <summary> /// 创建资讯评论的动态块 /// </summary> /// <param name="ActivityId"></param> /// <returns></returns> //[DonutOutputCache(CacheProfile = "Frequently")] public ActionResult _CreateCmsComment(long ActivityId) { Activity activity = new ActivityService().Get(ActivityId); if (activity == null) return Content(string.Empty); ContentItem contentItem = contentItemService.Get(activity.ReferenceId); if (contentItem == null) return Content(string.Empty); IEnumerable<Attachment> attachments = new AttachmentService(TenantTypeIds.Instance().ContentItem()).GetsByAssociateId(contentItem.ContentItemId); if (attachments != null && attachments.Count() > 0) { IEnumerable<Attachment> attachmentImages = attachments.Where(n => n.MediaType == MediaType.Image); if (attachmentImages != null && attachmentImages.Count() > 0) ViewData["Attachments"] = attachmentImages.FirstOrDefault(); } Comment comment = commentService.Get(activity.SourceId); if (comment == null) return Content(string.Empty); ViewData["contentItem"] = contentItem; ViewData["ActivityId"] = ActivityId; return View(comment); }
/// <summary> /// 动态处理程序 /// </summary> /// <param name="barThread"></param> /// <param name="eventArgs"></param> private void BarThreadActivityModule_After(BarThread barThread, AuditEventArgs eventArgs) { //1、通过审核的内容才生成动态;(不满足) //2、把通过审核的内容设置为未通过审核或者删除内容,需要移除动态;(不满足) //3、把未通过审核的内容通过审核,需要添加动态; (不满足) //4、详见动态需求说明 //生成动态 ActivityService activityService = new ActivityService(); AuditService auditService = new AuditService(); bool? auditDirection = auditService.ResolveAuditDirection(eventArgs.OldAuditStatus, eventArgs.NewAuditStatus); if (auditDirection == true) //生成动态 { if (barThread.BarSection == null) return; var barUrlGetter = BarUrlGetterFactory.Get(barThread.TenantTypeId); if (barUrlGetter == null) return; //生成Owner为帖吧的动态 Activity actvityOfBar = Activity.New(); actvityOfBar.ActivityItemKey = ActivityItemKeys.Instance().CreateBarThread(); actvityOfBar.ApplicationId = BarConfig.Instance().ApplicationId; AttachmentService attachmentService = new AttachmentService(TenantTypeIds.Instance().BarThread()); IEnumerable<Attachment> attachments = attachmentService.GetsByAssociateId(barThread.ThreadId); if (attachments != null && attachments.Any(n => n.MediaType == MediaType.Image)) actvityOfBar.HasImage = true; actvityOfBar.IsOriginalThread = true; actvityOfBar.IsPrivate = false; actvityOfBar.UserId = barThread.UserId; actvityOfBar.ReferenceId = 0;//没有涉及到的实体 actvityOfBar.ReferenceTenantTypeId = string.Empty; actvityOfBar.SourceId = barThread.ThreadId; actvityOfBar.TenantTypeId = TenantTypeIds.Instance().BarThread(); actvityOfBar.OwnerId = barThread.SectionId; actvityOfBar.OwnerName = barThread.BarSection.Name; actvityOfBar.OwnerType = barUrlGetter.ActivityOwnerType; activityService.Generate(actvityOfBar, false); if (!barUrlGetter.IsPrivate(barThread.SectionId)) { //生成Owner为用户的动态 Activity actvityOfUser = Activity.New(); actvityOfUser.ActivityItemKey = actvityOfBar.ActivityItemKey; actvityOfUser.ApplicationId = actvityOfBar.ApplicationId; actvityOfUser.HasImage = actvityOfBar.HasImage; actvityOfUser.HasMusic = actvityOfBar.HasMusic; actvityOfUser.HasVideo = actvityOfBar.HasVideo; actvityOfUser.IsOriginalThread = actvityOfBar.IsOriginalThread; actvityOfUser.IsPrivate = actvityOfBar.IsPrivate; actvityOfUser.UserId = actvityOfBar.UserId; actvityOfUser.ReferenceId = actvityOfBar.ReferenceId; actvityOfUser.SourceId = actvityOfBar.SourceId; actvityOfUser.TenantTypeId = actvityOfBar.TenantTypeId; actvityOfUser.OwnerId = barThread.UserId; actvityOfUser.OwnerName = barThread.User.DisplayName; actvityOfUser.OwnerType = ActivityOwnerTypes.Instance().User(); activityService.Generate(actvityOfUser, false); } } else if (auditDirection == false) //删除动态 { activityService.DeleteSource(TenantTypeIds.Instance().BarThread(), barThread.ThreadId); } }
public override void ProcessRequest(HttpContext context) { long attachmentId = context.Request.QueryString.Get<long>("attachmentId", 0); if (attachmentId <= 0) { WebUtility.Return404(context); return; } string tenantTypeId = context.Request.QueryString.GetString("tenantTypeId", string.Empty); if (string.IsNullOrEmpty(tenantTypeId)) { WebUtility.Return404(context); return; } //检查链接是否过期 string token = context.Request.QueryString.GetString("token", string.Empty); bool isTimeout = true; long attachmentIdInToken = Utility.DecryptTokenForAttachmentDownload(token, out isTimeout); if (isTimeout || attachmentIdInToken != attachmentId) { WebUtility.Return403(context); return; } AttachmentService<Attachment> attachmentService = new AttachmentService<Attachment>(tenantTypeId); Attachment attachment = attachmentService.Get(attachmentId); if (attachment == null) { WebUtility.Return404(context); return; } bool enableCaching = context.Request.QueryString.GetBool("enableCaching", true); DateTime lastModified = attachment.DateCreated.ToUniversalTime(); if (enableCaching && IsCacheOK(context, lastModified)) { WebUtility.Return304(context); return; } //输出文件流 IStoreFile storeFile = storeProvider.GetFile(attachment.GetRelativePath(), attachment.FileName); if (storeFile == null) { WebUtility.Return404(context); return; } context.Response.Clear(); //context.Response.ClearHeaders(); //context.Response.Cache.VaryByParams["attachmentId"] = true; string fileExtension = attachment.FileName.Substring(attachment.FileName.LastIndexOf('.') + 1); string friendlyFileName = attachment.FriendlyFileName + (attachment.FriendlyFileName.EndsWith(fileExtension) ? "" : "." + fileExtension); SetResponsesDetails(context, attachment.ContentType, friendlyFileName, lastModified); DefaultStoreFile fileSystemFile = storeFile as DefaultStoreFile; if (!fileSystemFile.FullLocalPath.StartsWith(@"\")) { //本地文件下载 context.Response.TransmitFile(fileSystemFile.FullLocalPath); context.Response.End(); } else { context.Response.AddHeader("Content-Length", storeFile.Size.ToString("0")); context.Response.Buffer = false; context.Response.BufferOutput = false; using (Stream stream = fileSystemFile.OpenReadStream()) { if (stream == null) { WebUtility.Return404(context); return; } long bufferLength = fileSystemFile.Size <= DownloadFileHandlerBase.BufferLength ? fileSystemFile.Size : DownloadFileHandlerBase.BufferLength; byte[] buffer = new byte[bufferLength]; int readedSize; while ((readedSize = stream.Read(buffer, 0, (int)bufferLength)) > 0 && context.Response.IsClientConnected) { context.Response.OutputStream.Write(buffer, 0, readedSize); context.Response.Flush(); } //context.Response.OutputStream.Flush(); //context.Response.Flush(); stream.Close(); } context.Response.End(); } }
/// <summary> /// 图片列表 /// </summary> /// <param name="tenantTypeId">租户类型Id</param> /// <param name="associateId">附件关联Id</param> public ActionResult _ListImages(string tenantTypeId, long associateId = 0) { IUser user = UserContext.CurrentUser; if (user == null) { return new EmptyResult(); } IEnumerable<Attachment> attachments = null; AttachmentService<Attachment> attachementService = new AttachmentService<Attachment>(tenantTypeId); if (associateId == 0) { attachments = attachementService.GetTemporaryAttachments(user.UserId, tenantTypeId); } else { attachments = attachementService.GetsByAssociateId(associateId); } if (attachments != null && attachments.Count() > 0) { attachments = attachments.Where(n => n.MediaType == MediaType.Image); } TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId); ViewData["inlinedImageWidth"] = tenantAttachmentSettings.InlinedImageWidth; ViewData["inlinedImageHeight"] = tenantAttachmentSettings.InlinedImageHeight; return View(attachments); }
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); } else { var file = Request.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } IUser user = UserContext.CurrentUser; string tenantTypeId = Request["tenantTypeId"]; bool resize = true; long associateId = 0; long.TryParse(Context.Request["associateId"], out associateId); AttachmentService<Attachment> attachementService = new AttachmentService<Attachment>(tenantTypeId); long userId = user.UserId, ownerId = user.UserId; string userDisplayName = user.DisplayName; Result.OriginFileName = uploadFileName; try { //保存文件 string contentType = MimeTypeConfiguration.GetMimeType(uploadFileName); MemoryStream ms = new MemoryStream(uploadFileBytes); string friendlyFileName = uploadFileName.Substring(uploadFileName.LastIndexOf("\\") + 1); Attachment attachment = new Attachment(ms, contentType, friendlyFileName); attachment.UserId = userId; attachment.AssociateId = associateId; attachment.TenantTypeId = tenantTypeId; attachment.OwnerId = ownerId; attachment.UserDisplayName = userDisplayName; attachementService.Create(attachment, ms); ms.Dispose(); Result.Url = SiteUrls.Instance().AttachmentDirectUrl(attachment); Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public AttachmentsController(JobService jobs, AttachmentService attachments) { Jobs = jobs; Attachments = attachments; }
public ActionResult _DeleteAttachment(string tenantTypeId, long attachmentId) { IUser user = UserContext.CurrentUser; if (user == null) { return new EmptyResult(); } AttachmentService<Attachment> attachementService = new AttachmentService<Attachment>(tenantTypeId); attachementService.Delete(attachmentId); if (attachmentId > 0) return Json(new StatusMessageData(StatusMessageType.Success, "删除成功!")); else return Json(new StatusMessageData(StatusMessageType.Error, "删除失败!")); }
/// <summary> /// 附件列表 /// </summary> /// <param name="teantTypeId">租户类型id</param> /// <param name="threadId">帖子id</param> /// <returns>附件列表</returns> public ActionResult _ListAttachement(string teantTypeId, long threadId) { AttachmentService attachementService = new AttachmentService(teantTypeId); ViewData["Attachments"] = attachementService.GetsByAssociateId(threadId); return View(); }
/// <summary> /// 附件列表 /// </summary> /// <param name="associateId">附件关联Id</param> public ActionResult _ListAttachments(string tenantTypeId, long associateId = 0) { IUser user = UserContext.CurrentUser; if (user == null) { return new EmptyResult(); } List<List<object>> attachmentMessages = new List<List<object>>(); IEnumerable<Attachment> attachments = null; AttachmentService<Attachment> attachementService = new AttachmentService<Attachment>(tenantTypeId); if (associateId == 0) { attachments = attachementService.GetTemporaryAttachments(user.UserId, tenantTypeId); } else { attachments = attachementService.GetsByAssociateId(associateId); } if (attachments != null) { attachments = attachments.Where(n => n.MediaType != MediaType.Image); } return View(attachments); }
public string Process(string body, string tenantTypeId, long associateId, long userId) { //if (string.IsNullOrEmpty(body) || !body.Contains("[attach:")) // return body; //List<long> attachmentIds = new List<long>(); //Regex rg = new Regex(@"\[attach:(?<id>[\d]+)\]", RegexOptions.Multiline | RegexOptions.Singleline); //MatchCollection matches = rg.Matches(body); //if (matches != null) //{ // foreach (Match m in matches) // { // if (m.Groups["id"] == null || string.IsNullOrEmpty(m.Groups["id"].Value)) // continue; // long attachmentId = 0; // long.TryParse(m.Groups["id"].Value, out attachmentId); // if (attachmentId > 0 && !attachmentIds.Contains(attachmentId)) // attachmentIds.Add(attachmentId); // } //} //IEnumerable<ContentAttachment> attachments = new ContentAttachmentService().Gets(attachmentIds); //if (attachments != null && attachments.Count() > 0) //{ // IList<BBTag> bbTags = new List<BBTag>(); // string htmlTemplate = "<div class=\"tn-annexinlaid\"><a href=\"{3}\" rel=\"nofollow\">{0}</a>(<em>{1}</em>,<em>下载次数:{2}</em>)<a href=\"{3}\" rel=\"nofollow\">下载</a> </div>"; // //解析文本中附件 // foreach (var attachment in attachments) // { // bbTags.Add(AddBBTag(htmlTemplate, attachment)); // } // body = HtmlUtility.BBCodeToHtml(body, bbTags); //} //解析at用户 AtUserService atUserService = new AtUserService(tenantTypeId); body = atUserService.ResolveBodyForDetail(body, associateId, userId, AtUserTagGenerate); AttachmentService attachmentService = new AttachmentService(tenantTypeId); IEnumerable<Attachment> attachments = attachmentService.GetsByAssociateId(associateId); if (attachments != null && attachments.Count() > 0) { IList<BBTag> bbTags = new List<BBTag>(); string htmlTemplate = "<div class=\"tn-annexinlaid\"><a href=\"{3}\" rel=\"nofollow\">{0}</a>(<em>{1}</em>,<em>下载次数:{2}</em>)<a href=\"{3}\" rel=\"nofollow\">下载</a> </div>"; //解析文本中附件 IEnumerable<Attachment> attachmentsFiles = attachments.Where(n => n.MediaType != MediaType.Image); foreach (var attachment in attachmentsFiles) { bbTags.Add(AddBBTag(htmlTemplate, attachment)); } body = HtmlUtility.BBCodeToHtml(body, bbTags); } body = new EmotionService().EmoticonTransforms(body); body = DIContainer.Resolve<ParsedMediaService>().ResolveBodyForHtmlDetail(body, ParsedMediaTagGenerate); return body; }
/// <summary> /// 资讯详情页 /// </summary> public ActionResult ContentItemDetail(long contentItemId) { ContentItem contentItem = contentItemService.Get(contentItemId); if (contentItem == null || contentItem.User == null) { return HttpNotFound(); } //验证是否通过审核 long currentSpaceUserId = UserIdToUserNameDictionary.GetUserId(contentItem.User.UserName); if (!authorizer.IsAdministrator(CmsConfig.Instance().ApplicationId) && contentItem.UserId != currentSpaceUserId && (int)contentItem.AuditStatus < (int)(new AuditService().GetPubliclyAuditStatus(CmsConfig.Instance().ApplicationId))) return Redirect(SiteUrls.Instance().SystemMessage(TempData, new SystemMessageViewModel { Title = "尚未通过审核", Body = "由于当前资讯尚未通过审核,您无法浏览当前内容。", StatusMessageType = StatusMessageType.Hint })); AttachmentService<Attachment> attachmentService = new AttachmentService<Attachment>(TenantTypeIds.Instance().ContentItem()); //更新浏览计数 CountService countService = new CountService(TenantTypeIds.Instance().ContentItem()); countService.ChangeCount(CountTypes.Instance().HitTimes(), contentItem.ContentItemId, contentItem.UserId, 1, true); if (UserContext.CurrentUser != null) { //创建访客记录 VisitService visitService = new VisitService(TenantTypeIds.Instance().ContentItem()); visitService.CreateVisit(UserContext.CurrentUser.UserId, UserContext.CurrentUser.DisplayName, contentItem.ContentItemId, contentItem.Title); } //设置SEO信息 pageResourceManager.InsertTitlePart(contentItem.Title); List<string> keywords = new List<string>(); keywords.AddRange(contentItem.TagNames); string keyword = string.Join(" ", keywords.Distinct()); keyword += " " + string.Join(" ", ClauseScrubber.TitleToKeywords(contentItem.Title)); pageResourceManager.SetMetaOfKeywords(keyword); pageResourceManager.SetMetaOfDescription(contentItem.Summary); return View(contentItem); }
public ActionResult _BuyAttachement(string tenantTypeId, long attachementId) { AttachmentService attachementService = new AttachmentService(tenantTypeId); Attachment attachment = attachementService.Get(attachementId); if (attachment == null) return Content(string.Empty); return View(attachment); }
/// <summary> /// 微博图片模式数据页 /// </summary> /// <param name="pageIndex"></param> /// <param name="tenantTypeId"></param> /// <param name="mediaType"></param> /// <param name="isOriginal"></param> /// <param name="sortBy"></param> /// <returns></returns> public ActionResult _Waterfall(int pageIndex = 1, string tenantTypeId = "", MediaType? mediaType = null, bool? isOriginal = null, SortBy_Microblog sortBy = SortBy_Microblog.DateCreated) { //获取微博分页数据 PagingDataSet<MicroblogEntity> MicroblogEntities = microblogService.GetPagings(pageIndex, tenantTypeId: TenantTypeIds.Instance().User(), mediaType: mediaType, sortBy: sortBy); //获取微博图片 AttachmentService<Attachment> attachementService = new AttachmentService<Attachment>(TenantTypeIds.Instance().Microblog()); foreach (var MicroblogEntity in MicroblogEntities.Where(n => n.HasPhoto)) { IEnumerable<Attachment> attachments = attachementService.GetsByAssociateId(MicroblogEntity.MicroblogId); if (attachments != null && attachments.Count<Attachment>() > 0) { MicroblogEntity.ImageWidth = attachments.First().Width; MicroblogEntity.ImageUrl = SiteUrls.Instance().ImageUrl(attachments.First(), TenantTypeIds.Instance().Microblog(), ImageSizeTypeKeys.Instance().Big()); } } //设置当前登录用户对当前页用户的关注情况 //如果当前登录用户关注了该用户 return View(MicroblogEntities.AsEnumerable<MicroblogEntity>()); }
/// <summary> /// 获取图片的URL /// </summary> /// <param name="attachmentId">附件Id</param> /// <param name="tenantTypeId">租户类型Id</param> /// <param name="imageSizeTypeKey">尺寸类型(通过ImageSizeTypeKeys类获取)</param> /// <param name="enableClientCaching">是否使用客户端缓存</param> /// <returns></returns> public string ImageUrl(long attachmentId, string tenantTypeId, string imageSizeTypeKey, bool enableClientCaching = true) { if (attachmentId <= 0) { return WebUtility.ResolveUrl("~/Themes/Shared/Styles/Images/default_img.png"); } AttachmentService<Attachment> attachmentService = new AttachmentService<Attachment>(tenantTypeId); Attachment attachment = attachmentService.Get(attachmentId); return ImageUrl(attachment, tenantTypeId, imageSizeTypeKey, enableClientCaching); }
/// <summary> /// 设置标题图 /// </summary> /// <param name="tenantTypeId">租户类型Id</param> /// <param name="associateId">关联附件Id</param> /// <param name="attachmentIds">已经选中的附件Id</param> /// <param name="htmlFieldName">隐藏域全名称</param> /// <param name="isMultiSelect">是否多选</param> /// <param name="maxSelect">最大选择数量</param> public ActionResult _SetTitleImage(string tenantTypeId, long associateId = 0, string htmlFieldName = "", bool isMultiSelect = false, string attachmentIds = "", int maxSelect = 0) { IUser user = UserContext.CurrentUser; if (user == null) { return Redirect(SiteUrls.Instance().Login()); } AttachmentService<Attachment> attachementService = new AttachmentService<Attachment>(tenantTypeId); IEnumerable<Attachment> attachments = null; if (associateId == 0) { attachments = attachementService.GetTemporaryAttachments(user.UserId, tenantTypeId); } else { attachments = attachementService.GetsByAssociateId(associateId); } IEnumerable<Attachment> images = attachments.Where(n => n.MediaType == MediaType.Image); ViewData["associateId"] = associateId; ViewData["htmlFieldName"] = htmlFieldName; ViewData["isMultiSelect"] = isMultiSelect; ViewData["attachmentIds"] = attachmentIds; ViewData["tenantTypeId"] = tenantTypeId; ViewData["maxSelect"] = maxSelect; return View(); }
public JsonResult _SavePrice(string tenantTypeId) { string price = Request.Form.GetString("Price", string.Empty).Trim(); int priceValue = 0; if (price != "0" && price != string.Empty) { int.TryParse(price, out priceValue); if (priceValue == 0) return Json(new StatusMessageData(StatusMessageType.Error, "请输入正整数")); } long attachementId = Request.Form.Get<long>("attachementId", 0); AttachmentService attachementService = new AttachmentService(tenantTypeId); Attachment attachment = attachementService.Get(attachementId); if (attachment == null) return Json(new StatusMessageData(StatusMessageType.Error, "抱歉,找不到您所要出售的附件")); attachementService.UpdatePrice(attachementId, priceValue); return Json(new { price = priceValue }); }
/// <summary> /// 呈现已上传图片的列表 /// </summary> /// <param name="tenantTypeId">租户类型Id</param> /// <param name="attachmentIds">附件Id</param> /// <param name="associateId">关联附件Id</param> /// <returns></returns> public ActionResult _TitleImageList(string tenantTypeId, string attachmentIds, long associateId) { AttachmentService<Attachment> attachementService = new AttachmentService<Attachment>(tenantTypeId); IEnumerable<Attachment> attachments = null; if (associateId == 0) { attachments = attachementService.GetTemporaryAttachments(UserContext.CurrentUser.UserId, tenantTypeId); } else { attachments = attachementService.GetsByAssociateId(associateId); } IEnumerable<Attachment> images = attachments.Where(n => n.MediaType == MediaType.Image); ViewData["_attachmentIds"] = attachmentIds; ViewData["_tenantTypeId"] = tenantTypeId; return View(images); }
public ActionResult UploadFile(string tenantTypeId, string requestName, long associateId, bool resize = false) { IUser user = UserContext.CurrentUser; if (user == null) { return new EmptyResult(); } AttachmentService<Attachment> attachementService = new AttachmentService<Attachment>(tenantTypeId); long userId = user.UserId, ownerId = user.UserId; string userDisplayName = user.DisplayName; long attachmentId = 0; if (Request.Files.Count > 0 && !string.IsNullOrEmpty(Request.Files[requestName].FileName)) { HttpPostedFileBase postFile = Request.Files[requestName]; string fileName = postFile.FileName; TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId); //图片类型支持:gif,jpg,jpeg,png string[] picTypes = { ".gif", ".jpg", ".jpeg", ".png" }; if (!tenantAttachmentSettings.ValidateFileExtensions(fileName) && !picTypes.Contains(fileName.Substring(fileName.LastIndexOf('.')))) { throw new ExceptionFacade(string.Format("只允许上传后缀名为{0}的文件", tenantAttachmentSettings.AllowedFileExtensions)); } if (!tenantAttachmentSettings.ValidateFileLength(postFile.ContentLength)) { throw new ExceptionFacade(string.Format("文件大小不允许超过{0}", tenantAttachmentSettings.MaxAttachmentLength)); } string contentType = MimeTypeConfiguration.GetMimeType(postFile.FileName); Attachment attachment = new Attachment(postFile, contentType); attachment.UserId = userId; attachment.AssociateId = associateId; attachment.TenantTypeId = tenantTypeId; attachment.OwnerId = ownerId; attachment.UserDisplayName = userDisplayName; using (Stream stream = postFile.InputStream) { attachementService.Create(attachment, stream); } attachmentId = attachment.AttachmentId; } return Json(new { AttachmentId = attachmentId }); }
/// <summary> /// 下载远程图片 /// </summary> /// <param name="imageUrl">将要下载的图片地址</param> /// <param name="microblogId">微博Id</param> private void DownloadRemoteImage(string imageUrl, long microblogId) { if (UserContext.CurrentUser == null || microblogId <= 0 || string.IsNullOrEmpty(imageUrl)) return; try { WebRequest webRequest = WebRequest.Create(SiteUrls.FullUrl(imageUrl)); HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); Stream stream = httpWebResponse.GetResponseStream(); MemoryStream ms = new MemoryStream(); stream.CopyTo(ms); string friendlyFileName = imageUrl.Substring(imageUrl.LastIndexOf("/") + 1); string contentType = MimeTypeConfiguration.GetMimeType(friendlyFileName); bool isImage = contentType.StartsWith("image"); if (!isImage || stream == null || !stream.CanRead) return; Attachment attachment = new Attachment(ms, contentType, friendlyFileName); attachment.FileLength = httpWebResponse.ContentLength; attachment.AssociateId = microblogId; attachment.UserId = UserContext.CurrentUser.UserId; attachment.UserDisplayName = UserContext.CurrentUser.DisplayName; attachment.TenantTypeId = TenantTypeIds.Instance().Microblog(); var attachmentService = new AttachmentService(TenantTypeIds.Instance().Microblog()); attachmentService.Create(attachment, ms); ms.Dispose(); ms.Close(); } catch { } }
public AttachmentsController(AttachmentService attachments) { Attachments = attachments; }